@sweet-player/core 0.2.1 → 0.4.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.
@@ -1,43 +1,44 @@
1
- "use strict";var SweetPlayer=(()=>{var ii=Object.defineProperty;var El=Object.getOwnPropertyDescriptor;var Tl=Object.getOwnPropertyNames;var Sl=Object.prototype.hasOwnProperty;var xl=(n,e)=>{for(var t in e)ii(n,t,{get:e[t],enumerable:!0})},Al=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Tl(e))!Sl.call(n,i)&&i!==t&&ii(n,i,{get:()=>e[i],enumerable:!(s=El(e,i))||s.enumerable});return n};var Ll=n=>Al(ii({},"__esModule",{value:!0}),n);var Wu={};xl(Wu,{default:()=>Yu});var Jt=class{constructor(){this.listeners=new Map}on(e,t){let s=this.listeners.get(e);return s||(s=new Set,this.listeners.set(e,s)),s.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(s=>s(t))}removeAll(){this.listeners.clear()}};var O=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},Il=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=bl},bl=Number.MAX_SAFE_INTEGER||9007199254740991,K=(function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n})({}),I=(function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.ASSET_LIST_LOAD_ERROR="assetListLoadError",n.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",n.ASSET_LIST_PARSING_ERROR="assetListParsingError",n.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.ATTACH_MEDIA_ERROR="attachMediaError",n.UNKNOWN="unknown",n})({}),m=(function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.MEDIA_ENDED="hlsMediaEnded",n.STALL_RESOLVED="hlsStallResolved",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFERED_TO_END="hlsBufferedToEnd",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n.ASSET_LIST_LOADING="hlsAssetListLoading",n.ASSET_LIST_LOADED="hlsAssetListLoaded",n.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",n.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",n.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",n.INTERSTITIAL_STARTED="hlsInterstitialStarted",n.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",n.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",n.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",n.INTERSTITIAL_ENDED="hlsInterstitialEnded",n.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",n.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",n.EVENT_CUE_ENTER="hlsEventCueEnter",n})({}),Q={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},N={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},et=class{constructor(e,t=0,s=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_=s}sample(e,t){let s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*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_}},bi=class{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new et(e),this.fast_=new et(t),this.defaultTTFB_=i,this.ttfb_=new et(e)}update(e,t){let{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new et(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new et(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new et(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){let t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function Rl(n,e,t){return(e=Dl(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function ie(){return ie=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(n[s]=t[s])}return n},ie.apply(null,arguments)}function yn(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,s)}return t}function te(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?yn(Object(t),!0).forEach(function(s){Rl(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):yn(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function _l(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Dl(n){var e=_l(n,"string");return typeof e=="symbol"?e:e+""}var Ie=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 s=`[${e}]:`;this.trace=tt,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},tt=function(){},Pl={trace:tt,debug:tt,log:tt,warn:tt,info:tt,error:tt};function Ri(){return ie({},Pl)}function kl(n,e){let t=self.console[n];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${n}] >`):tt}function vn(n,e,t){return e[n]?e[n].bind(e):kl(n,t)}var _i=Ri();function Cl(n,e,t){let s=Ri();if(typeof console=="object"&&n===!0||typeof n=="object"){let i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=vn(r,n,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch{return Ri()}i.forEach(r=>{_i[r]=vn(r,n)})}else ie(_i,s);return s}var se=_i;function st(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function wl(n){return typeof self<"u"&&n===self.ManagedMediaSource}function Da(n,e){let t=Object.keys(n),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(a=>s.indexOf(a)===-1)}function Pe(n,e=!1){if(typeof TextDecoder<"u"){let l=new TextDecoder("utf-8").decode(n);if(e){let h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}let t=n.length,s,i,r,a="",o=0;for(;o<t;){if(s=n[o++],s===0&&e)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:i=n[o++],a+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=n[o++],r=n[o++],a+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return a}function ye(n){let e="";for(let t=0;t<n.length;t++){let s=n[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function Pa(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Ml(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ri={exports:{}},En;function Ol(){return En||(En=1,(function(n,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return h.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):l;var f=o.parseURL(c);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(p.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)p.path=f.path,u.params||(p.params=f.params,u.query||(p.query=f.query));else{var y=f.path,v=y.substring(0,y.lastIndexOf("/")+1)+u.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=h.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(a,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};n.exports=o})()})(ri)),ri.exports}var Yr=Ol(),Ut=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}}},re={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Ts=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,Fl(this,"stats")}setByteRange(e,t){let s=e.split("@",2),i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}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={[re.AUDIO]:null,[re.VIDEO]:null,[re.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 Ut),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Yr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[re.AUDIO]=null,e[re.VIDEO]=null,e[re.AUDIOVIDEO]=null}};function ce(n){return n.sn!=="initSegment"}var Ot=class extends Ts{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(O(e)&&O(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 s=Object.keys(t);if(s.length===1){let i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=O(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 s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[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(!O(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ce(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 s;let i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,a=!1){let{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:a};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}},Di=class extends Ts{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function ka(n,e){let t=Object.getPrototypeOf(n);if(t){let s=Object.getOwnPropertyDescriptor(t,e);return s||ka(t,e)}}function Fl(n,e){let t=ka(n,e);t&&(t.enumerable=!0,Object.defineProperty(n,e,t))}var Tn=Math.pow(2,32)-1,Nl=[].push,Ca={video:1,audio:2,id3:3,text:4};function he(n){return String.fromCharCode.apply(null,n)}function wa(n,e){let t=n[e]<<8|n[e+1];return t<0?65536+t:t}function W(n,e){let t=Ma(n,e);return t<0?4294967296+t:t}function Sn(n,e){let t=W(n,e);return t*=Math.pow(2,32),t+=W(n,e+4),t}function Ma(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function Bl(n){let e=n.byteLength;for(let t=0;t<e;){let s=W(n,t);if(s>8&&n[t+4]===109&&n[t+5]===111&&n[t+6]===111&&n[t+7]===102)return!0;t=s>1?t+s:e}return!1}function X(n,e){let t=[];if(!e.length)return t;let s=n.byteLength;for(let i=0;i<s;){let r=W(n,i),a=he(n.subarray(i+4,i+8)),o=r>1?i+r:s;if(a===e[0])if(e.length===1)t.push(n.subarray(i+8,o));else{let c=X(n.subarray(i+8,o),e.slice(1));c.length&&Nl.apply(t,c)}i=o}return t}function Ul(n){let e=[],t=n[0],s=8,i=W(n,s);s+=4;let r=0,a=0;t===0?(r=W(n,s),a=W(n,s+4),s+=8):(r=Sn(n,s),a=Sn(n,s+8),s+=16),s+=2;let o=n.length+a,c=wa(n,s);s+=2;for(let l=0;l<c;l++){let h=s,d=W(n,h);h+=4;let u=d&2147483647;if((d&2147483648)>>>31===1)return se.warn("SIDX has hierarchical references (not supported)"),null;let g=W(n,h);h+=4,e.push({referenceSize:u,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+u-1}}),o+=u,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function Oa(n){let e=[],t=X(n,["moov","trak"]);for(let i=0;i<t.length;i++){let r=t[i],a=X(r,["tkhd"])[0];if(a){let o=a[0],c=W(a,o===0?12:20),l=X(r,["mdia","mdhd"])[0];if(l){o=l[0];let h=W(l,o===0?12:20),d=X(r,["mdia","hdlr"])[0];if(d){let u=he(d.subarray(8,12)),f={soun:re.AUDIO,vide:re.VIDEO}[u],g=X(r,["mdia","minf","stbl","stsd"])[0],p=$l(g);f?(e[c]={timescale:h,type:f,stsd:p},e[f]=te({timescale:h,id:c},p)):e[c]={timescale:h,type:u,stsd:p}}}}}return X(n,["moov","mvex","trex"]).forEach(i=>{let r=W(i,4),a=e[r];a&&(a.default={duration:W(i,12),flags:W(i,20)})}),e}function $l(n){let e=n.subarray(8),t=e.subarray(86),s=he(e.subarray(4,8)),i=s,r,a=s==="enca"||s==="encv";if(a){let l=X(e,[s])[0].subarray(s==="enca"?28:78);X(l,["sinf"]).forEach(d=>{let u=X(d,["schm"])[0];if(u){let f=he(u.subarray(4,8));if(f==="cbcs"||f==="cenc"){let g=X(d,["frma"])[0];g&&(i=he(g))}}})}let o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{let c=X(t,["avcC"])[0];c&&c.length>3&&(i+="."+ts(c[1])+ts(c[2])+ts(c[3]),r=es(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let c=X(e,[s])[0],l=X(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=ni(l,h),h+=2;let d=l[h++];if(d&128&&(h+=2),d&64&&(h+=l[h++]),l[h++]!==4)break;h=ni(l,h);let u=l[h++];if(u===64)i+="."+ts(u);else break;if(h+=12,l[h++]!==5)break;h=ni(l,h);let f=l[h++],g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[h]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{let c=X(t,["hvcC"])[0];if(c&&c.length>12){let l=c[1],h=["","A","B","C"][l>>6],d=l&31,u=W(c,2),f=(l&32)>>5?"H":"L",g=c[12],p=c.subarray(6,12);i+="."+h+d,i+="."+Gl(u).toString(16).toUpperCase(),i+="."+f+g;let y="";for(let v=p.length;v--;){let E=p[v];(E||y)&&(y="."+E.toString(16).toUpperCase()+y)}i+=y}r=es(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=es(i,t)||i;break}case"vp09":{let c=X(t,["vpcC"])[0];if(c&&c.length>6){let l=c[4],h=c[5],d=c[6]>>4&15;i+="."+Ke(l)+"."+Ke(h)+"."+Ke(d)}break}case"av01":{let c=X(t,["av1C"])[0];if(c&&c.length>2){let l=c[1]>>>5,h=c[1]&31,d=c[2]>>>7?"H":"M",u=(c[2]&64)>>6,f=(c[2]&32)>>5,g=l===2&&u?f?12:10:u?10:8,p=(c[2]&16)>>4,y=(c[2]&8)>>3,v=(c[2]&4)>>2,E=c[2]&3;i+="."+l+"."+Ke(h)+d+"."+Ke(g)+"."+p+"."+y+v+E+"."+Ke(1)+"."+Ke(1)+"."+Ke(1)+"."+0,r=es("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:r}}function es(n,e){let t=X(e,["dvvC"]),s=t.length?t[0]:X(e,["dvcC"])[0];if(s){let i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return n+"."+Ke(i)+"."+Ke(r)}}function Gl(n){let e=0;for(let t=0;t<32;t++)e|=(n>>t&1)<<31-t;return e>>>0}function ni(n,e){let t=e+5;for(;n[e++]&128&&e<t;);return e}function ts(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function Ke(n){return(n<10?"0":"")+n}function Kl(n,e){if(!n||!e)return;let t=e.keyId;t&&e.isCommonEncryption&&Fa(n,(s,i)=>{let r=s.subarray(8,24);r.some(a=>a!==0)||(se.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${ye(r)} -> ${ye(t)}`),s.set(t,8))})}function Vl(n){let e=[];return Fa(n,t=>e.push(t.subarray(8,24))),e}function Fa(n,e){X(n,["moov","trak"]).forEach(s=>{let i=X(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;let r=i.subarray(8),a=X(r,["enca"]),o=a.length>0;o||(a=X(r,["encv"])),a.forEach(c=>{let l=o?c.subarray(28):c.subarray(78);X(l,["sinf"]).forEach(d=>{let u=Na(d);u&&e(u,o)})})})}function Na(n){let e=X(n,["schm"])[0];if(e){let t=he(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let s=X(n,["schi","tenc"])[0];if(s)return s}}}function Hl(n,e,t){let s={},i=X(n,["moof","traf"]);for(let r=0;r<i.length;r++){let a=i[r],o=X(a,["tfhd"])[0],c=W(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});let h=s[c],d=X(a,["tfdt"])[0];if(d){let T=d[0],S=W(d,4);T===1&&(S===Tn?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Tn+1,S+=W(d,8))),O(S)&&(!O(h.start)||S<h.start)&&(h.start=S)}let u=l.default,f=W(o,0)|u?.flags,g=u?.duration||0;f&8&&(f&2?g=W(o,12):g=W(o,8));let p=X(a,["trun"]),y=h.start||0,v=0,E=g;for(let T=0;T<p.length;T++){let S=p[T],x=W(S,4),_=h.sampleCount;h.sampleCount+=x;let A=S[3]&1,R=S[3]&4,b=S[2]&1,L=S[2]&2,P=S[2]&4,M=S[2]&8,B=8,V=x;for(A&&(B+=4),R&&x&&(!(S[B+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=_),B+=4,b?(E=W(S,B),B+=4):E=g,L&&(B+=4),M&&(B+=4),y+=E,v+=E,V--);V--;)b?(E=W(S,B),B+=4):E=g,L&&(B+=4),P&&(S[B+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(V+1),h.keyFrameStart=y),B+=4),M&&(B+=4),y+=E,v+=E;!v&&g&&(v+=g*x)}h.duration+=v}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,a=0,o=X(n,["sidx"]);for(let c=0;c<o.length;c++){let l=Ul(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);let h=l.references.reduce((d,u)=>d+u.info.duration||0,0);a=Math.max(a,h+l.earliestPresentationTime/l.timescale)}}a&&O(a)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=a*s[c].timescale-s[c].start)})}return s}function Yl(n){let e={valid:null,remainder:null},t=X(n,["moof"]);if(t.length<2)return e.remainder=n,e;let s=t[t.length-1];return e.valid=n.slice(0,s.byteOffset-8),e.remainder=n.slice(s.byteOffset-8),e}function we(n,e){let t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function xn(n,e){let t=[],s=e.samples,i=e.timescale,r=e.id,a=!1;return X(s,["moof"]).map(c=>{let l=c.byteOffset-8;X(c,["traf"]).map(d=>{let u=X(d,["tfdt"]).map(f=>{let g=f[0],p=W(f,4);return g===1&&(p*=Math.pow(2,32),p+=W(f,8)),p/i})[0];return u!==void 0&&(n=u),X(d,["tfhd"]).map(f=>{let g=W(f,4),p=W(f,0)&16777215,y=(p&1)!==0,v=(p&2)!==0,E=(p&8)!==0,T=0,S=(p&16)!==0,x=0,_=(p&32)!==0,A=8;g===r&&(y&&(A+=8),v&&(A+=4),E&&(T=W(f,A),A+=4),S&&(x=W(f,A),A+=4),_&&(A+=4),e.type==="video"&&(a=Ws(e.codec)),X(d,["trun"]).map(R=>{let b=R[0],L=W(R,0)&16777215,P=(L&1)!==0,M=0,B=(L&4)!==0,V=(L&256)!==0,U=0,k=(L&512)!==0,$=0,F=(L&1024)!==0,G=(L&2048)!==0,Y=0,C=W(R,4),w=8;P&&(M=W(R,w),w+=4),B&&(w+=4);let j=M+l;for(let ee=0;ee<C;ee++){if(V?(U=W(R,w),w+=4):U=T,k?($=W(R,w),w+=4):$=x,F&&(w+=4),G&&(b===0?Y=W(R,w):Y=Ma(R,w),w+=4),e.type===re.VIDEO){let z=0;for(;z<$;){let Z=W(s,j);if(j+=4,Wl(a,s[j])){let Ee=s.subarray(j,j+Z);Wr(Ee,a?2:1,n+Y/i,t)}j+=Z,z+=Z+4}}n+=U/i}}))})})}),t}function Ws(n){if(!n)return!1;let e=n.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Wl(n,e){if(n){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Wr(n,e,t,s){let i=Ba(n),r=0;r+=e;let a=0,o=0,c=0;for(;r<i.length;){a=0;do{if(r>=i.length)break;c=i[r++],a+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);let l=i.length-r,h=r;if(o<l)r+=o;else if(o>l){se.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(i[h++]===181){let u=wa(i,h);if(h+=2,u===49){let f=W(i,h);if(h+=4,f===1195456820){let g=i[h++];if(g===3){let p=i[h++],y=31&p,v=64&p,E=v?2+y*3:0,T=new Uint8Array(E);if(v){T[0]=p;for(let S=1;S<E;S++)T[S]=i[h++]}s.push({type:g,payloadType:a,pts:t,bytes:T})}}}}}else if(a===5&&o>16){let d=[];for(let g=0;g<16;g++){let p=i[h++].toString(16);d.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&d.push("-")}let u=o-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=i[h++];s.push({payloadType:a,pts:t,uuid:d.join(""),userData:Pe(f),userDataBytes:f})}}}function Ba(n){let e=n.byteLength,t=[],s=1;for(;s<e-2;)n[s]===0&&n[s+1]===0&&n[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return n;let i=e-t.length,r=new Uint8Array(i),a=0;for(s=0;s<i;a++,s++)a===t[0]&&(a++,t.shift()),r[s]=n[a];return r}function ql(n){let e=n[0],t="",s="",i=0,r=0,a=0,o=0,c=0,l=0;if(e===0){for(;he(n.subarray(l,l+1))!=="\0";)t+=he(n.subarray(l,l+1)),l+=1;for(t+=he(n.subarray(l,l+1)),l+=1;he(n.subarray(l,l+1))!=="\0";)s+=he(n.subarray(l,l+1)),l+=1;s+=he(n.subarray(l,l+1)),l+=1,i=W(n,12),r=W(n,16),o=W(n,20),c=W(n,24),l=28}else if(e===1){l+=4,i=W(n,l),l+=4;let d=W(n,l);l+=4;let u=W(n,l);for(l+=4,a=2**32*d+u,Il(a)||(a=Number.MAX_SAFE_INTEGER,se.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=W(n,l),l+=4,c=W(n,l),l+=4;he(n.subarray(l,l+1))!=="\0";)t+=he(n.subarray(l,l+1)),l+=1;for(t+=he(n.subarray(l,l+1)),l+=1;he(n.subarray(l,l+1))!=="\0";)s+=he(n.subarray(l,l+1)),l+=1;s+=he(n.subarray(l,l+1)),l+=1}let h=n.subarray(l,n.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function jl(n,...e){let t=e.length,s=8,i=t;for(;i--;)s+=e[i].byteLength;let r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(n,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function zl(n,e,t){if(n.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),jl([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,t)}function Xl(n){let e=[];if(n instanceof ArrayBuffer){let t=n.byteLength,s=0;for(;s+32<t;){let i=new DataView(n,s),r=Ql(i);e.push(r),s+=r.size}}return e}function Ql(n){let e=n.getUint32(0),t=n.byteOffset,s=n.byteLength;if(s<e)return{offset:t,size:s};if(n.getUint32(4)!==1886614376)return{offset:t,size:e};let r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};let a=n.buffer,o=ye(new Uint8Array(a,t+12,16)),c=null,l=null,h=0;if(r===0)h=28;else{let u=n.getUint32(28);if(!u||s<32+u*16)return{offset:t,size:e};c=[];for(let f=0;f<u;f++)c.push(new Uint8Array(a,t+32+f*16,16));h=32+u*16}if(!h)return{offset:t,size:e};let d=n.getUint32(h);return e-32<d?{offset:t,size:e}:(l=new Uint8Array(a,t+h+4,d),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}var Ua=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),_t={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function qr(n,e){let t=_t[e];return!!t&&!!t[n.slice(0,4)]}function $t(n,e,t=!0){return!n.split(",").some(s=>!jr(s,e,t))}function jr(n,e,t=!0){var s;let i=st(t);return(s=i?.isTypeSupported(Gt(n,e)))!=null?s:!1}function Gt(n,e){return`${e}/mp4;codecs=${n}`}function An(n){if(n){let e=n.substring(0,4);return _t.video[e]}return 2}function Ss(n){let e=Ua();return n.split(",").reduce((t,s)=>{let r=e&&Ws(s)?9:_t.video[s];return r?(r*2+t)/(t?3:2):(_t.audio[s]+t)/(t?2:1)},0)}var ai={};function Zl(n,e=!0){if(ai[n])return ai[n];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[n];for(let i=0;i<t.length;i++){var s;if(jr(t[i],"audio",e))return ai[n]=t[i],t[i];if(t[i]==="mp3"&&(s=st(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return n}var Jl=/flac|opus|mp4a\.40\.34/i;function xs(n,e=!0){return n.replace(Jl,t=>Zl(t.toLowerCase(),e))}function ec(n,e){let t=[];if(n){let s=n.split(",");for(let i=0;i<s.length;i++)qr(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function fs(n,e){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1)&&(Ln(n,"audio")||Ln(n,"video")))return n;if(e){let t=e.split(",");if(t.length>1){if(n){for(let s=t.length;s--;)if(t[s].substring(0,4)===n.substring(0,4))return t[s]}return t[0]}}return e||n}function Ln(n,e){return qr(n,e)&&jr(n,e)}function tc(n){let e=n.split(",");for(let t=0;t<e.length;t++){let s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function sc(n){if(n.startsWith("av01.")){let e=n.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return n}function In(n){let e=st(n)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Pi(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var ic={supported:!0,powerEfficient:!0,smooth:!0},rc={supported:!1,smooth:!1,powerEfficient:!1},$a={supported:!0,configurations:[],decodingInfoResults:[ic]};function Ga(n,e){return{supported:!1,configurations:e,decodingInfoResults:[rc],error:n}}function nc(n,e,t,s,i,r){let a=n.videoCodec,o=n.audioCodec?n.audioGroups:null,c=r?.audioCodec,l=r?.channels,h=l?parseInt(l):c?1/0:2,d=null;if(o!=null&&o.length)try{o.length===1&&o[0]?d=e.groups[o[0]].channels:d=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(p=>{u[p]=(u[p]||0)+g.channels[p]})}return u},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(u=>Ws(u))||n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(s,30)||n.videoRange!=="SDR"&&n.videoRange!==t||n.bitrate>Math.max(i,8e6))||!!d&&O(h)&&Object.keys(d).some(u=>parseInt(u)>h)}function Ka(n,e,t,s={}){let i=n.videoCodec;if(!i&&!n.audioCodec||!t)return Promise.resolve($a);let r=[],a=ac(n),o=a.length,c=oc(n,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){let d={type:"media-source"};if(o&&(d.video=a[h%o]),l){d.audio=c[h%l];let u=d.audio.bitrate;d.video&&u&&(d.video.bitrate-=u)}r.push(d)}if(i){let h=navigator.userAgent;if(i.split(",").some(d=>Ws(d))&&Ua())return Promise.resolve(Ga(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{let d=cc(h);return s[d]||(s[d]=t.decodingInfo(h))})).then(h=>({supported:!h.some(d=>!d.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function ac(n){var e;let t=(e=n.videoCodec)==null?void 0:e.split(","),s=Va(n),i=n.width||640,r=n.height||480,a=n.frameRate||30,o=n.videoRange.toLowerCase();return t?t.map(c=>{let l={contentType:Gt(sc(c),"video"),width:i,height:r,bitrate:s,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function oc(n,e,t){var s;let i=(s=n.audioCodec)==null?void 0:s.split(","),r=Va(n);return i&&n.audioGroups?n.audioGroups.reduce((a,o)=>{var c;let l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,d)=>{if(d.groupId===o){let u=parseFloat(d.channels||"");i.forEach(f=>{let g={contentType:Gt(f,"audio"),bitrate:t?lc(f,r):r};u&&(g.channels=""+u),h.push(g)})}return h},a):a},[]):[]}function lc(n,e){if(e<=1)return 1;let t=128e3;return n==="ec-3"?t=768e3:n==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Va(n){return Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)/1e3)*1e3||1}function cc(n){let e="",{audio:t,video:s}=n;if(s){let i=Pi(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){let i=Pi(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}var ki=["NONE","TYPE-0","TYPE-1",null];function hc(n){return ki.indexOf(n)>-1}var As=["SDR","PQ","HLG"];function dc(n){return!!n&&As.indexOf(n)>-1}var gs={No:"",Yes:"YES",v2:"v2"};function bn(n){let{canSkipUntil:e,canSkipDateRanges:t,age:s}=n,i=s<e/2;return e&&i?t?gs.v2:gs.Yes:gs.No}var Ls=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},ft=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.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[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,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Rn(this._audioGroups,e)}hasSubtitleGroup(e){return Rn(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.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 Rn(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function uc(){if(typeof matchMedia=="function"){let n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return n.matches===!0}return!1}function fc(n,e){let t=!1,s=[];if(n&&(t=n!=="SDR",s=[n]),e){s=e.allowedVideoRanges||As.slice(0);let i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&uc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}var gc=n=>{let e=new WeakSet;return(t,s)=>{if(n&&(s=n(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ne=(n,e)=>JSON.stringify(n,gc(e));function mc(n,e,t,s,i){let r=Object.keys(n),a=s?.channels,o=s?.audioCodec,c=i?.videoCodec,l=a&&parseInt(a)===2,h=!1,d=!1,u=1/0,f=1/0,g=1/0,p=1/0,y=0,v=[],{preferHDR:E,allowedVideoRanges:T}=fc(e,i);for(let R=r.length;R--;){let b=n[r[R]];h||(h=b.channels[2]>0),u=Math.min(u,b.minHeight),f=Math.min(f,b.minFramerate),g=Math.min(g,b.minBitrate),T.filter(P=>b.videoRanges[P]>0).length>0&&(d=!0)}u=O(u)?u:0,f=O(f)?f:0;let S=Math.max(1080,u),x=Math.max(30,f);g=O(g)?g:t,t=Math.max(g,t),d||(e=void 0);let _=r.length>1;return{codecSet:r.reduce((R,b)=>{let L=n[b];if(b===R)return R;if(v=d?T.filter(P=>L.videoRanges[P]>0):[],_){if(L.minBitrate>t)return $e(b,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),R;if(!L.hasDefaultAudio)return $e(b,"no renditions with default or auto-select sound found"),R;if(o&&b.indexOf(o.substring(0,4))%5!==0)return $e(b,`audio codec preference "${o}" not found`),R;if(a&&!l){if(!L.channels[a])return $e(b,`no renditions with ${a} channel sound found (channels options: ${Object.keys(L.channels)})`),R}else if((!o||l)&&h&&L.channels[2]===0)return $e(b,"no renditions with stereo sound found"),R;if(L.minHeight>S)return $e(b,`min resolution of ${L.minHeight} > maximum of ${S}`),R;if(L.minFramerate>x)return $e(b,`min framerate of ${L.minFramerate} > maximum of ${x}`),R;if(!v.some(P=>L.videoRanges[P]>0))return $e(b,`no variants with VIDEO-RANGE of ${ne(v)} found`),R;if(c&&b.indexOf(c.substring(0,4))%5!==0)return $e(b,`video codec preference "${c}" not found`),R;if(L.maxScore<y)return $e(b,`max score of ${L.maxScore} < selected max of ${y}`),R}return R&&(Ss(b)>=Ss(R)||L.fragmentError>n[R].fragmentError)?R:(p=L.minIndex,y=L.maxScore,b)},void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}function $e(n,e){se.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function Ha(n){return n.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);let i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function pc(n,e,t,s){return n.slice(t,s+1).reduce((i,r,a)=>{if(!r.codecSet)return i;let o=r.audioGroups,c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);let l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,a),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;let d=e.groups[h];d&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?d.hasDefault:d.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(d.channels).forEach(u=>{c.channels[u]=(c.channels[u]||0)+d.channels[u]}))}),i},{})}function _n(n){if(!n)return n;let{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=n;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function He(n,e,t){if("attrs"in n){let s=e.indexOf(n);if(s!==-1)return s}for(let s=0;s<e.length;s++){let i=e[s];if(dt(n,i,t))return s}return-1}function dt(n,e,t){let{groupId:s,name:i,lang:r,assocLang:a,default:o}=n,c=n.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||yc(r,e.lang))&&(r===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in n)||vc(n.characteristics||"",e.characteristics))&&(t===void 0||t(n,e))}function yc(n,e="--"){return n.length===e.length?n===e:n.startsWith(e)||e.startsWith(n)}function vc(n,e=""){let t=n.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function ct(n,e){let{audioCodec:t,channels:s}=n;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Ec(n,e,t,s,i){let r=e[s],o=e.reduce((u,f,g)=>{let p=f.uri;return(u[p]||(u[p]=[])).push(g),u},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));let c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),d=Dn(e,s,u=>{if(u.videoRange!==c||u.frameRate!==l||u.codecSet.substring(0,4)!==h)return!1;let f=u.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return He(n,g,i)>-1});return d>-1?d:Dn(e,s,u=>{let f=u.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return He(n,g,i)>-1})}function Dn(n,e,t){for(let s=e;s>-1;s--)if(t(n[s]))return s;for(let s=e+1;s<n.length;s++)if(t(n[s]))return s;return-1}function Is(n,e){var t;return!!n&&n!==((t=e.loadLevelObj)==null?void 0:t.uri)}var Ci=class extends Ie{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;let{fragCurrent:i,partCurrent:r,hls:a}=this,{autoLevelEnabled:o,media:c}=a;if(!i||!c)return;let l=performance.now(),h=r?r.stats:i.stats,d=r?r.duration:i.duration,u=l-h.loading.start,f=a.minAutoLevel,g=i.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let y=p>-1&&p!==g,v=!!t||y;if(!v&&(c.paused||!c.playbackRate||!c.readyState))return;let E=a.mainForwardBufferInfo;if(!v&&E===null)return;let T=this.bwEstimator.getEstimateTTFB(),S=Math.abs(c.playbackRate);if(u<=Math.max(T,1e3*(d/(S*2))))return;let x=E?E.len/S:0,_=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&_>-1,R=this.getBwEstimate(),b=a.levels,L=b[g],P=Math.max(h.loaded,Math.round(d*(i.bitrate||L.averageBitrate)/8)),M=A?u-_:u;M<1&&A&&(M=Math.min(u,h.loaded*8/R));let B=A?h.loaded*1e3/M:0,V=T/1e3,U=B?(P-h.loaded)/B:P*8/R+V;if(U<=x)return;let k=B?B*8:R,$=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,F=this.hls.config.abrBandWidthUpFactor,G=Number.POSITIVE_INFINITY,Y;for(Y=g-1;Y>f;Y--){let ee=b[Y].maxBitrate,z=!b[Y].details||$;if(G=this.getTimeToLoadFrag(V,k,d*ee,z),G<Math.min(x,d+V))break}if(G>=U||G>d*10)return;A?this.bwEstimator.sample(u-Math.min(T,_),h.loaded):this.bwEstimator.sampleTTFB(u);let C=b[Y].maxBitrate;this.getBwEstimate()*F>C&&this.resetEstimator(C);let w=this.findBestLevel(C,f,Y,0,x,1,1);w>-1&&(Y=w),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
1
+ "use strict";var SweetPlayer=(()=>{var ni=Object.defineProperty;var bl=Object.getOwnPropertyDescriptor;var Rl=Object.getOwnPropertyNames;var _l=Object.prototype.hasOwnProperty;var Pl=(r,e)=>{for(var t in e)ni(r,t,{get:e[t],enumerable:!0})},Dl=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Rl(e))!_l.call(r,i)&&i!==t&&ni(r,i,{get:()=>e[i],enumerable:!(s=bl(e,i))||s.enumerable});return r};var kl=r=>Dl(ni({},"__esModule",{value:!0}),r);var Ju={};Pl(Ju,{default:()=>Zu});var es=class{constructor(){this.listeners=new Map}on(e,t){let s=this.listeners.get(e);return s||(s=new Set,this.listeners.set(e,s)),s.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(s=>s(t))}removeAll(){this.listeners.clear()}};var F=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Cl=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=wl},wl=Number.MAX_SAFE_INTEGER||9007199254740991,V=(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})({}),R=(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.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_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.UNKNOWN="unknown",r})({}),m=(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})({}),Q={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},B={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},tt=class{constructor(e,t=0,s=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_=s}sample(e,t){let s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*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_}},Ri=class{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new tt(e),this.fast_=new tt(t),this.defaultTTFB_=i,this.ttfb_=new tt(e)}update(e,t){let{slow_:s,fast_:i,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new tt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new tt(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new tt(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let s=8*t,i=e/1e3,n=s/i;this.fast_.sample(i,n),this.slow_.sample(i,n)}sampleTTFB(e){let t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function Ml(r,e,t){return(e=Fl(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function ie(){return ie=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(r[s]=t[s])}return r},ie.apply(null,arguments)}function Tr(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,s)}return t}function te(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Tr(Object(t),!0).forEach(function(s){Ml(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Tr(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}function Ol(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Fl(r){var e=Ol(r,"string");return typeof e=="symbol"?e:e+""}var Re=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 s=`[${e}]:`;this.trace=st,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},st=function(){},Nl={trace:st,debug:st,log:st,warn:st,info:st,error:st};function _i(){return ie({},Nl)}function Bl(r,e){let t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):st}function Sr(r,e,t){return e[r]?e[r].bind(e):Bl(r,t)}var Pi=_i();function $l(r,e,t){let s=_i();if(typeof console=="object"&&r===!0||typeof r=="object"){let i=["debug","log","info","warn","error"];i.forEach(n=>{s[n]=Sr(n,r,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch{return _i()}i.forEach(n=>{Pi[n]=Sr(n,r)})}else ie(Pi,s);return s}var se=Pi;function it(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ul(r){return typeof self<"u"&&r===self.ManagedMediaSource}function Ca(r,e){let t=Object.keys(r),s=Object.keys(e),i=t.length,n=s.length;return!i||!n||i===n&&!t.some(a=>s.indexOf(a)===-1)}function ke(r,e=!1){if(typeof TextDecoder<"u"){let l=new TextDecoder("utf-8").decode(r);if(e){let d=l.indexOf("\0");return d!==-1?l.substring(0,d):l}return l.replace(/\0/g,"")}let t=r.length,s,i,n,a="",o=0;for(;o<t;){if(s=r[o++],s===0&&e)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:i=r[o++],a+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=r[o++],n=r[o++],a+=String.fromCharCode((s&15)<<12|(i&63)<<6|(n&63)<<0);break}}return a}function ve(r){let e="";for(let t=0;t<r.length;t++){let s=r[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function wa(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Gl(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ri={exports:{}},xr;function Kl(){return xr||(xr=1,(function(r,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,d){if(d=d||{},c=c.trim(),l=l.trim(),!l){if(!d.alwaysNormalize)return c;var h=o.parseURL(c);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(l);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return d.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):l;var g=o.parseURL(c);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=i.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var p={scheme:g.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(p.netLoc=g.netLoc,u.path[0]!=="/"))if(!u.path)p.path=g.path,u.params||(p.params=g.params,u.query||(p.query=g.query));else{var y=g.path,v=y.substring(0,y.lastIndexOf("/")+1)+u.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=d.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(n,"");c.length!==(c=c.replace(a,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};r.exports=o})()})(ri)),ri.exports}var qn=Kl(),Ut=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}}},ne={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Ss=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,Vl(this,"stats")}setByteRange(e,t){let s=e.split("@",2),i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}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={[ne.AUDIO]:null,[ne.VIDEO]:null,[ne.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 Ut),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=qn.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[ne.AUDIO]=null,e[ne.VIDEO]=null,e[ne.AUDIOVIDEO]=null}};function de(r){return r.sn!=="initSegment"}var Ft=class extends Ss{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(F(e)&&F(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 s=Object.keys(t);if(s.length===1){let i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=F(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 s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[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(!F(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return de(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 s;let i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,n,a=!1){let{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:n,partial:a};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,n)}},Di=class extends Ss{constructor(e,t,s,i,n){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;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)}};function Ma(r,e){let t=Object.getPrototypeOf(r);if(t){let s=Object.getOwnPropertyDescriptor(t,e);return s||Ma(t,e)}}function Vl(r,e){let t=Ma(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}var Ar=Math.pow(2,32)-1,Hl=[].push,Oa={video:1,audio:2,id3:3,text:4};function ue(r){return String.fromCharCode.apply(null,r)}function Fa(r,e){let t=r[e]<<8|r[e+1];return t<0?65536+t:t}function W(r,e){let t=Na(r,e);return t<0?4294967296+t:t}function Lr(r,e){let t=W(r,e);return t*=Math.pow(2,32),t+=W(r,e+4),t}function Na(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Yl(r){let e=r.byteLength;for(let t=0;t<e;){let s=W(r,t);if(s>8&&r[t+4]===109&&r[t+5]===111&&r[t+6]===111&&r[t+7]===102)return!0;t=s>1?t+s:e}return!1}function X(r,e){let t=[];if(!e.length)return t;let s=r.byteLength;for(let i=0;i<s;){let n=W(r,i),a=ue(r.subarray(i+4,i+8)),o=n>1?i+n:s;if(a===e[0])if(e.length===1)t.push(r.subarray(i+8,o));else{let c=X(r.subarray(i+8,o),e.slice(1));c.length&&Hl.apply(t,c)}i=o}return t}function Wl(r){let e=[],t=r[0],s=8,i=W(r,s);s+=4;let n=0,a=0;t===0?(n=W(r,s),a=W(r,s+4),s+=8):(n=Lr(r,s),a=Lr(r,s+8),s+=16),s+=2;let o=r.length+a,c=Fa(r,s);s+=2;for(let l=0;l<c;l++){let d=s,h=W(r,d);d+=4;let u=h&2147483647;if((h&2147483648)>>>31===1)return se.warn("SIDX has hierarchical references (not supported)"),null;let f=W(r,d);d+=4,e.push({referenceSize:u,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+u-1}}),o+=u,d+=4,s=d}return{earliestPresentationTime:n,timescale:i,version:t,referencesCount:c,references:e}}function Ba(r){let e=[],t=X(r,["moov","trak"]);for(let i=0;i<t.length;i++){let n=t[i],a=X(n,["tkhd"])[0];if(a){let o=a[0],c=W(a,o===0?12:20),l=X(n,["mdia","mdhd"])[0];if(l){o=l[0];let d=W(l,o===0?12:20),h=X(n,["mdia","hdlr"])[0];if(h){let u=ue(h.subarray(8,12)),g={soun:ne.AUDIO,vide:ne.VIDEO}[u],f=X(n,["mdia","minf","stbl","stsd"])[0],p=ql(f);g?(e[c]={timescale:d,type:g,stsd:p},e[g]=te({timescale:d,id:c},p)):e[c]={timescale:d,type:u,stsd:p}}}}}return X(r,["moov","mvex","trex"]).forEach(i=>{let n=W(i,4),a=e[n];a&&(a.default={duration:W(i,12),flags:W(i,20)})}),e}function ql(r){let e=r.subarray(8),t=e.subarray(86),s=ue(e.subarray(4,8)),i=s,n,a=s==="enca"||s==="encv";if(a){let l=X(e,[s])[0].subarray(s==="enca"?28:78);X(l,["sinf"]).forEach(h=>{let u=X(h,["schm"])[0];if(u){let g=ue(u.subarray(4,8));if(g==="cbcs"||g==="cenc"){let f=X(h,["frma"])[0];f&&(i=ue(f))}}})}let o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{let c=X(t,["avcC"])[0];c&&c.length>3&&(i+="."+ss(c[1])+ss(c[2])+ss(c[3]),n=ts(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let c=X(e,[s])[0],l=X(c.subarray(28),["esds"])[0];if(l&&l.length>7){let d=4;if(l[d++]!==3)break;d=ai(l,d),d+=2;let h=l[d++];if(h&128&&(d+=2),h&64&&(d+=l[d++]),l[d++]!==4)break;d=ai(l,d);let u=l[d++];if(u===64)i+="."+ss(u);else break;if(d+=12,l[d++]!==5)break;d=ai(l,d);let g=l[d++],f=(g&248)>>3;f===31&&(f+=1+((g&7)<<3)+((l[d]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{let c=X(t,["hvcC"])[0];if(c&&c.length>12){let l=c[1],d=["","A","B","C"][l>>6],h=l&31,u=W(c,2),g=(l&32)>>5?"H":"L",f=c[12],p=c.subarray(6,12);i+="."+d+h,i+="."+jl(u).toString(16).toUpperCase(),i+="."+g+f;let y="";for(let v=p.length;v--;){let E=p[v];(E||y)&&(y="."+E.toString(16).toUpperCase()+y)}i+=y}n=ts(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=ts(i,t)||i;break}case"vp09":{let c=X(t,["vpcC"])[0];if(c&&c.length>6){let l=c[4],d=c[5],h=c[6]>>4&15;i+="."+He(l)+"."+He(d)+"."+He(h)}break}case"av01":{let c=X(t,["av1C"])[0];if(c&&c.length>2){let l=c[1]>>>5,d=c[1]&31,h=c[2]>>>7?"H":"M",u=(c[2]&64)>>6,g=(c[2]&32)>>5,f=l===2&&u?g?12:10:u?10:8,p=(c[2]&16)>>4,y=(c[2]&8)>>3,v=(c[2]&4)>>2,E=c[2]&3;i+="."+l+"."+He(d)+h+"."+He(f)+"."+p+"."+y+v+E+"."+He(1)+"."+He(1)+"."+He(1)+"."+0,n=ts("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:n}}function ts(r,e){let t=X(e,["dvvC"]),s=t.length?t[0]:X(e,["dvcC"])[0];if(s){let i=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return r+"."+He(i)+"."+He(n)}}function jl(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function ai(r,e){let t=e+5;for(;r[e++]&128&&e<t;);return e}function ss(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function He(r){return(r<10?"0":"")+r}function zl(r,e){if(!r||!e)return;let t=e.keyId;t&&e.isCommonEncryption&&$a(r,(s,i)=>{let n=s.subarray(8,24);n.some(a=>a!==0)||(se.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${ve(n)} -> ${ve(t)}`),s.set(t,8))})}function Xl(r){let e=[];return $a(r,t=>e.push(t.subarray(8,24))),e}function $a(r,e){X(r,["moov","trak"]).forEach(s=>{let i=X(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;let n=i.subarray(8),a=X(n,["enca"]),o=a.length>0;o||(a=X(n,["encv"])),a.forEach(c=>{let l=o?c.subarray(28):c.subarray(78);X(l,["sinf"]).forEach(h=>{let u=Ua(h);u&&e(u,o)})})})}function Ua(r){let e=X(r,["schm"])[0];if(e){let t=ue(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let s=X(r,["schi","tenc"])[0];if(s)return s}}}function Ql(r,e,t){let s={},i=X(r,["moof","traf"]);for(let n=0;n<i.length;n++){let a=i[n],o=X(a,["tfhd"])[0],c=W(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});let d=s[c],h=X(a,["tfdt"])[0];if(h){let T=h[0],x=W(h,4);T===1&&(x===Ar?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(x*=Ar+1,x+=W(h,8))),F(x)&&(!F(d.start)||x<d.start)&&(d.start=x)}let u=l.default,g=W(o,0)|u?.flags,f=u?.duration||0;g&8&&(g&2?f=W(o,12):f=W(o,8));let p=X(a,["trun"]),y=d.start||0,v=0,E=f;for(let T=0;T<p.length;T++){let x=p[T],A=W(x,4),_=d.sampleCount;d.sampleCount+=A;let S=x[3]&1,I=x[3]&4,b=x[2]&1,L=x[2]&2,D=x[2]&4,C=x[2]&8,$=8,H=A;for(S&&($+=4),I&&A&&(!(x[$+1]&1)&&d.keyFrameIndex===void 0&&(d.keyFrameIndex=_),$+=4,b?(E=W(x,$),$+=4):E=f,L&&($+=4),C&&($+=4),y+=E,v+=E,H--);H--;)b?(E=W(x,$),$+=4):E=f,L&&($+=4),D&&(x[$+1]&1||d.keyFrameIndex===void 0&&(d.keyFrameIndex=d.sampleCount-(H+1),d.keyFrameStart=y),$+=4),C&&($+=4),y+=E,v+=E;!v&&f&&(v+=f*A)}d.duration+=v}if(!Object.keys(s).some(n=>s[n].duration)){let n=1/0,a=0,o=X(r,["sidx"]);for(let c=0;c<o.length;c++){let l=Wl(o[c]);if(l!=null&&l.references){n=Math.min(n,l.earliestPresentationTime/l.timescale);let d=l.references.reduce((h,u)=>h+u.info.duration||0,0);a=Math.max(a,d+l.earliestPresentationTime/l.timescale)}}a&&F(a)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=a*s[c].timescale-s[c].start)})}return s}function Zl(r){let e={valid:null,remainder:null},t=X(r,["moof"]);if(t.length<2)return e.remainder=r,e;let s=t[t.length-1];return e.valid=r.slice(0,s.byteOffset-8),e.remainder=r.slice(s.byteOffset-8),e}function Oe(r,e){let t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function Ir(r,e){let t=[],s=e.samples,i=e.timescale,n=e.id,a=!1;return X(s,["moof"]).map(c=>{let l=c.byteOffset-8;X(c,["traf"]).map(h=>{let u=X(h,["tfdt"]).map(g=>{let f=g[0],p=W(g,4);return f===1&&(p*=Math.pow(2,32),p+=W(g,8)),p/i})[0];return u!==void 0&&(r=u),X(h,["tfhd"]).map(g=>{let f=W(g,4),p=W(g,0)&16777215,y=(p&1)!==0,v=(p&2)!==0,E=(p&8)!==0,T=0,x=(p&16)!==0,A=0,_=(p&32)!==0,S=8;f===n&&(y&&(S+=8),v&&(S+=4),E&&(T=W(g,S),S+=4),x&&(A=W(g,S),S+=4),_&&(S+=4),e.type==="video"&&(a=qs(e.codec)),X(h,["trun"]).map(I=>{let b=I[0],L=W(I,0)&16777215,D=(L&1)!==0,C=0,$=(L&4)!==0,H=(L&256)!==0,U=0,k=(L&512)!==0,G=0,N=(L&1024)!==0,K=(L&2048)!==0,Y=0,w=W(I,4),M=8;D&&(C=W(I,M),M+=4),$&&(M+=4);let j=C+l;for(let ee=0;ee<w;ee++){if(H?(U=W(I,M),M+=4):U=T,k?(G=W(I,M),M+=4):G=A,N&&(M+=4),K&&(b===0?Y=W(I,M):Y=Na(I,M),M+=4),e.type===ne.VIDEO){let z=0;for(;z<G;){let Z=W(s,j);if(j+=4,Jl(a,s[j])){let Se=s.subarray(j,j+Z);jn(Se,a?2:1,r+Y/i,t)}j+=Z,z+=Z+4}}r+=U/i}}))})})}),t}function qs(r){if(!r)return!1;let e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Jl(r,e){if(r){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function jn(r,e,t,s){let i=Ga(r),n=0;n+=e;let a=0,o=0,c=0;for(;n<i.length;){a=0;do{if(n>=i.length)break;c=i[n++],a+=c}while(c===255);o=0;do{if(n>=i.length)break;c=i[n++],o+=c}while(c===255);let l=i.length-n,d=n;if(o<l)n+=o;else if(o>l){se.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(i[d++]===181){let u=Fa(i,d);if(d+=2,u===49){let g=W(i,d);if(d+=4,g===1195456820){let f=i[d++];if(f===3){let p=i[d++],y=31&p,v=64&p,E=v?2+y*3:0,T=new Uint8Array(E);if(v){T[0]=p;for(let x=1;x<E;x++)T[x]=i[d++]}s.push({type:f,payloadType:a,pts:t,bytes:T})}}}}}else if(a===5&&o>16){let h=[];for(let f=0;f<16;f++){let p=i[d++].toString(16);h.push(p.length==1?"0"+p:p),(f===3||f===5||f===7||f===9)&&h.push("-")}let u=o-16,g=new Uint8Array(u);for(let f=0;f<u;f++)g[f]=i[d++];s.push({payloadType:a,pts:t,uuid:h.join(""),userData:ke(g),userDataBytes:g})}}}function Ga(r){let e=r.byteLength,t=[],s=1;for(;s<e-2;)r[s]===0&&r[s+1]===0&&r[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return r;let i=e-t.length,n=new Uint8Array(i),a=0;for(s=0;s<i;a++,s++)a===t[0]&&(a++,t.shift()),n[s]=r[a];return n}function ec(r){let e=r[0],t="",s="",i=0,n=0,a=0,o=0,c=0,l=0;if(e===0){for(;ue(r.subarray(l,l+1))!=="\0";)t+=ue(r.subarray(l,l+1)),l+=1;for(t+=ue(r.subarray(l,l+1)),l+=1;ue(r.subarray(l,l+1))!=="\0";)s+=ue(r.subarray(l,l+1)),l+=1;s+=ue(r.subarray(l,l+1)),l+=1,i=W(r,12),n=W(r,16),o=W(r,20),c=W(r,24),l=28}else if(e===1){l+=4,i=W(r,l),l+=4;let h=W(r,l);l+=4;let u=W(r,l);for(l+=4,a=2**32*h+u,Cl(a)||(a=Number.MAX_SAFE_INTEGER,se.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=W(r,l),l+=4,c=W(r,l),l+=4;ue(r.subarray(l,l+1))!=="\0";)t+=ue(r.subarray(l,l+1)),l+=1;for(t+=ue(r.subarray(l,l+1)),l+=1;ue(r.subarray(l,l+1))!=="\0";)s+=ue(r.subarray(l,l+1)),l+=1;s+=ue(r.subarray(l,l+1)),l+=1}let d=r.subarray(l,r.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:c,payload:d}}function tc(r,...e){let t=e.length,s=8,i=t;for(;i--;)s+=e[i].byteLength;let n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(r,4),i=0,s=8;i<t;i++)n.set(e[i],s),s+=e[i].byteLength;return n}function sc(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let n;s>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),tc([112,115,115,104],new Uint8Array([s,0,0,0]),r,n,i,a,t)}function ic(r){let e=[];if(r instanceof ArrayBuffer){let t=r.byteLength,s=0;for(;s+32<t;){let i=new DataView(r,s),n=nc(i);e.push(n),s+=n.size}}return e}function nc(r){let e=r.getUint32(0),t=r.byteOffset,s=r.byteLength;if(s<e)return{offset:t,size:s};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=ve(new Uint8Array(a,t+12,16)),c=null,l=null,d=0;if(n===0)d=28;else{let u=r.getUint32(28);if(!u||s<32+u*16)return{offset:t,size:e};c=[];for(let g=0;g<u;g++)c.push(new Uint8Array(a,t+32+g*16,16));d=32+u*16}if(!d)return{offset:t,size:e};let h=r.getUint32(d);return e-32<h?{offset:t,size:e}:(l=new Uint8Array(a,t+d+4,h),{version:n,systemId:o,kids:c,data:l,offset:t,size:e})}var Ka=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Pt={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function zn(r,e){let t=Pt[e];return!!t&&!!t[r.slice(0,4)]}function Gt(r,e,t=!0){return!r.split(",").some(s=>!Xn(s,e,t))}function Xn(r,e,t=!0){var s;let i=it(t);return(s=i?.isTypeSupported(Kt(r,e)))!=null?s:!1}function Kt(r,e){return`${e}/mp4;codecs=${r}`}function br(r){if(r){let e=r.substring(0,4);return Pt.video[e]}return 2}function xs(r){let e=Ka();return r.split(",").reduce((t,s)=>{let n=e&&qs(s)?9:Pt.video[s];return n?(n*2+t)/(t?3:2):(Pt.audio[s]+t)/(t?2:1)},0)}var oi={};function rc(r,e=!0){if(oi[r])return oi[r];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let i=0;i<t.length;i++){var s;if(Xn(t[i],"audio",e))return oi[r]=t[i],t[i];if(t[i]==="mp3"&&(s=it(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return r}var ac=/flac|opus|mp4a\.40\.34/i;function As(r,e=!0){return r.replace(ac,t=>rc(t.toLowerCase(),e))}function oc(r,e){let t=[];if(r){let s=r.split(",");for(let i=0;i<s.length;i++)zn(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function gs(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(Rr(r,"audio")||Rr(r,"video")))return r;if(e){let t=e.split(",");if(t.length>1){if(r){for(let s=t.length;s--;)if(t[s].substring(0,4)===r.substring(0,4))return t[s]}return t[0]}}return e||r}function Rr(r,e){return zn(r,e)&&Xn(r,e)}function lc(r){let e=r.split(",");for(let t=0;t<e.length;t++){let s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function cc(r){if(r.startsWith("av01.")){let e=r.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return r}function _r(r){let e=it(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 ki(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var dc={supported:!0,powerEfficient:!0,smooth:!0},hc={supported:!1,smooth:!1,powerEfficient:!1},Va={supported:!0,configurations:[],decodingInfoResults:[dc]};function Ha(r,e){return{supported:!1,configurations:e,decodingInfoResults:[hc],error:r}}function uc(r,e,t,s,i,n){let a=r.videoCodec,o=r.audioCodec?r.audioGroups:null,c=n?.audioCodec,l=n?.channels,d=l?parseInt(l):c?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,g)=>{if(g){let f=e.groups[g];if(!f)throw new Error(`Audio track group ${g} not found`);Object.keys(f.channels).forEach(p=>{u[p]=(u[p]||0)+f.channels[p]})}return u},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(u=>qs(u))||r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(s,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(i,8e6))||!!h&&F(d)&&Object.keys(h).some(u=>parseInt(u)>d)}function Ya(r,e,t,s={}){let i=r.videoCodec;if(!i&&!r.audioCodec||!t)return Promise.resolve(Va);let n=[],a=fc(r),o=a.length,c=gc(r,e,o>0),l=c.length;for(let d=o||1*l||1;d--;){let h={type:"media-source"};if(o&&(h.video=a[d%o]),l){h.audio=c[d%l];let u=h.audio.bitrate;h.video&&u&&(h.video.bitrate-=u)}n.push(h)}if(i){let d=navigator.userAgent;if(i.split(",").some(h=>qs(h))&&Ka())return Promise.resolve(Ha(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),n))}return Promise.all(n.map(d=>{let h=mc(d);return s[h]||(s[h]=t.decodingInfo(d))})).then(d=>({supported:!d.some(h=>!h.supported),configurations:n,decodingInfoResults:d})).catch(d=>({supported:!1,configurations:n,decodingInfoResults:[],error:d}))}function fc(r){var e;let t=(e=r.videoCodec)==null?void 0:e.split(","),s=Wa(r),i=r.width||640,n=r.height||480,a=r.frameRate||30,o=r.videoRange.toLowerCase();return t?t.map(c=>{let l={contentType:Kt(cc(c),"video"),width:i,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function gc(r,e,t){var s;let i=(s=r.audioCodec)==null?void 0:s.split(","),n=Wa(r);return i&&r.audioGroups?r.audioGroups.reduce((a,o)=>{var c;let l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((d,h)=>{if(h.groupId===o){let u=parseFloat(h.channels||"");i.forEach(g=>{let f={contentType:Kt(g,"audio"),bitrate:t?pc(g,n):n};u&&(f.channels=""+u),d.push(f)})}return d},a):a},[]):[]}function pc(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 Wa(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function mc(r){let e="",{audio:t,video:s}=r;if(s){let i=ki(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){let i=ki(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}var Ci=["NONE","TYPE-0","TYPE-1",null];function yc(r){return Ci.indexOf(r)>-1}var Ls=["SDR","PQ","HLG"];function vc(r){return!!r&&Ls.indexOf(r)>-1}var ps={No:"",Yes:"YES",v2:"v2"};function Pr(r){let{canSkipUntil:e,canSkipDateRanges:t,age:s}=r,i=s<e/2;return e&&i?t?ps.v2:ps.Yes:ps.No}var Is=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},gt=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.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[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,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Dr(this._audioGroups,e)}hasSubtitleGroup(e){return Dr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.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 Dr(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function Ec(){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 Tc(r,e){let t=!1,s=[];if(r&&(t=r!=="SDR",s=[r]),e){s=e.allowedVideoRanges||Ls.slice(0);let i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&Ec(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}var Sc=r=>{let e=new WeakSet;return(t,s)=>{if(r&&(s=r(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},re=(r,e)=>JSON.stringify(r,Sc(e));function xc(r,e,t,s,i){let n=Object.keys(r),a=s?.channels,o=s?.audioCodec,c=i?.videoCodec,l=a&&parseInt(a)===2,d=!1,h=!1,u=1/0,g=1/0,f=1/0,p=1/0,y=0,v=[],{preferHDR:E,allowedVideoRanges:T}=Tc(e,i);for(let I=n.length;I--;){let b=r[n[I]];d||(d=b.channels[2]>0),u=Math.min(u,b.minHeight),g=Math.min(g,b.minFramerate),f=Math.min(f,b.minBitrate),T.filter(D=>b.videoRanges[D]>0).length>0&&(h=!0)}u=F(u)?u:0,g=F(g)?g:0;let x=Math.max(1080,u),A=Math.max(30,g);f=F(f)?f:t,t=Math.max(f,t),h||(e=void 0);let _=n.length>1;return{codecSet:n.reduce((I,b)=>{let L=r[b];if(b===I)return I;if(v=h?T.filter(D=>L.videoRanges[D]>0):[],_){if(L.minBitrate>t)return Ke(b,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),I;if(!L.hasDefaultAudio)return Ke(b,"no renditions with default or auto-select sound found"),I;if(o&&b.indexOf(o.substring(0,4))%5!==0)return Ke(b,`audio codec preference "${o}" not found`),I;if(a&&!l){if(!L.channels[a])return Ke(b,`no renditions with ${a} channel sound found (channels options: ${Object.keys(L.channels)})`),I}else if((!o||l)&&d&&L.channels[2]===0)return Ke(b,"no renditions with stereo sound found"),I;if(L.minHeight>x)return Ke(b,`min resolution of ${L.minHeight} > maximum of ${x}`),I;if(L.minFramerate>A)return Ke(b,`min framerate of ${L.minFramerate} > maximum of ${A}`),I;if(!v.some(D=>L.videoRanges[D]>0))return Ke(b,`no variants with VIDEO-RANGE of ${re(v)} found`),I;if(c&&b.indexOf(c.substring(0,4))%5!==0)return Ke(b,`video codec preference "${c}" not found`),I;if(L.maxScore<y)return Ke(b,`max score of ${L.maxScore} < selected max of ${y}`),I}return I&&(xs(b)>=xs(I)||L.fragmentError>r[I].fragmentError)?I:(p=L.minIndex,y=L.maxScore,b)},void 0),videoRanges:v,preferHDR:E,minFramerate:g,minBitrate:f,minIndex:p}}function Ke(r,e){se.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function qa(r){return r.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);let i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Ac(r,e,t,s){return r.slice(t,s+1).reduce((i,n,a)=>{if(!n.codecSet)return i;let o=n.audioGroups,c=i[n.codecSet];c||(i[n.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,n.bitrate);let l=Math.min(n.height,n.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,n.frameRate),c.minIndex=Math.min(c.minIndex,a),c.maxScore=Math.max(c.maxScore,n.score),c.fragmentError+=n.fragmentError,c.videoRanges[n.videoRange]=(c.videoRanges[n.videoRange]||0)+1,o&&o.forEach(d=>{if(!d)return;let h=e.groups[d];h&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{c.channels[u]=(c.channels[u]||0)+h.channels[u]}))}),i},{})}function kr(r){if(!r)return r;let{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:n}=r;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:n}}function We(r,e,t){if("attrs"in r){let s=e.indexOf(r);if(s!==-1)return s}for(let s=0;s<e.length;s++){let i=e[s];if(ut(r,i,t))return s}return-1}function ut(r,e,t){let{groupId:s,name:i,lang:n,assocLang:a,default:o}=r,c=r.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(n===void 0||Lc(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in r)||Ic(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function Lc(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function Ic(r,e=""){let t=r.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function dt(r,e){let{audioCodec:t,channels:s}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function bc(r,e,t,s,i){let n=e[s],o=e.reduce((u,g,f)=>{let p=g.uri;return(u[p]||(u[p]=[])).push(f),u},{})[n.uri];o.length>1&&(s=Math.max.apply(Math,o));let c=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),h=Cr(e,s,u=>{if(u.videoRange!==c||u.frameRate!==l||u.codecSet.substring(0,4)!==d)return!1;let g=u.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return We(r,f,i)>-1});return h>-1?h:Cr(e,s,u=>{let g=u.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return We(r,f,i)>-1})}function Cr(r,e,t){for(let s=e;s>-1;s--)if(t(r[s]))return s;for(let s=e+1;s<r.length;s++)if(t(r[s]))return s;return-1}function bs(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}var wi=class extends Re{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;let{fragCurrent:i,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:c}=a;if(!i||!c)return;let l=performance.now(),d=n?n.stats:i.stats,h=n?n.duration:i.duration,u=l-d.loading.start,g=a.minAutoLevel,f=i.level,p=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||f<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let y=p>-1&&p!==f,v=!!t||y;if(!v&&(c.paused||!c.playbackRate||!c.readyState))return;let E=a.mainForwardBufferInfo;if(!v&&E===null)return;let T=this.bwEstimator.getEstimateTTFB(),x=Math.abs(c.playbackRate);if(u<=Math.max(T,1e3*(h/(x*2))))return;let A=E?E.len/x:0,_=d.loading.first?d.loading.first-d.loading.start:-1,S=d.loaded&&_>-1,I=this.getBwEstimate(),b=a.levels,L=b[f],D=Math.max(d.loaded,Math.round(h*(i.bitrate||L.averageBitrate)/8)),C=S?u-_:u;C<1&&S&&(C=Math.min(u,d.loaded*8/I));let $=S?d.loaded*1e3/C:0,H=T/1e3,U=$?(D-d.loaded)/$:D*8/I+H;if(U<=A)return;let k=$?$*8:I,G=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,N=this.hls.config.abrBandWidthUpFactor,K=Number.POSITIVE_INFINITY,Y;for(Y=f-1;Y>g;Y--){let ee=b[Y].maxBitrate,z=!b[Y].details||G;if(K=this.getTimeToLoadFrag(H,k,h*ee,z),K<Math.min(A,h+H))break}if(K>=U||K>h*10)return;S?this.bwEstimator.sample(u-Math.min(T,_),d.loaded):this.bwEstimator.sampleTTFB(u);let w=b[Y].maxBitrate;this.getBwEstimate()*N>w&&this.resetEstimator(w);let M=this.findBestLevel(w,g,Y,0,A,1,1);M>-1&&(Y=M),this.warn(`Fragment ${i.sn}${n?" part "+n.index:""} of level ${f} is loading too slowly;
2
2
  Fragment duration: ${i.duration.toFixed(3)}
3
- Time to underbuffer: ${x.toFixed(3)} s
3
+ Time to underbuffer: ${A.toFixed(3)} s
4
4
  Estimated load time for current fragment: ${U.toFixed(3)} s
5
- Estimated load time for down switch fragment: ${G.toFixed(3)} s
5
+ Estimated load time for down switch fragment: ${K.toFixed(3)} s
6
6
  TTFB estimate: ${_|0} ms
7
- Current BW estimate: ${O(R)?R|0:"Unknown"} bps
7
+ Current BW estimate: ${F(I)?I|0:"Unknown"} bps
8
8
  New BW estimate: ${this.getBwEstimate()|0} bps
9
- Switching to level ${Y} @ ${C|0} bps`),a.nextLoadLevel=a.nextAutoLevel=Y,this.clearTimer();let j=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===Y&&Y>0){let ee=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Y>0?"and switching down":""}
9
+ Switching to level ${Y} @ ${w|0} bps`),a.nextLoadLevel=a.nextAutoLevel=Y,this.clearTimer();let j=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===Y&&Y>0){let ee=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Y>0?"and switching down":""}
10
10
  Fragment duration: ${i.duration.toFixed(3)} s
11
- Time to underbuffer: ${ee.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,Y>f){let z=this.findBestLevel(this.hls.levels[f].bitrate,f,Y,0,ee,1,1);z===-1&&(z=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=z,this.resetEstimator(this.hls.levels[z].bitrate)}}};y||U>G*2?j():this.timer=self.setInterval(j,G*1e3),a.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new bi(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i: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 I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case I.FRAG_LOAD_TIMEOUT:{let s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){let a=performance.now(),o=r?r.stats:s.stats,c=a-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){let d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(d,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){let r=e+s/t,a=i?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){let s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;O(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){let i=s?s.stats:t.stats;if(t.type===N.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let r=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,c=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:c},a.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){let r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;let a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==N.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;let{maxAutoLevel:i,config:r,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay(),h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){let y=this.findBestLevel(c,a,i,l,0,h,d);if(y>=0)return this.rebufferNotice=-1,y}let u=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){let y=this.bitrateTestDelay;y&&(u=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=d=1)}let f=this.findBestLevel(c,a,i,l,u,h,d);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let g=s.levels[a],p=s.loadLevelObj;return p&&g?.bitrate<p.bitrate?a:s.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,a,o){var c;let l=i+r,h=this.lastLoadedFragLevel,d=h===-1?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:f}=this,{levels:g,allAudioTracks:p,loadLevel:y,config:v}=this.hls;if(g.length===1)return 0;let E=g[d],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),S=y===-1||h===-1,x,_="SDR",A=E?.frameRate||0,{audioPreference:R,videoPreference:b}=v,L=this.audioTracksByGroup||(this.audioTracksByGroup=Ha(p)),P=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;let k=this.codecTiers||(this.codecTiers=pc(g,L,t,s)),$=mc(k,_,e,R,b),{codecSet:F,videoRanges:G,minFramerate:Y,minBitrate:C,minIndex:w,preferHDR:j}=$;P=w,x=F,_=j?G[G.length-1]:G[0],A=Y,e=Math.max(e,C),this.log(`picked start tier ${ne($)}`)}else x=E?.codecSet,_=E?.videoRange;let M=f?f.duration:u?u.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,V=[];for(let k=s;k>=t;k--){var U;let $=g[k],F=k>d;if(!$)continue;if(v.useMediaCapabilities&&!$.supportedResult&&!$.supportedPromise){let z=navigator.mediaCapabilities;typeof z?.decodingInfo=="function"&&nc($,L,_,A,e,R)?($.supportedPromise=Ka($,L,z,this.supportedCache),$.supportedPromise.then(Z=>{if(!this.hls)return;$.supportedResult=Z;let Ee=this.hls.levels,pe=Ee.indexOf($);Z.error?this.warn(`MediaCapabilities decodingInfo error: "${Z.error}" for level ${pe} ${ne(Z)}`):Z.supported?Z.decodingInfoResults.some(ke=>ke.smooth===!1||ke.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${pe} not smooth or powerEfficient: ${ne(Z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${pe} ${ne(Z)}`),pe>-1&&Ee.length>1&&(this.log(`Removing unsupported level ${pe}`),this.hls.removeLevel(pe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Z}`)})):$.supportedResult=$a}if((x&&$.codecSet!==x||_&&$.videoRange!==_||F&&A>$.frameRate||!F&&A>0&&A<$.frameRate||(U=$.supportedResult)!=null&&(U=U.decodingInfoResults)!=null&&U.some(z=>z.smooth===!1))&&(!S||k!==P)){V.push(k);continue}let G=$.details,Y=(f?G?.partTarget:G?.averagetargetduration)||M,C;F?C=o*e:C=a*e;let w=M&&i>=M*2&&r===0?$.averageBitrate:$.maxBitrate,j=this.getTimeToLoadFrag(B,C,w*Y,G===void 0);if(C>=w&&(k===h||$.loadError===0&&$.fragmentError===0)&&(j<=B||!O(j)||T&&!this.bitrateTestDelay||j<l)){let z=this.forcedAutoLevel;return k!==y&&(z===-1||z!==y)&&(V.length&&this.trace(`Skipped level(s) ${V.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[V[0]].codecs}" ${g[V[0]].videoRange}; not compatible with "${x}" ${_}`),this.info(`switch candidate:${d}->${k} adjustedbw(${Math.round(C)})-bitrate=${Math.round(C-w)} ttfb:${B.toFixed(1)} avgDuration:${Y.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${S} codecSet:${$.codecSet} videoRange:${$.videoRange} hls.loadLevel:${y}`)),S&&(this.firstSelection=k),k}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},Ya={search:function(n,e){let t=0,s=n.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=n[i];let a=e(r);if(a>0)t=i+1;else if(a<0)s=i-1;else return r}return null}};function Tc(n,e,t){if(e===null||!Array.isArray(n)||!n.length||!O(e))return null;let s=n[0].programDateTime;if(e<(s||0))return null;let i=n[n.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<n.length;++r){let a=n[r];if(xc(e,t,a))return a}return null}function gt(n,e,t=0,s=0,i=.005){let r=null;if(n){r=e[1+n.sn-e[0].sn]||null;let o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&n.level!==r.level&&r.end<=n.end&&(r=e[2+n.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!n||n.level===r.level)&&Pn(t,s,r)===0||Sc(r,n,Math.min(i,s))))return r;let a=Ya.search(e,Pn.bind(null,t,s));return a&&(a!==n||!r)?a:r}function Sc(n,e,t){if(e&&e.start===0&&e.level<n.level&&(e.endPTS||0)>0){let s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return n.start<=s}return!1}function Pn(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=n?1:t.start-s>n&&t.start?-1:0}function xc(n,e,t){let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>n}function Wa(n,e,t){if(n&&n.startCC<=e&&n.endCC>=e){let s=n.fragments,{fragmentHint:i}=n;i&&(s=s.concat(i));let r;return Ya.search(s,a=>a.cc<e?1:a.cc>e?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function bs(n){switch(n.details){case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_TIMEOUT:case I.LEVEL_LOAD_TIMEOUT:case I.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function qa(n){return n.details.startsWith("key")}function ja(n){return qa(n)&&!!n.frag&&!n.frag.decryptdata}function kn(n,e){let t=bs(e);return n.default[`${t?"timeout":"error"}Retry`]}function zr(n,e){let t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function Cn(n){return te(te({},n),{errorRetry:null,timeoutRetry:null})}function Rs(n,e,t,s){if(!n)return!1;let i=s?.code,r=e<n.maxNumRetry&&(Ac(i)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,s,r):r}function Ac(n){return wi(n)||!!n&&(n<400||n>499)}function wi(n){return n===0&&navigator.onLine===!1}var ge={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Re={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},Mi=class extends Ie{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(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===N.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;let i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(a=>i.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 s;if(t.fatal)return;let i=this.hls,r=t.context;switch(t.details){case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case I.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Lt();return}case I.FRAG_GAP:case I.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ge.SendAlternateToPenaltyBox;return}case I.LEVEL_EMPTY_ERROR:case I.LEVEL_PARSING_ERROR:{var a;let c=t.parent===N.MAIN?t.level:i.loadLevel;t.details===I.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case I.AUDIO_TRACK_LOAD_ERROR:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.SUBTITLE_LOAD_ERROR:case I.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){let c=i.loadLevelObj;if(c&&(r.type===Q.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===Q.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=ge.SendAlternateToPenaltyBox,t.errorAction.flags=Re.MoveAllAlternatesMatchingHost;return}}return;case I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ge.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingHDCP};return;case I.KEY_SYSTEM_SESSION_UPDATE_FAILED:case I.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case I.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ge.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingKey};return;case I.BUFFER_ADD_CODEC_ERROR:case I.REMUX_ALLOC_ERROR:case I.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case I.INTERNAL_EXCEPTION:case I.BUFFER_APPENDING_ERROR:case I.BUFFER_FULL_ERROR:case I.LEVEL_SWITCH_ERROR:case I.BUFFER_STALLED_ERROR:case I.BUFFER_SEEK_OVER_HOLE:case I.BUFFER_NUDGE_ON_STALL:t.errorAction=Lt();return}t.type===K.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Lt())}getPlaylistRetryOrSwitchAction(e,t){let s=this.hls,i=kn(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(Rs(i,r,bs(e),e.response))return{action:ge.RetryRequest,flags:Re.None,retryConfig:i,retryCount:r};let o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){let t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=kn(qa(e)?a:r,e),c=t.levels.reduce((h,d)=>h+d.fragmentError,0);if(i&&(e.details!==I.FRAG_GAP&&i.fragmentError++,!ja(e)&&Rs(o,c,bs(e),e.response)))return{action:ge.RetryRequest,flags:Re.None,retryConfig:o,retryCount:c};let l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){let s=this.hls;t==null&&(t=s.loadLevel);let i=this.hls.levels[t];if(i){var r,a;let l=e.details;i.loadError++,l===I.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1,{levels:d,loadLevel:u,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);let p=(r=e.frag)==null?void 0:r.type,v=(p===N.AUDIO&&l===I.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===I.BUFFER_ADD_CODEC_ERROR||l===I.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:_})=>i.audioCodec!==_),T=e.sourceBufferName==="video"&&(l===I.BUFFER_ADD_CODEC_ERROR||l===I.BUFFER_APPEND_ERROR)&&d.some(({codecSet:_,audioCodec:A})=>i.codecSet!==_&&i.audioCodec===A),{type:S,groupId:x}=(a=e.context)!=null?a:{};for(let _=d.length;_--;){let A=(_+u)%d.length;if(A!==u&&A>=f&&A<=g&&d[A].loadError===0){var o,c;let R=d[A];if(l===I.FRAG_GAP&&p===N.MAIN&&e.frag){let b=d[A].details;if(b){let L=gt(e.frag,b.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(S===Q.AUDIO_TRACK&&R.hasAudioGroup(x)||S===Q.SUBTITLE_TRACK&&R.hasSubtitleGroup(x))continue;if(p===N.AUDIO&&(o=i.audioGroups)!=null&&o.some(b=>R.hasAudioGroup(b))||p===N.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(b=>R.hasSubtitleGroup(b))||v&&i.audioCodec===R.audioCodec||T&&i.codecSet===R.codecSet||!v&&i.codecSet!==R.codecSet)continue}h=A;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:ge.SendAlternateToPenaltyBox,flags:Re.None,nextAutoLevel:h}}return{action:ge.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case ge.DoNothing:break;case ge.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==I.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case ge.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,s=e.errorAction;if(!s)return;let{flags:i}=s,r=s.nextAutoLevel;switch(i){case Re.None:this.switchLevel(e,r);break;case Re.MoveAllAlternatesMatchingHDCP:{let c=this.getVariantLevelIndex(e.frag),l=t.levels[c],h=l?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=ki[ki.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Re.MoveAllAlternatesMatchingKey:{let c=e.decryptdata;if(c){let l=this.hls.levels,h=l.length;for(let u=h;u--;)if(this.variantHasKey(l[u],c)){var a,o;this.log(`Banned key found in level ${u} (${l[u].bitrate}bps) or audio group "${(a=l[u].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${ye(c.keyId||[])}`),l[u].fragmentError++,l[u].loadError++,this.log(`Removing level ${u} with key error (${e.error})`),this.hls.removeLevel(u)}let d=e.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(d&&d.type!==N.MAIN){let u=d.decryptdata;u&&!c.matches(u)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}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===I.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let s=Pi(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}};function Lt(n){let e={action:ge.DoNothing,flags:Re.None};return n&&(e.resolved=!0),e}var de={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Oi=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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let s=this.activePartLists[t];if(s)for(let i=s.length;i--;){let r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){let{fragments:i}=this,r=Object.keys(i);for(let a=r.length;a--;){let o=i[r[a]];if(o?.body.type===t&&(!s||o.buffered)){let c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);let a=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{let c=this.fragments[o];if(!c||a>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===s&&this.removeFragment(c.body);return}let l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(h=>{let d=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return d&&this.removeFragment(c.body),d})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;let s=e.frag,i=pt(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;let a=!s.relurl;Object.keys(t).forEach(o=>{let c=s.elementaryStreams[o];if(!c)return;let l=t[o],h=a||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),ss(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let s=this.activePartLists[t];s&&(this.activePartLists[t]=wn(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){let s=pt(e),i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){let r={time:[],partial:s},a=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||a;for(let h=0;h<i.length;h++){let d=i.start(h)-this.bufferPadding,u=i.end(h)+this.bufferPadding;if(l>=d&&c<=u){r.time.push({startPTS:Math.max(a,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(a<u&&o>d){let f=Math.max(a,i.start(h)),g=Math.min(o,i.end(h));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=d)break}return r}getPartialFragment(e){let t=null,s,i,r,a=0,{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{let h=c[l];h&&ss(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),a<=s&&(t=h.body,a=s)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||ss(t))}getState(e){let t=pt(e),s=this.fragments[t];return s?s.buffered?ss(s)?de.PARTIAL:de.OK:de.APPENDING:de.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,r=s.end(a)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;let s=t.frag,i=t.part?null:t,r=pt(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:s,part:i,timeRanges:r,type:a}=t;if(s.sn==="initSegment")return;let o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;let c=r[a];this.detectEvictedFragments(a,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=pt(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){let r=t[s[i]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||r)&&this.removeFragment(c)})}removeFragment(e){let t=pt(e);e.clearElementaryStreamInfo();let s=this.activePartLists[e.type];if(s){let i=e.sn;this.activePartLists[e.type]=wn(s,r=>r.fragment.sn!==i)}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(s=>s.clearElementaryStreamInfo())}};function ss(n){var e,t,s;return n.buffered&&!!(n.body.gap||(e=n.range.video)!=null&&e.partial||(t=n.range.audio)!=null&&t.partial||(s=n.range.audiovideo)!=null&&s.partial)}function pt(n){return`${n.type}_${n.level}_${n.sn}`}function wn(n,e){return n.filter(t=>{let s=e(t);return s||t.clearElementaryStreamInfo(),s})}var it={cbc:0,ctr:1},Fi=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case it.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case it.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 Lc(n){let e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?n.slice(0,e-t):n}var Ni=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),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){let e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],a=s[2],o=s[3],c=this.invSubMix,l=c[0],h=c[1],d=c[2],u=c[3],f=new Uint32Array(256),g=0,p=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[y]=y<<1^283;for(y=0;y<256;y++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[g]=v,t[v]=g;let E=f[g],T=f[E],S=f[T],x=f[v]*257^v*16843008;i[g]=x<<24|x>>>8,r[g]=x<<16|x>>>16,a[g]=x<<8|x>>>24,o[g]=x,x=S*16843009^T*65537^E*257^g*16843008,l[v]=x<<24|x>>>8,h[v]=x<<16|x>>>16,d[v]=x<<8|x>>>24,u[v]=x,g?(g=E^f[f[f[S^E]]],p^=f[f[p]]):g=p=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;let r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);let a=this.ksRows=(r+6+1)*4,o,c,l=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),d=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],p=f[1],y=f[2],v=f[3],E,T;for(o=0;o<a;o++){if(o<r){E=l[o]=t[o];continue}T=E,o%r===0?(T=T<<8|T>>>24,T=d[T>>>24]<<24|d[T>>>16&255]<<16|d[T>>>8&255]<<8|d[T&255],T^=u[o/r|0]<<24):r>6&&o%r===4&&(T=d[T>>>24]<<24|d[T>>>16&255]<<16|d[T>>>8&255]<<8|d[T&255]),l[o]=E=(l[o-r]^T)>>>0}for(c=0;c<a;c++)o=a-c,c&3?T=l[o]:T=l[o-4],c<4||o<=4?h[c]=T:h[c]=g[d[T>>>24]]^p[d[T>>>16&255]]^y[d[T>>>8&255]]^v[d[T&255]],h[c]=h[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){let i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],h=o[2],d=o[3],u=this.uint8ArrayToUint32Array_(s),f=u[0],g=u[1],p=u[2],y=u[3],v=new Int32Array(e),E=new Int32Array(v.length),T,S,x,_,A,R,b,L,P,M,B,V,U,k,$=this.networkToHostOrderSwap;for(;t<v.length;){for(P=$(v[t]),M=$(v[t+1]),B=$(v[t+2]),V=$(v[t+3]),A=P^r[0],R=V^r[1],b=B^r[2],L=M^r[3],U=4,k=1;k<i;k++)T=c[A>>>24]^l[R>>16&255]^h[b>>8&255]^d[L&255]^r[U],S=c[R>>>24]^l[b>>16&255]^h[L>>8&255]^d[A&255]^r[U+1],x=c[b>>>24]^l[L>>16&255]^h[A>>8&255]^d[R&255]^r[U+2],_=c[L>>>24]^l[A>>16&255]^h[R>>8&255]^d[b&255]^r[U+3],A=T,R=S,b=x,L=_,U=U+4;T=a[A>>>24]<<24^a[R>>16&255]<<16^a[b>>8&255]<<8^a[L&255]^r[U],S=a[R>>>24]<<24^a[b>>16&255]<<16^a[L>>8&255]<<8^a[A&255]^r[U+1],x=a[b>>>24]<<24^a[L>>16&255]<<16^a[A>>8&255]<<8^a[R&255]^r[U+2],_=a[L>>>24]<<24^a[A>>16&255]<<16^a[R>>8&255]<<8^a[b&255]^r[U+3],E[t]=$(T^f),E[t+1]=$(_^g),E[t+2]=$(x^p),E[t+3]=$(S^y),f=P,g=M,p=B,y=V,t=t+4}return E.buffer}},Bi=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){let e=Ic(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function Ic(n){switch(n){case it.cbc:return"AES-CBC";case it.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}var bc=16,Kt=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let s=self.crypto;s&&(this.subtle=s.subtle||s.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 s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Lc(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);let c=this.flush();c?r(c.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){let{currentIV:r,currentResult:a,remainderData:o}=this;if(i!==it.cbc||t.byteLength!==16)return se.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=we(o,e),this.remainderData=null);let c=this.getValidChunk(e);if(!c.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ni),l.expandKey(t);let h=a;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Bi(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Fi(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(se.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){let r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,s=e.length-e.length%bc;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(se.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Mn=Math.pow(2,17),Ui=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){let s=e.url;if(!s)return Promise.reject(new Be({type:K.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();let i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){c(Fn(e));return}else e.gap=!1;let l=this.loader=r?new r(i):new a(i),h=On(e);e.loader=l;let d=Cn(i.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Mn};e.stats=l.stats;let f={onSuccess:(g,p,y,v)=>{this.resetLoader(e,l);let E=g.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:e,part:null,payload:E,networkDetails:v})},onError:(g,p,y,v)=>{this.resetLoader(e,l),c(new Be({type:K.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:te({url:s,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:y,stats:v}))},onAbort:(g,p,y)=>{this.resetLoader(e,l),c(new Be({type:K.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:g}))},onTimeout:(g,p,y)=>{this.resetLoader(e,l),c(new Be({type:K.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:y,stats:g}))}};t&&(f.onProgress=(g,p,y,v)=>t({frag:e,part:null,payload:y,networkDetails:v})),l.load(h,u,f)})}loadPart(e,t,s){this.abort();let i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(Fn(e,t));return}let l=this.loader=r?new r(i):new a(i),h=On(e,t);e.loader=l;let d=Cn(i.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Mn};t.stats=l.stats,l.load(h,u,{onSuccess:(f,g,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:y};s(v),o(v)},onError:(f,g,p,y)=>{this.resetLoader(e,l),c(new Be({type:K.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:te({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:y}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new Be({type:K.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,l),c(new Be({type:K.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){let s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){let c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),c),d=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+d}else s.total=Math.max(s.loaded,s.total);let a=s.loading,o=i.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,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function On(n,e=null){let t=e||n,s={frag:n,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(O(i)&&O(r)){var a;let o=i,c=r;if(n.sn==="initSegment"&&Rc((a=n.decryptdata)==null?void 0:a.method)){let l=r-i;l%16&&(c=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function Fn(n,e){let t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:K.MEDIA_ERROR,details:I.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(s.part=e),(e||n).stats.aborted=!0,new Be(s)}function Rc(n){return n==="AES-128"||n==="AES-256"}var Be=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},_s=class extends Ie{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)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Vt=class{constructor(e,t,s,i=0,r=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=is(),this.buffering={audio:is(),video:is(),audiovideo:is()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=a}};function is(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Nn={length:0,start:()=>0,end:()=>0},q=class n{static isBuffered(e,t){if(e){let s=n.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){let t=n.getBuffered(e);return n.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){let i=n.bufferedRanges(e);if(i.length)return n.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,d)=>h.start-d.start||d.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);let d=r.length;if(d){let u=r[d-1].end;e[h].start-u<s?e[h].end>u&&(r[d-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let a=0,o,c=t,l=t;for(let h=0;h<r.length;h++){let d=r[h].start,u=r[h].end;if(i===-1&&t>=d&&t<=u&&(i=h),t+s>=d&&t<u)c=d,l=u,a=l-t;else if(t+s<d){o=d;break}}return{len:a,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Nn}catch(t){return se.log("failed to get media.buffered",t),Nn}}},za=/\{\$([a-zA-Z0-9-_]+)\}/g;function Bn(n){return za.test(n)}function $i(n,e){if(n.variableList!==null||n.hasVariableRefs){let t=n.variableList;return e.replace(za,s=>{let i=s.substring(2,s.length-1),r=t?.[i];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function Un(n,e,t){let s=n.variableList;s||(n.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(i))r=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in s?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function _c(n,e,t){let s=e.IMPORT;if(t&&s in t){let i=n.variableList;i||(n.variableList=i={}),i[s]=t[s]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}var Dc=/^(\d+)x(\d+)$/,$n=/(.+?)=(".*?"|.*?)(?:,|$)/g,ae=class n{constructor(e,t){typeof e=="string"&&(e=n.parseAttrList(e,t)),ie(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 s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}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 s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=Dc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s,i={};for($n.lastIndex=0;(s=$n.exec(e))!==null;){let a=s[1].trim(),o=s[2],c=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1,l=!1;if(c)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=$i(t,o);else if(!l&&!c)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":se.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}},Pc="com.apple.hls.interstitial";function kc(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function Cc(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}var Ds=class{constructor(e,t,s=0){var i;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=(i=t?.tagOrder)!=null?i:s,t){let r=t.attr;for(let a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){se.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ie(new ae({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let r=t?.endDate||new Date(this.attr["END-DATE"]);O(r.getTime())&&(this._endDate=r)}}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?(se.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(O(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===Pc}get isValid(){return!!this.id&&!this._badValueForSameId&&O(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)}},wc=10,Gi=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.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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?O(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||wc}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 Ps(n,e){return n.length===e.length?!n.some((t,s)=>t!==e[s]):!1}function Gn(n,e){return!n&&!e?!0:!n||!e?!1:Ps(n,e)}function It(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function Xr(n){switch(n){case"AES-128":case"AES-256":return it.cbc;case"AES-256-CTR":return it.ctr;default:throw new Error(`invalid full segment method ${n}`)}}function Qr(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Ki(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}function Mc(n){let e=Ki(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Xa(n){let e=function(s,i,r){let a=s[i];s[i]=s[r],s[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}function Qa(n){let e=n.split(":"),t=null;if(e[0]==="data"&&e.length===2){let s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){let r=i[0]==="base64",a=i[1];r?(s.splice(-1,1),t=Qr(a)):t=Mc(a)}}return t}var ks=typeof self<"u"?self:void 0,oe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ms(n){switch(n){case ve.FAIRPLAY:return oe.FAIRPLAY;case ve.PLAYREADY:return oe.PLAYREADY;case ve.WIDEVINE:return oe.WIDEVINE;case ve.CLEARKEY:return oe.CLEARKEY}}function oi(n){switch(n){case oe.FAIRPLAY:return ve.FAIRPLAY;case oe.PLAYREADY:return ve.PLAYREADY;case oe.WIDEVINE:return ve.WIDEVINE;case oe.CLEARKEY:return ve.CLEARKEY}}function Mt(n){let{drmSystems:e,widevineLicenseUrl:t}=n,s=e?[oe.FAIRPLAY,oe.WIDEVINE,oe.PLAYREADY,oe.CLEARKEY].filter(i=>!!e[i]):[];return!s[oe.WIDEVINE]&&t&&s.push(oe.WIDEVINE),s}var Za=(function(n){return ks!=null&&(n=ks.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Oc(n,e,t,s){let i;switch(n){case oe.FAIRPLAY:i=["cenc","sinf"];break;case oe.WIDEVINE:case oe.PLAYREADY:i=["cenc"];break;case oe.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return Fc(i,e,t,s)}function Fc(n,e,t,s){return[{initDataTypes:n,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Nc(n){var e;return!!n&&(n.sessionType==="persistent-license"||!!((e=n.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Ja(n){let e=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let c=Qr(o).subarray(0,16);return Xa(c),c}}return null}var yt={},Dt=class n{static clearKeyUriToKeyIdMap(){yt={}}static setKeyIdForUri(e,t){yt[e]=t}static addKeyIdForUri(e){let t=Object.keys(yt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),yt[e]=s,s}constructor(e,t,s,i=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!It(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Pa(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Ps(e.keyFormatVersions,this.keyFormatVersions)&&Gn(e.iv,this.iv)&&Gn(e.keyId,this.keyId)}isSupported(){if(this.method){if(It(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ve.FAIRPLAY:case ve.WIDEVINE:case ve.PLAYREADY:case ve.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(It(this.method)){let r=this.iv;return r||(typeof e!="number"&&(se.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=Uc(e)),new n(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){let r=yt[this.uri];if(r&&!Ps(this.keyId,r)&&n.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let s=Qa(this.uri);if(s)switch(this.keyFormat){case ve.WIDEVINE:if(this.pssh=s,!this.keyId){let r=Xl(s.buffer);if(r.length){var i;let a=r[0];this.keyId=(i=a.kids)!=null&&i.length?a.kids[0]:null}}this.keyId||(this.keyId=Kn(t));break;case ve.PLAYREADY:{let r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=zl(r,null,s),this.keyId=Ja(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){let a=new Uint8Array(16);a.set(r,16-r.length),r=a}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=Bc(t),r||(r=Kn(t),r||(r=yt[this.uri])),r&&(this.keyId=r,n.setKeyIdForUri(this.uri,r))}return this}};function Bc(n){let e=n?.[ve.WIDEVINE];return e?e.keyId:null}function Kn(n){let e=n?.[ve.PLAYREADY];if(e){let t=Qa(e.uri);if(t)return Ja(t)}return null}function Uc(n){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}var Vn=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Hn=/#EXT-X-MEDIA:(.*)/g,$c=/^#EXT(?:INF|-X-TARGETDURATION):/m,li=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Gc=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),ht=class n{static findGroup(e,t){for(let s=0;s<e.length;s++){let i=e[s];if(i.id===t)return i}}static resolve(e,t){return Yr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return $c.test(e)}static parseMasterPlaylist(e,t){let s=Bn(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(Vn.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=Vn.exec(e))!=null;)if(a[1]){var o;let l=new ae(a[1],i),h=$i(i,a[2]),d={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:n.resolve(h,t)},u=l.decimalResolution("RESOLUTION");u&&(d.width=u.width,d.height=u.height),qn(l.CODECS,d);let f=l["SUPPLEMENTAL-CODECS"];f&&(d.supplemental={},qn(f,d.supplemental)),(o=d.unknownCodecs)!=null&&o.length||r.push(d),i.levels.push(d)}else if(a[3]){let l=a[3],h=a[4];switch(l){case"SESSION-DATA":{let d=new ae(h,i),u=d["DATA-ID"];u&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[u]=d);break}case"SESSION-KEY":{let d=Yn(h,t,i);d.encrypted&&d.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(d)):se.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{let d=new ae(h,i);Un(i,d,t)}break}case"CONTENT-STEERING":{let d=new ae(h,i);i.contentSteering={uri:n.resolve(d["SERVER-URI"],t),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=Wn(h);break}}}let c=r.length>0&&r.length<i.levels.length;return i.levels=c?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i,r={},a=s.levels,o={AUDIO:a.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]},c=0;for(Hn.lastIndex=0;(i=Hn.exec(e))!==null;){let l=new ae(i[1],s),h=l.TYPE;if(h){let d=o[h],u=r[h]||[];r[h]=u;let f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,v=l["INSTREAM-ID"],E={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:h,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?n.resolve(l.URI,t):""};if(g&&(E.assocLang=g),p&&(E.channels=p),y&&(E.characteristics=y),v&&(E.instreamId=v),d!=null&&d.length){let T=n.findGroup(d,E.groupId)||d[0];jn(E,T,"audioCodec"),jn(E,T,"textCodec")}u.push(E)}}return r}static parseLevelPlaylist(e,t,s,i,r,a){var o;let c={url:t},l=new Gi(t),h=l.fragments,d=[],u=null,f=0,g=0,p=0,y=0,v=0,E=null,T=new Ot(i,c),S,x,_,A=-1,R=!1,b=null,L;if(li.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Bn(e),((o=li.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=li.exec(e))!==null;){R&&(R=!1,T=new Ot(i,c),T.playlistOffset=p,T.setStart(p),T.sn=f,T.cc=y,v&&(T.bitrate=v),T.level=s,u&&(T.initSegment=u,u.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),b&&(T.setByteRange(b),b=null)));let V=S[1];if(V){T.duration=parseFloat(V);let U=(" "+S[2]).slice(1);T.title=U||null,T.tagList.push(U?["INF",V,U]:["INF",V])}else if(S[3]){if(O(T.duration)){T.playlistOffset=p,T.setStart(p),_&&Xn(T,_,l),T.sn=f,T.level=s,T.cc=y,h.push(T);let U=(" "+S[3]).slice(1);T.relurl=$i(l,U),Vi(T,E,d),E=T,p+=T.duration,f++,g=0,R=!0}}else{if(S=S[0].match(Gc),!S){se.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<S.length&&S[x]===void 0;x++);let U=(" "+S[x]).slice(1),k=(" "+S[x+1]).slice(1),$=S[x+2]?(" "+S[x+2]).slice(1):null;switch(U){case"BYTERANGE":E?T.setByteRange(k,E):T.setByteRange(k);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=k,T.tagList.push(["PROGRAM-DATE-TIME",k]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":l.type&&qe(l,U,S),l.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?qe(l,U,S):h.length>0&&Qn(l,U,S),f=l.startSN=parseInt(k);break;case"SKIP":{l.skippedSegments&&qe(l,U,S);let F=new ae(k,l),G=F.decimalInteger("SKIPPED-SEGMENTS");if(O(G)){l.skippedSegments+=G;for(let C=G;C--;)h.push(null);f+=G}let Y=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");Y&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(Y.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&qe(l,U,S),l.targetduration=Math.max(parseInt(k),1);break;case"VERSION":l.version!==null&&qe(l,U,S),l.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||qe(l,U,S),l.live=!1;break;case"#":(k||$)&&T.tagList.push($?[k,$]:[k]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([U]);break;case"BITRATE":T.tagList.push([U,k]),v=parseInt(k)*1e3,O(v)?T.bitrate=v:v=0;break;case"DATERANGE":{let F=new ae(k,l),G=new Ds(F,l.dateRanges[F.ID],l.dateRangeTagCount);l.dateRangeTagCount++,G.isValid||l.skippedSegments?l.dateRanges[G.id]=G:se.warn(`Ignoring invalid DATERANGE tag: "${k}"`),T.tagList.push(["EXT-X-DATERANGE",k]);break}case"DEFINE":{{let F=new ae(k,l);"IMPORT"in F?_c(l,F,a):Un(l,F,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?qe(l,U,S):h.length>0&&Qn(l,U,S),l.startCC=y=parseInt(k);break;case"KEY":{let F=Yn(k,t,l);if(F.isSupported()){if(F.method==="NONE"){_=void 0;break}_||(_={});let G=_[F.keyFormat];G!=null&&G.matches(F)||(G&&(_=ie({},_)),_[F.keyFormat]=F)}else se.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${k}"`);break}case"START":l.startTimeOffset=Wn(k);break;case"MAP":{let F=new ae(k,l);if(T.duration){let G=new Ot(i,c);zn(G,F,s,_),u=G,T.initSegment=u,u.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime)}else{let G=T.byteRangeEndOffset;if(G){let Y=T.byteRangeStartOffset;b=`${G-Y}@${Y}`}else b=null;zn(T,F,s,_),u=T,R=!0}u.cc=y;break}case"SERVER-CONTROL":{L&&qe(l,U,S),L=new ae(k),l.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),l.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&qe(l,U,S);let F=new ae(k);l.partTarget=F.decimalFloatingPoint("PART-TARGET");break}case"PART":{let F=l.partList;F||(F=l.partList=[]);let G=g>0?F[F.length-1]:void 0,Y=g++,C=new ae(k,l),w=new Di(C,T,c,Y,G);F.push(w),T.duration+=w.duration;break}case"PRELOAD-HINT":{let F=new ae(k,l);l.preloadHint=F;break}case"RENDITION-REPORT":{let F=new ae(k,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(F);break}default:se.warn(`line parsed but not handled: ${S}`);break}}}E&&!E.relurl?(h.pop(),p-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(Vi(T,E,d),T.cc=y,l.fragmentHint=T,_&&Xn(T,_,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));let P=h.length,M=h[0],B=h[P-1];if(p+=l.skippedSegments*l.targetduration,p>0&&P&&B){l.averagetargetduration=p/P;let V=B.sn;l.endSN=V!=="initSegment"?V:0,l.live||(B.endList=!0),A>0&&(Vc(h,A),M&&d.unshift(M))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,d.length&&l.dateRangeTagCount&&M&&eo(d,l),l.endCC=y,l}};function eo(n,e){let t=n.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];n.push(o),t++}else return;let s=n[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){let c=e.dateRanges[r[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let h=t;h--;){var a;if(((a=n[h])==null?void 0:a.sn)<e.startSN)break;let d=Kc(e,l,n,h,i);if(d!==-1){c.tagAnchor=e.fragments[d].ref;break}}}}function Kc(n,e,t,s,i){let r=t[s];if(r){let o=r.programDateTime;if(e>=o||s===0){var a;let c=(((a=t[s+1])==null?void 0:a.start)||i)-r.start;if(e<=o+c*1e3){let l=t[s].sn-n.startSN;if(l<0)return-1;let h=n.fragments;if(h.length>t.length){let u=(t[s+1]||h[h.length-1]).sn-n.startSN;for(let f=u;f>l;f--){let g=h[f].programDateTime;if(e>=g&&e<g+h[f].duration*1e3)return f}}return l}}}return-1}function Yn(n,e,t){var s,i;let r=new ae(n,t),a=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&se.error(`Invalid IV: ${r.IV}`);let d=o?ht.resolve(o,e):"",u=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Dt(a,d,h,u,c,r.KEYID)}function Wn(n){let t=new ae(n).decimalFloatingPoint("TIME-OFFSET");return O(t)?t:null}function qn(n,e){let t=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{let i=t.filter(r=>qr(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function jn(n,e,t){let s=e[t];s&&(n[t]=s)}function Vc(n,e){let t=n[e];for(let s=e;s--;){let i=n[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Vi(n,e,t){n.rawProgramDateTime?t.push(n):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime)}function zn(n,e,t,s){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",s&&(n.levelkeys=s),n.initSegment=null}function Xn(n,e,t){n.levelkeys=e;let{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(n)}function qe(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Qn(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function ci(n,e){let t=e.startPTS;if(O(t)){let s=0,i;e.sn>n.sn?(s=t-n.start,i=n):(s=n.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?e.setStart(n.start+(n.minEndPTS-n.start)):e.setStart(n.start+n.duration):e.setStart(Math.max(n.start-e.duration,0))}function to(n,e,t,s,i,r,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,l=s,h=e.startPTS,d=e.endPTS;if(O(h)){let v=Math.abs(h-t);n&&v>n.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${n.url}`):O(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,c=Math.max(t,h),t=Math.min(t,h),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,d),s=Math.max(s,d),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}let u=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;let f=e.sn;if(!n||f<n.startSN||f>n.endSN)return 0;let g,p=f-n.startSN,y=n.fragments;for(y[p]=e,g=p;g>0;g--)ci(y[g],y[g-1]);for(g=p;g<y.length-1;g++)ci(y[g],y[g+1]);return n.fragmentHint&&ci(y[y.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,u}function Hc(n,e,t){if(n===e)return;let s=null,i=n.fragments;for(let h=i.length-1;h>=0;h--){let d=i[h].initSegment;if(d){s=d;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let r;qc(n,e,(h,d,u,f)=>{if((!e.startCC||e.skippedSegments)&&d.cc!==h.cc){let g=h.cc-d.cc;for(let p=u;p<f.length;p++)f[p].cc+=g;e.endCC=f[f.length-1].cc}O(h.startPTS)&&O(h.endPTS)&&(d.setStart(d.startPTS=h.startPTS),d.startDTS=h.startDTS,d.maxStartPTS=h.maxStartPTS,d.endPTS=h.endPTS,d.endDTS=h.endDTS,d.minEndPTS=h.minEndPTS,d.setDuration(h.endPTS-h.startPTS),d.duration&&(r=d),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(d.elementaryStreams=h.elementaryStreams),d.loader=h.loader,h.hasStats&&(d.stats=h.stats),h.initSegment&&(d.initSegment=h.initSegment,s=h.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(h=>{var d;h&&(!h.initSegment||h.initSegment.relurl===((d=s)==null?void 0:d.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Yc(n.dateRanges,e,t));let h=n.fragments.filter(d=>d.rawProgramDateTime);if(n.hasProgramDateTime&&!e.hasProgramDateTime)for(let d=1;d<o.length;d++)o[d].programDateTime===null&&Vi(o[d],o[d-1],h);eo(h,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var c;let h=ro(n,e.startSN-1);e.startCC=(c=h?.cc)!=null?c:a[0].cc}Wc(n.partList,e.partList,(h,d)=>{d.elementaryStreams=h.elementaryStreams,d.stats=h.stats}),r?to(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):so(n,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;let l=e.advancedDateTime;if(e.advanced&&l){let h=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=h),e.driftEndTime=l,e.driftEnd=h}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=n.requestScheduled)}function Yc(n,e,t){let{dateRanges:s,recentlyRemovedDateranges:i}=e,r=ie({},n);i&&i.forEach(c=>{delete r[c]});let o=Object.keys(r).length;return o?(Object.keys(s).forEach(c=>{let l=r[c],h=new Ds(s[c].attr,l);h.isValid?(r[c]=h,l||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ne(s[c].attr)}"`)}),r):s}function Wc(n,e,t){if(n&&e){let s=0;for(let i=0,r=n.length;i<=r;i++){let a=n[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function qc(n,e,t){let s=e.skippedSegments,i=Math.max(n.startSN,e.startSN)-e.startSN,r=(n.fragmentHint?1:0)+(s?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,a=e.startSN-n.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments;for(let l=i;l<=r;l++){let h=c[a+l],d=o[l];if(s&&!d&&h&&(d=e.fragments[l]=h),h&&d){t(h,d,l,o);let u=h.relurl,f=d.relurl;if(u&&jc(u,f)){e.playlistParsingError=Zn(`media sequence mismatch ${d.sn}:`,n,e,h,d);return}else if(h.cc!==d.cc){e.playlistParsingError=Zn(`discontinuity sequence mismatch (${h.cc}!=${d.cc})`,n,e,h,d);return}}}}function Zn(n,e,t,s,i){return new Error(`${n} ${i.url}
11
+ Time to underbuffer: ${ee.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,Y>g){let z=this.findBestLevel(this.hls.levels[g].bitrate,g,Y,0,ee,1,1);z===-1&&(z=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=z,this.resetEstimator(this.hls.levels[z].bitrate)}}};y||U>K*2?j():this.timer=self.setInterval(j,K*1e3),a.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:n,stats:d})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new Ri(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i: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 R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{let s=t.frag,{fragCurrent:i,partCurrent:n}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){let a=performance.now(),o=n?n.stats:s.stats,c=a-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){let h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(h,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){let n=e+s/t,a=i?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let s=this.hls.config,{loading:i}=t.stats,n=i.end-i.first;F(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){let i=s?s.stats:t.stats;if(t.type===B.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let n=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,c=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:c},a.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){let n={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:s,part:i}=t,n=i!=null&&i.stats.loaded?i.stats:s.stats;if(n.aborted||this.ignoreFragment(s))return;let a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==B.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,n=this.findBestLevel(s,t,e,0,i,1,1);if(n>-1)return n;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=s&&i?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:s}=this;if(s.levels.length<=1)return s.loadLevel;let{maxAutoLevel:i,config:n,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay(),d=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(l){let y=this.findBestLevel(c,a,i,l,0,d,h);if(y>=0)return this.rebufferNotice=-1,y}let u=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){let y=this.bitrateTestDelay;y&&(u=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=h=1)}let g=this.findBestLevel(c,a,i,l,u,d,h);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;let f=s.levels[a],p=s.loadLevelObj;return p&&f?.bitrate<p.bitrate?a:s.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,n,a,o){var c;let l=i+n,d=this.lastLoadedFragLevel,h=d===-1?this.hls.firstLevel:d,{fragCurrent:u,partCurrent:g}=this,{levels:f,allAudioTracks:p,loadLevel:y,config:v}=this.hls;if(f.length===1)return 0;let E=f[h],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),x=y===-1||d===-1,A,_="SDR",S=E?.frameRate||0,{audioPreference:I,videoPreference:b}=v,L=this.audioTracksByGroup||(this.audioTracksByGroup=qa(p)),D=-1;if(x){if(this.firstSelection!==-1)return this.firstSelection;let k=this.codecTiers||(this.codecTiers=Ac(f,L,t,s)),G=xc(k,_,e,I,b),{codecSet:N,videoRanges:K,minFramerate:Y,minBitrate:w,minIndex:M,preferHDR:j}=G;D=M,A=N,_=j?K[K.length-1]:K[0],S=Y,e=Math.max(e,w),this.log(`picked start tier ${re(G)}`)}else A=E?.codecSet,_=E?.videoRange;let C=g?g.duration:u?u.duration:0,$=this.bwEstimator.getEstimateTTFB()/1e3,H=[];for(let k=s;k>=t;k--){var U;let G=f[k],N=k>h;if(!G)continue;if(v.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){let z=navigator.mediaCapabilities;typeof z?.decodingInfo=="function"&&uc(G,L,_,S,e,I)?(G.supportedPromise=Ya(G,L,z,this.supportedCache),G.supportedPromise.then(Z=>{if(!this.hls)return;G.supportedResult=Z;let Se=this.hls.levels,ye=Se.indexOf(G);Z.error?this.warn(`MediaCapabilities decodingInfo error: "${Z.error}" for level ${ye} ${re(Z)}`):Z.supported?Z.decodingInfoResults.some(we=>we.smooth===!1||we.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ye} not smooth or powerEfficient: ${re(Z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ye} ${re(Z)}`),ye>-1&&Se.length>1&&(this.log(`Removing unsupported level ${ye}`),this.hls.removeLevel(ye),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Z}`)})):G.supportedResult=Va}if((A&&G.codecSet!==A||_&&G.videoRange!==_||N&&S>G.frameRate||!N&&S>0&&S<G.frameRate||(U=G.supportedResult)!=null&&(U=U.decodingInfoResults)!=null&&U.some(z=>z.smooth===!1))&&(!x||k!==D)){H.push(k);continue}let K=G.details,Y=(g?K?.partTarget:K?.averagetargetduration)||C,w;N?w=o*e:w=a*e;let M=C&&i>=C*2&&n===0?G.averageBitrate:G.maxBitrate,j=this.getTimeToLoadFrag($,w,M*Y,K===void 0);if(w>=M&&(k===d||G.loadError===0&&G.fragmentError===0)&&(j<=$||!F(j)||T&&!this.bitrateTestDelay||j<l)){let z=this.forcedAutoLevel;return k!==y&&(z===-1||z!==y)&&(H.length&&this.trace(`Skipped level(s) ${H.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[H[0]].codecs}" ${f[H[0]].videoRange}; not compatible with "${A}" ${_}`),this.info(`switch candidate:${h}->${k} adjustedbw(${Math.round(w)})-bitrate=${Math.round(w-M)} ttfb:${$.toFixed(1)} avgDuration:${Y.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${x} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${y}`)),x&&(this.firstSelection=k),k}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},ja={search:function(r,e){let t=0,s=r.length-1,i=null,n=null;for(;t<=s;){i=(t+s)/2|0,n=r[i];let a=e(n);if(a>0)t=i+1;else if(a<0)s=i-1;else return n}return null}};function Rc(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!F(e))return null;let s=r[0].programDateTime;if(e<(s||0))return null;let i=r[r.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let n=0;n<r.length;++n){let a=r[n];if(Pc(e,t,a))return a}return null}function pt(r,e,t=0,s=0,i=.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)&&wr(t,s,n)===0||_c(n,r,Math.min(i,s))))return n;let a=ja.search(e,wr.bind(null,t,s));return a&&(a!==r||!n)?a:n}function _c(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){let s=e.tagList.reduce((i,n)=>(n[0]==="INF"&&(i+=parseFloat(n[1])),i),t);return r.start<=s}return!1}function wr(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=r?1:t.start-s>r&&t.start?-1:0}function Pc(r,e,t){let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>r}function za(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){let s=r.fragments,{fragmentHint:i}=r;i&&(s=s.concat(i));let n;return ja.search(s,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 Rs(r){switch(r.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Xa(r){return r.details.startsWith("key")}function Qa(r){return Xa(r)&&!!r.frag&&!r.frag.decryptdata}function Mr(r,e){let t=Rs(e);return r.default[`${t?"timeout":"error"}Retry`]}function Qn(r,e){let t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function Or(r){return te(te({},r),{errorRetry:null,timeoutRetry:null})}function _s(r,e,t,s){if(!r)return!1;let i=s?.code,n=e<r.maxNumRetry&&(Dc(i)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,s,n):n}function Dc(r){return Mi(r)||!!r&&(r<400||r>499)}function Mi(r){return r===0&&navigator.onLine===!1}var me={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},_e={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},Oi=class extends Re{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(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===B.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;let i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(a=>i.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 s;if(t.fatal)return;let i=this.hls,n=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=It();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=me.SendAlternateToPenaltyBox;return}case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var a;let c=t.parent===B.MAIN?t.level:i.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let c=i.loadLevelObj;if(c&&(n.type===Q.AUDIO_TRACK&&c.hasAudioGroup(n.groupId)||n.type===Q.SUBTITLE_TRACK&&c.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=me.SendAlternateToPenaltyBox,t.errorAction.flags=_e.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:me.SendAlternateToPenaltyBox,flags:_e.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:t.errorAction={action:me.SendAlternateToPenaltyBox,flags:_e.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction=It();return}t.type===V.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=It())}getPlaylistRetryOrSwitchAction(e,t){let s=this.hls,i=Mr(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(_s(i,n,Rs(e),e.response))return{action:me.RetryRequest,flags:_e.None,retryConfig:i,retryCount:n};let o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Mr(Xa(e)?a:n,e),c=t.levels.reduce((d,h)=>d+h.fragmentError,0);if(i&&(e.details!==R.FRAG_GAP&&i.fragmentError++,!Qa(e)&&_s(o,c,Rs(e),e.response)))return{action:me.RetryRequest,flags:_e.None,retryConfig:o,retryCount:c};let l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){let s=this.hls;t==null&&(t=s.loadLevel);let i=this.hls.levels[t];if(i){var n,a;let l=e.details;i.loadError++,l===R.BUFFER_APPEND_ERROR&&i.fragmentError++;let d=-1,{levels:h,loadLevel:u,minAutoLevel:g,maxAutoLevel:f}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);let p=(n=e.frag)==null?void 0:n.type,v=(p===B.AUDIO&&l===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:_})=>i.audioCodec!==_),T=e.sourceBufferName==="video"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR)&&h.some(({codecSet:_,audioCodec:S})=>i.codecSet!==_&&i.audioCodec===S),{type:x,groupId:A}=(a=e.context)!=null?a:{};for(let _=h.length;_--;){let S=(_+u)%h.length;if(S!==u&&S>=g&&S<=f&&h[S].loadError===0){var o,c;let I=h[S];if(l===R.FRAG_GAP&&p===B.MAIN&&e.frag){let b=h[S].details;if(b){let L=pt(e.frag,b.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(x===Q.AUDIO_TRACK&&I.hasAudioGroup(A)||x===Q.SUBTITLE_TRACK&&I.hasSubtitleGroup(A))continue;if(p===B.AUDIO&&(o=i.audioGroups)!=null&&o.some(b=>I.hasAudioGroup(b))||p===B.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(b=>I.hasSubtitleGroup(b))||v&&i.audioCodec===I.audioCodec||T&&i.codecSet===I.codecSet||!v&&i.codecSet!==I.codecSet)continue}d=S;break}}if(d>-1&&s.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:me.SendAlternateToPenaltyBox,flags:_e.None,nextAutoLevel:d}}return{action:me.SendAlternateToPenaltyBox,flags:_e.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case me.DoNothing:break;case me.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case me.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,s=e.errorAction;if(!s)return;let{flags:i}=s,n=s.nextAutoLevel;switch(i){case _e.None:this.switchLevel(e,n);break;case _e.MoveAllAlternatesMatchingHDCP:{let c=this.getVariantLevelIndex(e.frag),l=t.levels[c],d=l?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=d,d==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(d){t.maxHdcpLevel=Ci[Ci.indexOf(d)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case _e.MoveAllAlternatesMatchingKey:{let c=e.decryptdata;if(c){let l=this.hls.levels,d=l.length;for(let u=d;u--;)if(this.variantHasKey(l[u],c)){var a,o;this.log(`Banned key found in level ${u} (${l[u].bitrate}bps) or audio group "${(a=l[u].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${ve(c.keyId||[])}`),l[u].fragmentError++,l[u].loadError++,this.log(`Removing level ${u} with key error (${e.error})`),this.hls.removeLevel(u)}let h=e.frag;if(this.hls.levels.length<d)s.resolved=!0;else if(h&&h.type!==B.MAIN){let u=h.decryptdata;u&&!c.matches(u)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,n)}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===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let s=ki(e.mimeType),i=this.hls.levels;for(let n=i.length;n--;)i[n][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${n} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(n))}}};function It(r){let e={action:me.DoNothing,flags:_e.None};return r&&(e.resolved=!0),e}var fe={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Fi=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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let s=this.activePartLists[t];if(s)for(let i=s.length;i--;){let n=s[i];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,s){let{fragments:i}=this,n=Object.keys(i);for(let a=n.length;a--;){let o=i[n[a]];if(o?.body.type===t&&(!s||o.buffered)){let c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,n){this.timeRanges&&(this.timeRanges[e]=t);let a=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{let c=this.fragments[o];if(!c||a>=c.body.sn)return;if(!c.buffered&&(!c.loaded||n)){c.body.type===s&&this.removeFragment(c.body);return}let l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(d=>{let h=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return h&&this.removeFragment(c.body),h})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;let s=e.frag,i=yt(s),n=this.fragments[i];if(!n||n.buffered&&s.gap)return;let a=!s.relurl;Object.keys(t).forEach(o=>{let c=s.elementaryStreams[o];if(!c)return;let l=t[o],d=a||c.partial===!0;n.range[o]=this.getBufferedTimes(s,e.part,d,l)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,s),is(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let s=this.activePartLists[t];s&&(this.activePartLists[t]=Fr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){let s=yt(e),i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){let n={time:[],partial:s},a=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||a;for(let d=0;d<i.length;d++){let h=i.start(d)-this.bufferPadding,u=i.end(d)+this.bufferPadding;if(l>=h&&c<=u){n.time.push({startPTS:Math.max(a,i.start(d)),endPTS:Math.min(o,i.end(d))});break}else if(a<u&&o>h){let g=Math.max(a,i.start(d)),f=Math.min(o,i.end(d));f>g&&(n.partial=!0,n.time.push({startPTS:g,endPTS:f}))}else if(o<=h)break}return n}getPartialFragment(e){let t=null,s,i,n,a=0,{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{let d=c[l];d&&is(d)&&(i=d.body.start-o,n=d.body.end+o,e>=i&&e<=n&&(s=Math.min(e-i,n-e),a<=s&&(t=d.body,a=s)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||is(t))}getState(e){let t=yt(e),s=this.fragments[t];return s?s.buffered?is(s)?fe.PARTIAL:fe.OK:fe.APPENDING:fe.NOT_LOADED}isTimeBuffered(e,t,s){let i,n;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,n=s.end(a)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;let s=t.frag,i=t.part?null:t,n=yt(s);this.fragments[n]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:s,part:i,timeRanges:n,type:a}=t;if(s.sn==="initSegment")return;let o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=n;let c=n[a];this.detectEvictedFragments(a,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=yt(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){let n=t[s[i]];if(n?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,n){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||n)&&this.removeFragment(c)})}removeFragment(e){let t=yt(e);e.clearElementaryStreamInfo();let s=this.activePartLists[e.type];if(s){let i=e.sn;this.activePartLists[e.type]=Fr(s,n=>n.fragment.sn!==i)}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(s=>s.clearElementaryStreamInfo())}};function is(r){var e,t,s;return r.buffered&&!!(r.body.gap||(e=r.range.video)!=null&&e.partial||(t=r.range.audio)!=null&&t.partial||(s=r.range.audiovideo)!=null&&s.partial)}function yt(r){return`${r.type}_${r.level}_${r.sn}`}function Fr(r,e){return r.filter(t=>{let s=e(t);return s||t.clearElementaryStreamInfo(),s})}var nt={cbc:0,ctr:1},Ni=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case nt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case nt.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 kc(r){let e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}var Bi=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),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){let e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],n=s[1],a=s[2],o=s[3],c=this.invSubMix,l=c[0],d=c[1],h=c[2],u=c[3],g=new Uint32Array(256),f=0,p=0,y=0;for(y=0;y<256;y++)y<128?g[y]=y<<1:g[y]=y<<1^283;for(y=0;y<256;y++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[f]=v,t[v]=f;let E=g[f],T=g[E],x=g[T],A=g[v]*257^v*16843008;i[f]=A<<24|A>>>8,n[f]=A<<16|A>>>16,a[f]=A<<8|A>>>24,o[f]=A,A=x*16843009^T*65537^E*257^f*16843008,l[v]=A<<24|A>>>8,d[v]=A<<16|A>>>16,h[v]=A<<8|A>>>24,u[v]=A,f?(f=E^g[g[g[x^E]]],p^=g[g[p]]):f=p=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)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,c,l=this.keySchedule=new Uint32Array(a),d=this.invKeySchedule=new Uint32Array(a),h=this.sBox,u=this.rcon,g=this.invSubMix,f=g[0],p=g[1],y=g[2],v=g[3],E,T;for(o=0;o<a;o++){if(o<n){E=l[o]=t[o];continue}T=E,o%n===0?(T=T<<8|T>>>24,T=h[T>>>24]<<24|h[T>>>16&255]<<16|h[T>>>8&255]<<8|h[T&255],T^=u[o/n|0]<<24):n>6&&o%n===4&&(T=h[T>>>24]<<24|h[T>>>16&255]<<16|h[T>>>8&255]<<8|h[T&255]),l[o]=E=(l[o-n]^T)>>>0}for(c=0;c<a;c++)o=a-c,c&3?T=l[o]:T=l[o-4],c<4||o<=4?d[c]=T:d[c]=f[h[T>>>24]]^p[h[T>>>16&255]]^y[h[T>>>8&255]]^v[h[T&255]],d[c]=d[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){let i=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],d=o[2],h=o[3],u=this.uint8ArrayToUint32Array_(s),g=u[0],f=u[1],p=u[2],y=u[3],v=new Int32Array(e),E=new Int32Array(v.length),T,x,A,_,S,I,b,L,D,C,$,H,U,k,G=this.networkToHostOrderSwap;for(;t<v.length;){for(D=G(v[t]),C=G(v[t+1]),$=G(v[t+2]),H=G(v[t+3]),S=D^n[0],I=H^n[1],b=$^n[2],L=C^n[3],U=4,k=1;k<i;k++)T=c[S>>>24]^l[I>>16&255]^d[b>>8&255]^h[L&255]^n[U],x=c[I>>>24]^l[b>>16&255]^d[L>>8&255]^h[S&255]^n[U+1],A=c[b>>>24]^l[L>>16&255]^d[S>>8&255]^h[I&255]^n[U+2],_=c[L>>>24]^l[S>>16&255]^d[I>>8&255]^h[b&255]^n[U+3],S=T,I=x,b=A,L=_,U=U+4;T=a[S>>>24]<<24^a[I>>16&255]<<16^a[b>>8&255]<<8^a[L&255]^n[U],x=a[I>>>24]<<24^a[b>>16&255]<<16^a[L>>8&255]<<8^a[S&255]^n[U+1],A=a[b>>>24]<<24^a[L>>16&255]<<16^a[S>>8&255]<<8^a[I&255]^n[U+2],_=a[L>>>24]<<24^a[S>>16&255]<<16^a[I>>8&255]<<8^a[b&255]^n[U+3],E[t]=G(T^g),E[t+1]=G(_^f),E[t+2]=G(A^p),E[t+3]=G(x^y),g=D,f=C,p=$,y=H,t=t+4}return E.buffer}},$i=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){let e=Cc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function Cc(r){switch(r){case nt.cbc:return"AES-CBC";case nt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}var wc=16,Vt=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let s=self.crypto;s&&(this.subtle=s.subtle||s.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 s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?kc(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((n,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);let c=this.flush();c?n(c.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){let{currentIV:n,currentResult:a,remainderData:o}=this;if(i!==nt.cbc||t.byteLength!==16)return se.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Oe(o,e),this.remainderData=null);let c=this.getValidChunk(e);if(!c.length)return null;n&&(s=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Bi),l.expandKey(t);let d=a;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new $i(this.subtle,t,i)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Ni(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(se.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);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,s=e.length-e.length%wc;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(se.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Nr=Math.pow(2,17),Ui=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){let s=e.url;if(!s)return Promise.reject(new Ue({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();let i=this.config,n=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){c($r(e));return}else e.gap=!1;let l=this.loader=n?new n(i):new a(i),d=Br(e);e.loader=l;let h=Or(i.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Nr};e.stats=l.stats;let g={onSuccess:(f,p,y,v)=>{this.resetLoader(e,l);let E=f.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:e,part:null,payload:E,networkDetails:v})},onError:(f,p,y,v)=>{this.resetLoader(e,l),c(new Ue({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:te({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:v}))},onAbort:(f,p,y)=>{this.resetLoader(e,l),c(new Ue({type:V.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,p,y)=>{this.resetLoader(e,l),c(new Ue({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:y,stats:f}))}};t&&(g.onProgress=(f,p,y,v)=>t({frag:e,part:null,payload:y,networkDetails:v})),l.load(d,u,g)})}loadPart(e,t,s){this.abort();let i=this.config,n=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c($r(e,t));return}let l=this.loader=n?new n(i):new a(i),d=Br(e,t);e.loader=l;let h=Or(i.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Nr};t.stats=l.stats,l.load(d,u,{onSuccess:(g,f,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:g.data,networkDetails:y};s(v),o(v)},onError:(g,f,p,y)=>{this.resetLoader(e,l),c(new Ue({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:te({url:d.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:y}))},onAbort:(g,f,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new Ue({type:V.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,f,p)=>{this.resetLoader(e,l),c(new Ue({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:g}))}})})}updateStatsFromPart(e,t){let s=e.stats,i=t.stats,n=i.total;if(s.loaded+=i.loaded,n){let c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/n),c),h=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+h}else s.total=Math.max(s.loaded,s.total);let a=s.loading,o=i.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,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function Br(r,e=null){let t=e||r,s={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(F(i)&&F(n)){var a;let o=i,c=n;if(r.sn==="initSegment"&&Mc((a=r.decryptdata)==null?void 0:a.method)){let l=n-i;l%16&&(c=n+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function $r(r,e){let t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),s={type:V.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(s.part=e),(e||r).stats.aborted=!0,new Ue(s)}function Mc(r){return r==="AES-128"||r==="AES-256"}var Ue=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Ps=class extends Re{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)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Ht=class{constructor(e,t,s,i=0,n=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=ns(),this.buffering={audio:ns(),video:ns(),audiovideo:ns()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=n,this.partial=a}};function ns(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Ur={length:0,start:()=>0,end:()=>0},q=class r{static isBuffered(e,t){if(e){let s=r.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))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 s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){let i=r.bufferedRanges(e);if(i.length)return r.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((d,h)=>d.start-h.start||h.end-d.end);let i=-1,n=[];if(s)for(let d=0;d<e.length;d++){t>=e[d].start&&t<=e[d].end&&(i=d);let h=n.length;if(h){let u=n[h-1].end;e[d].start-u<s?e[d].end>u&&(n[h-1].end=e[d].end):n.push(e[d])}else n.push(e[d])}else n=e;let a=0,o,c=t,l=t;for(let d=0;d<n.length;d++){let h=n[d].start,u=n[d].end;if(i===-1&&t>=h&&t<=u&&(i=d),t+s>=h&&t<u)c=h,l=u,a=l-t;else if(t+s<h){o=h;break}}return{len:a,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Ur}catch(t){return se.log("failed to get media.buffered",t),Ur}}},Za=/\{\$([a-zA-Z0-9-_]+)\}/g;function Gr(r){return Za.test(r)}function Gi(r,e){if(r.variableList!==null||r.hasVariableRefs){let t=r.variableList;return e.replace(Za,s=>{let i=s.substring(2,s.length-1),n=t?.[i];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):n})}return e}function Kr(r,e,t){let s=r.variableList;s||(r.variableList=s={});let i,n;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(i))n=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(a){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,n=e.VALUE;i in s?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=n||""}function Oc(r,e,t){let s=e.IMPORT;if(t&&s in t){let i=r.variableList;i||(r.variableList=i={}),i[s]=t[s]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}var Fc=/^(\d+)x(\d+)$/,Vr=/(.+?)=(".*?"|.*?)(?:,|$)/g,ae=class r{constructor(e,t){typeof e=="string"&&(e=r.parseAttrList(e,t)),ie(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 s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}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 s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,n)=>(i[n.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=Fc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s,i={};for(Vr.lastIndex=0;(s=Vr.exec(e))!==null;){let a=s[1].trim(),o=s[2],c=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1,l=!1;if(c)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=Gi(t,o);else if(!l&&!c)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":se.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}},Nc="com.apple.hls.interstitial";function Bc(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function $c(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}var Ds=class{constructor(e,t,s=0){var i;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=(i=t?.tagOrder)!=null?i:s,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){se.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ie(new ae({}),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 this.attr){let n=t?.endDate||new Date(this.attr["END-DATE"]);F(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?(se.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(F(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===Nc}get isValid(){return!!this.id&&!this._badValueForSameId&&F(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)}},Uc=10,Ki=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.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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?F(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Uc}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 ks(r,e){return r.length===e.length?!r.some((t,s)=>t!==e[s]):!1}function Hr(r,e){return!r&&!e?!0:!r||!e?!1:ks(r,e)}function bt(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function Zn(r){switch(r){case"AES-128":case"AES-256":return nt.cbc;case"AES-256-CTR":return nt.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Jn(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Vi(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function Gc(r){let e=Vi(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Ja(r){let e=function(s,i,n){let a=s[i];s[i]=s[n],s[n]=a};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function eo(r){let e=r.split(":"),t=null;if(e[0]==="data"&&e.length===2){let s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){let n=i[0]==="base64",a=i[1];n?(s.splice(-1,1),t=Jn(a)):t=Gc(a)}}return t}var Cs=typeof self<"u"?self:void 0,oe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ee={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ms(r){switch(r){case Ee.FAIRPLAY:return oe.FAIRPLAY;case Ee.PLAYREADY:return oe.PLAYREADY;case Ee.WIDEVINE:return oe.WIDEVINE;case Ee.CLEARKEY:return oe.CLEARKEY}}function li(r){switch(r){case oe.FAIRPLAY:return Ee.FAIRPLAY;case oe.PLAYREADY:return Ee.PLAYREADY;case oe.WIDEVINE:return Ee.WIDEVINE;case oe.CLEARKEY:return Ee.CLEARKEY}}function Ot(r){let{drmSystems:e,widevineLicenseUrl:t}=r,s=e?[oe.FAIRPLAY,oe.WIDEVINE,oe.PLAYREADY,oe.CLEARKEY].filter(i=>!!e[i]):[];return!s[oe.WIDEVINE]&&t&&s.push(oe.WIDEVINE),s}var to=(function(r){return Cs!=null&&(r=Cs.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Kc(r,e,t,s){let i;switch(r){case oe.FAIRPLAY:i=["cenc","sinf"];break;case oe.WIDEVINE:case oe.PLAYREADY:i=["cenc"];break;case oe.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Vc(i,e,t,s)}function Vc(r,e,t,s){return[{initDataTypes:r,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Hc(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function so(r){let e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let c=Jn(o).subarray(0,16);return Ja(c),c}}return null}var vt={},Dt=class r{static clearKeyUriToKeyIdMap(){vt={}}static setKeyIdForUri(e,t){vt[e]=t}static addKeyIdForUri(e){let t=Object.keys(vt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),vt[e]=s,s}constructor(e,t,s,i=[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.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!bt(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(wa(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ks(e.keyFormatVersions,this.keyFormatVersions)&&Hr(e.iv,this.iv)&&Hr(e.keyId,this.keyId)}isSupported(){if(this.method){if(bt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ee.FAIRPLAY:case Ee.WIDEVINE:case Ee.PLAYREADY:case Ee.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(bt(this.method)){let n=this.iv;return n||(typeof e!="number"&&(se.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=Wc(e)),new r(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){let n=vt[this.uri];if(n&&!ks(this.keyId,n)&&r.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let s=eo(this.uri);if(s)switch(this.keyFormat){case Ee.WIDEVINE:if(this.pssh=s,!this.keyId){let n=ic(s.buffer);if(n.length){var i;let a=n[0];this.keyId=(i=a.kids)!=null&&i.length?a.kids[0]:null}}this.keyId||(this.keyId=Yr(t));break;case Ee.PLAYREADY:{let n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=sc(n,null,s),this.keyId=so(s);break}default:{let n=s.subarray(0,16);if(n.length!==16){let a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=Yc(t),n||(n=Yr(t),n||(n=vt[this.uri])),n&&(this.keyId=n,r.setKeyIdForUri(this.uri,n))}return this}};function Yc(r){let e=r?.[Ee.WIDEVINE];return e?e.keyId:null}function Yr(r){let e=r?.[Ee.PLAYREADY];if(e){let t=eo(e.uri);if(t)return so(t)}return null}function Wc(r){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}var Wr=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,qr=/#EXT-X-MEDIA:(.*)/g,qc=/^#EXT(?:INF|-X-TARGETDURATION):/m,ci=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),jc=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),ht=class r{static findGroup(e,t){for(let s=0;s<e.length;s++){let i=e[s];if(i.id===t)return i}}static resolve(e,t){return qn.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return qc.test(e)}static parseMasterPlaylist(e,t){let s=Gr(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if(Wr.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=Wr.exec(e))!=null;)if(a[1]){var o;let l=new ae(a[1],i),d=Gi(i,a[2]),h={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:r.resolve(d,t)},u=l.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),Xr(l.CODECS,h);let g=l["SUPPLEMENTAL-CODECS"];g&&(h.supplemental={},Xr(g,h.supplemental)),(o=h.unknownCodecs)!=null&&o.length||n.push(h),i.levels.push(h)}else if(a[3]){let l=a[3],d=a[4];switch(l){case"SESSION-DATA":{let h=new ae(d,i),u=h["DATA-ID"];u&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[u]=h);break}case"SESSION-KEY":{let h=jr(d,t,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):se.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{let h=new ae(d,i);Kr(i,h,t)}break}case"CONTENT-STEERING":{let h=new ae(d,i);i.contentSteering={uri:r.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=zr(d);break}}}let c=n.length>0&&n.length<i.levels.length;return i.levels=c?n:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i,n={},a=s.levels,o={AUDIO:a.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]},c=0;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){let l=new ae(i[1],s),d=l.TYPE;if(d){let h=o[d],u=n[d]||[];n[d]=u;let g=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,v=l["INSTREAM-ID"],E={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||g||"",type:d,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:g,url:l.URI?r.resolve(l.URI,t):""};if(f&&(E.assocLang=f),p&&(E.channels=p),y&&(E.characteristics=y),v&&(E.instreamId=v),h!=null&&h.length){let T=r.findGroup(h,E.groupId)||h[0];Qr(E,T,"audioCodec"),Qr(E,T,"textCodec")}u.push(E)}}return n}static parseLevelPlaylist(e,t,s,i,n,a){var o;let c={url:t},l=new Ki(t),d=l.fragments,h=[],u=null,g=0,f=0,p=0,y=0,v=0,E=null,T=new Ft(i,c),x,A,_,S=-1,I=!1,b=null,L;if(ci.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Gr(e),((o=ci.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(x=ci.exec(e))!==null;){I&&(I=!1,T=new Ft(i,c),T.playlistOffset=p,T.setStart(p),T.sn=g,T.cc=y,v&&(T.bitrate=v),T.level=s,u&&(T.initSegment=u,u.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),b&&(T.setByteRange(b),b=null)));let H=x[1];if(H){T.duration=parseFloat(H);let U=(" "+x[2]).slice(1);T.title=U||null,T.tagList.push(U?["INF",H,U]:["INF",H])}else if(x[3]){if(F(T.duration)){T.playlistOffset=p,T.setStart(p),_&&Jr(T,_,l),T.sn=g,T.level=s,T.cc=y,d.push(T);let U=(" "+x[3]).slice(1);T.relurl=Gi(l,U),Hi(T,E,h),E=T,p+=T.duration,g++,f=0,I=!0}}else{if(x=x[0].match(jc),!x){se.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<x.length&&x[A]===void 0;A++);let U=(" "+x[A]).slice(1),k=(" "+x[A+1]).slice(1),G=x[A+2]?(" "+x[A+2]).slice(1):null;switch(U){case"BYTERANGE":E?T.setByteRange(k,E):T.setByteRange(k);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=k,T.tagList.push(["PROGRAM-DATE-TIME",k]),S===-1&&(S=d.length);break;case"PLAYLIST-TYPE":l.type&&je(l,U,x),l.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?je(l,U,x):d.length>0&&ea(l,U,x),g=l.startSN=parseInt(k);break;case"SKIP":{l.skippedSegments&&je(l,U,x);let N=new ae(k,l),K=N.decimalInteger("SKIPPED-SEGMENTS");if(F(K)){l.skippedSegments+=K;for(let w=K;w--;)d.push(null);g+=K}let Y=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");Y&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(Y.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&je(l,U,x),l.targetduration=Math.max(parseInt(k),1);break;case"VERSION":l.version!==null&&je(l,U,x),l.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||je(l,U,x),l.live=!1;break;case"#":(k||G)&&T.tagList.push(G?[k,G]:[k]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([U]);break;case"BITRATE":T.tagList.push([U,k]),v=parseInt(k)*1e3,F(v)?T.bitrate=v:v=0;break;case"DATERANGE":{let N=new ae(k,l),K=new Ds(N,l.dateRanges[N.ID],l.dateRangeTagCount);l.dateRangeTagCount++,K.isValid||l.skippedSegments?l.dateRanges[K.id]=K:se.warn(`Ignoring invalid DATERANGE tag: "${k}"`),T.tagList.push(["EXT-X-DATERANGE",k]);break}case"DEFINE":{{let N=new ae(k,l);"IMPORT"in N?Oc(l,N,a):Kr(l,N,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?je(l,U,x):d.length>0&&ea(l,U,x),l.startCC=y=parseInt(k);break;case"KEY":{let N=jr(k,t,l);if(N.isSupported()){if(N.method==="NONE"){_=void 0;break}_||(_={});let K=_[N.keyFormat];K!=null&&K.matches(N)||(K&&(_=ie({},_)),_[N.keyFormat]=N)}else se.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${k}"`);break}case"START":l.startTimeOffset=zr(k);break;case"MAP":{let N=new ae(k,l);if(T.duration){let K=new Ft(i,c);Zr(K,N,s,_),u=K,T.initSegment=u,u.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime)}else{let K=T.byteRangeEndOffset;if(K){let Y=T.byteRangeStartOffset;b=`${K-Y}@${Y}`}else b=null;Zr(T,N,s,_),u=T,I=!0}u.cc=y;break}case"SERVER-CONTROL":{L&&je(l,U,x),L=new ae(k),l.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),l.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&je(l,U,x);let N=new ae(k);l.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=l.partList;N||(N=l.partList=[]);let K=f>0?N[N.length-1]:void 0,Y=f++,w=new ae(k,l),M=new Di(w,T,c,Y,K);N.push(M),T.duration+=M.duration;break}case"PRELOAD-HINT":{let N=new ae(k,l);l.preloadHint=N;break}case"RENDITION-REPORT":{let N=new ae(k,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(N);break}default:se.warn(`line parsed but not handled: ${x}`);break}}}E&&!E.relurl?(d.pop(),p-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(Hi(T,E,h),T.cc=y,l.fragmentHint=T,_&&Jr(T,_,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));let D=d.length,C=d[0],$=d[D-1];if(p+=l.skippedSegments*l.targetduration,p>0&&D&&$){l.averagetargetduration=p/D;let H=$.sn;l.endSN=H!=="initSegment"?H:0,l.live||($.endList=!0),S>0&&(Xc(d,S),C&&h.unshift(C))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,h.length&&l.dateRangeTagCount&&C&&io(h,l),l.endCC=y,l}};function io(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 s=r[t-1],i=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let c=e.dateRanges[n[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let d=t;d--;){var a;if(((a=r[d])==null?void 0:a.sn)<e.startSN)break;let h=zc(e,l,r,d,i);if(h!==-1){c.tagAnchor=e.fragments[h].ref;break}}}}function zc(r,e,t,s,i){let n=t[s];if(n){let o=n.programDateTime;if(e>=o||s===0){var a;let c=(((a=t[s+1])==null?void 0:a.start)||i)-n.start;if(e<=o+c*1e3){let l=t[s].sn-r.startSN;if(l<0)return-1;let d=r.fragments;if(d.length>t.length){let u=(t[s+1]||d[d.length-1]).sn-r.startSN;for(let g=u;g>l;g--){let f=d[g].programDateTime;if(e>=f&&e<f+d[g].duration*1e3)return g}}return l}}}return-1}function jr(r,e,t){var s,i;let n=new ae(r,t),a=(s=n.METHOD)!=null?s:"",o=n.URI,c=n.hexadecimalInteger("IV"),l=n.KEYFORMATVERSIONS,d=(i=n.KEYFORMAT)!=null?i:"identity";o&&n.IV&&!c&&se.error(`Invalid IV: ${n.IV}`);let h=o?ht.resolve(o,e):"",u=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Dt(a,h,d,u,c,n.KEYID)}function zr(r){let t=new ae(r).decimalFloatingPoint("TIME-OFFSET");return F(t)?t:null}function Xr(r,e){let t=(r||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{let i=t.filter(n=>zn(n,s));i.length&&(e[`${s}Codec`]=i.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>i.indexOf(n)===-1))}),e.unknownCodecs=t}function Qr(r,e,t){let s=e[t];s&&(r[t]=s)}function Xc(r,e){let t=r[e];for(let s=e;s--;){let i=r[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Hi(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function Zr(r,e,t,s){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",s&&(r.levelkeys=s),r.initSegment=null}function Jr(r,e,t){r.levelkeys=e;let{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(r)}function je(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function ea(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function di(r,e){let t=e.startPTS;if(F(t)){let s=0,i;e.sn>r.sn?(s=t-r.start,i=r):(s=r.start-t,i=e),i.duration!==s&&i.setDuration(s)}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 no(r,e,t,s,i,n,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,n=i+e.duration);let c=t,l=s,d=e.startPTS,h=e.endPTS;if(F(d)){let v=Math.abs(d-t);r&&v>r.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${r.url}`):F(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,c=Math.max(t,d),t=Math.min(t,d),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,h),s=Math.max(s,h),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}let u=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=n;let g=e.sn;if(!r||g<r.startSN||g>r.endSN)return 0;let f,p=g-r.startSN,y=r.fragments;for(y[p]=e,f=p;f>0;f--)di(y[f],y[f-1]);for(f=p;f<y.length-1;f++)di(y[f],y[f+1]);return r.fragmentHint&&di(y[y.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,u}function Qc(r,e,t){if(r===e)return;let s=null,i=r.fragments;for(let d=i.length-1;d>=0;d--){let h=i[d].initSegment;if(h){s=h;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;ed(r,e,(d,h,u,g)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==d.cc){let f=d.cc-h.cc;for(let p=u;p<g.length;p++)g[p].cc+=f;e.endCC=g[g.length-1].cc}F(d.startPTS)&&F(d.endPTS)&&(h.setStart(h.startPTS=d.startPTS),h.startDTS=d.startDTS,h.maxStartPTS=d.maxStartPTS,h.endPTS=d.endPTS,h.endDTS=d.endDTS,h.minEndPTS=d.minEndPTS,h.setDuration(d.endPTS-d.startPTS),h.duration&&(n=h),e.PTSKnown=e.alignedSliding=!0),d.hasStreams&&(h.elementaryStreams=d.elementaryStreams),h.loader=d.loader,d.hasStats&&(h.stats=d.stats),d.initSegment&&(h.initSegment=d.initSegment,s=d.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(d=>{var h;d&&(!d.initSegment||d.initSegment.relurl===((h=s)==null?void 0:h.relurl))&&(d.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(d=>!d),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=e.skippedSegments;d--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Zc(r.dateRanges,e,t));let d=r.fragments.filter(h=>h.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let h=1;h<o.length;h++)o[h].programDateTime===null&&Hi(o[h],o[h-1],d);io(d,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var c;let d=oo(r,e.startSN-1);e.startCC=(c=d?.cc)!=null?c:a[0].cc}Jc(r.partList,e.partList,(d,h)=>{h.elementaryStreams=d.elementaryStreams,h.stats=d.stats}),n?no(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):ro(r,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;let l=e.advancedDateTime;if(e.advanced&&l){let d=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=d),e.driftEndTime=l,e.driftEnd=d}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function Zc(r,e,t){let{dateRanges:s,recentlyRemovedDateranges:i}=e,n=ie({},r);i&&i.forEach(c=>{delete n[c]});let o=Object.keys(n).length;return o?(Object.keys(s).forEach(c=>{let l=n[c],d=new Ds(s[c].attr,l);d.isValid?(n[c]=d,l||(d.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${re(s[c].attr)}"`)}),n):s}function Jc(r,e,t){if(r&&e){let s=0;for(let i=0,n=r.length;i<=n;i++){let a=r[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function ed(r,e,t){let s=e.skippedSegments,i=Math.max(r.startSN,e.startSN)-e.startSN,n=(r.fragmentHint?1:0)+(s?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,a=e.startSN-r.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let l=i;l<=n;l++){let d=c[a+l],h=o[l];if(s&&!h&&d&&(h=e.fragments[l]=d),d&&h){t(d,h,l,o);let u=d.relurl,g=h.relurl;if(u&&td(u,g)){e.playlistParsingError=ta(`media sequence mismatch ${h.sn}:`,r,e,d,h);return}else if(d.cc!==h.cc){e.playlistParsingError=ta(`discontinuity sequence mismatch (${d.cc}!=${h.cc})`,r,e,d,h);return}}}}function ta(r,e,t,s,i){return new Error(`${r} ${i.url}
12
12
  Playlist starting @${e.startSN}
13
13
  ${e.m3u8}
14
14
 
15
15
  Playlist starting @${t.startSN}
16
- ${t.m3u8}`)}function so(n,e,t=!0){let s=e.startSN+e.skippedSegments-n.startSN,i=n.fragments,r=s>=0,a=0;if(r&&s<i.length)a=i[s].start;else if(r&&e.startSN===n.endSN+1)a=n.fragmentEnd;else if(r&&t)a=n.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=n.fragmentStart;else return;Hi(e,a)}function Hi(n,e){if(e){let t=n.fragments;for(let s=n.skippedSegments;s<t.length;s++)t[s].addStart(e);n.fragmentHint&&n.fragmentHint.addStart(e)}}function io(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){let s=n.fragments;if(s.length&&t*4>e){let r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function ro(n,e,t){if(!n)return null;let s=n.fragments[e-n.startSN];return s||(s=n.fragmentHint,s&&s.sn===e)?s:e<n.startSN&&t&&t.sn===e?t:null}function Jn(n,e,t){return n?no(n.partList,e,t):null}function no(n,e,t){if(n)for(let s=n.length;s--;){let i=n[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function ao(n){n.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function jc(n,e){return n!==e&&e?ea(n)!==ea(e):!1}function ea(n){return n.replace(/\?[^?]*$/,"")}function Ft(n,e){for(let s=0,i=n.length;s<i;s++){var t;if(((t=n[s])==null?void 0:t.cc)===e)return n[s]}return null}function zc(n,e){return!!(n&&e.startCC<n.endCC&&e.endCC>n.startCC)}function ta(n,e){let t=n.start+e;n.startPTS=t,n.setStart(t),n.endPTS=t+n.duration}function oo(n,e){let t=e.fragments;for(let s=0,i=t.length;s<i;s++)ta(t[s],n);e.fragmentHint&&ta(e.fragmentHint,n),e.alignedSliding=!0}function Xc(n,e){n&&(lo(e,n),e.alignedSliding||Cs(e,n),!e.alignedSliding&&!e.skippedSegments&&so(n,e,!1))}function lo(n,e){if(!zc(e,n))return;let t=Math.min(e.endCC,n.endCC),s=Ft(e.fragments,t),i=Ft(n.fragments,t);if(!s||!i)return;se.log(`Aligning playlist at start of dicontinuity sequence ${t}`);let r=s.start-i.start;oo(r,n)}function Cs(n,e){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;let t=n.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r,a=Math.min(e.endCC,n.endCC);e.startCC<a&&n.startCC<a&&(i=Ft(s,a),r=Ft(t,a)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Ft(t,i.cc)||t[Math.floor(t.length/2)]);let o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;let l=(c-o)/1e3-(r.start-i.start);oo(l,n)}function xe(n,e,t){Le(n,e,t),n.addEventListener(e,t)}function Le(n,e,t){n.removeEventListener(e,t)}var Qc={toString:function(n){let e="",t=n.length;for(let s=0;s<t;s++)e+=`[${n.start(s).toFixed(3)}-${n.end(s).toFixed(3)}]`;return e}},D={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"},Ht=class extends _s{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=D.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,d=c?c.currentTime:0,u=q.bufferInfo(l||c,d,a.maxBufferHole),f=!u.len;if(this.log(`Media seeking to ${O(d)?d.toFixed(3):d}, state: ${h}, ${f?"out of":"in"} buffer`),this.state===D.ENDED)this.resetLoadingState();else if(o){let g=a.maxFragLookUpTolerance,p=o.start-g,y=o.start+o.duration+g;if(f||y<u.start||p>u.end){let v=d>y;(d<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);let g=this.lastCurrentTime;if(d>g&&(this.lastCurrentTime=d),!this.loadingParts){let p=Math.max(u.end,d),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${d.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,f&&(this.startPosition=d)),f&&this.state===D.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new Ui(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Kt(e.config)}registerListeners(){let{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===D.STOPPED)return;this.fragmentLoader.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=D.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;let r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=q.bufferedInfo(r,e.start,0));let a=e.nextStart;if(a&&a>i&&a<t.edge||this.media.currentTime<e.start)return!1;let c=t.partList;if(c!=null&&c.length){let h=c[c.length-1];return q.isBuffered(this.media,h.start+h.duration/2)}let l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}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 s=this.media=this.mediaBuffer=t.media;xe(s,"seeking",this.onMediaSeeking),xe(s,"ended",this.onMediaEnded);let i=this.config;this.levels&&i.autoStartLoad&&this.state===D.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){let s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Le(i,"seeking",this.onMediaSeeking),Le(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(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=D.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){let i=r=>{let a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;let a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===D.FRAG_LOADING||!this.fragCurrent&&a===D.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=D.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===D.STOPPED||this.state===D.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:s}=this;if(s.getState(e)===de.APPENDING){let r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===de.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;let i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{let i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{let{hls:i}=this,{frag:r,payload:a}=s,o=r.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&It(o.method)){let c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Xr(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{let h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===D.STOPPED||this.state===D.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let s=e.frag.stats;this.state!==D.STOPPED&&(this.state=D.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;let r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.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(m.ERROR,{type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let s=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:${s?Qc.toString(q.getBuffered(s)):"(detached)"})`),ce(e)){var i;if(e.type!==N.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=D.IDLE;return}}let r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=D.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:s,part:i,partsLoaded:r}=e,a=!r||r.length===0||r.some(c=>!c),o=new Vt(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=D.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(m.KEY_LOADED,u),this.state===D.KEY_LOADING&&(this.state=D.IDLE),u}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));let c=this.fragPrevious;if(ce(e)&&(!c||e.sn!==c.sn)){let u=this.shouldLoadParts(t.details,e.end);u!==this.loadingParts&&(this.log(`LL-Part loading ${u?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=u)}if(s=Math.max(e.start,s||0),this.loadingParts&&ce(e)){let u=a.partList;if(u&&i){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let f=this.getNextPart(u,e,s);if(f>-1){let g=u[f];e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${u.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=D.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,g,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,g,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(u,s))return Promise.resolve(null)}}if(ce(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=a.partList)==null?void 0:l.filter(u=>u.loaded).map(u=>`[${u.start}-${u.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),O(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=D.FRAG_LOADING;let h=this.config.progressive&&e.type!==N.SUBTITLE,d;return h&&o?d=o.then(u=>!u||this.fragContextChanged(u.frag)?null:this.fragmentLoader.load(e,i)).catch(u=>this.handleFragLoadError(u)):d=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([u])=>(!h&&i&&i(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,s,i){return new Promise((r,a)=>{var o;let c=[],l=(o=s.details)==null?void 0:o.partList,h=d=>{this.fragmentLoader.loadPart(e,d,i).then(u=>{c[d.index]=u;let f=u.part;this.hls.trigger(m.FRAG_LOADED,u);let g=Jn(s.details,e.sn,d.index+1)||no(l,e.sn,d.index+1);if(g)h(g);else return r({frag:e,part:f,partsLoaded:c})}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===I.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===K.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:K.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==D.PARSING){!this.fragCurrent&&this.state!==D.STOPPED&&this.state!==D.ERROR&&(this.state=D.IDLE);return}let{frag:s,part:i,level:r}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a);let o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;let r=e.partList[0];if(r.fragment.type===N.SUBTITLE)return!1;let a=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=a){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:a}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;let o=t[i],c=o.details,l=a>-1?Jn(c,r,a):null,h=l?l.fragment:ro(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==D.PARSING)return;let{data1:a,data2:o}=e,c=a;if(o&&(c=we(a,o)),!c.length)return;let l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let s=t.currentTime,i=q.bufferInfo(t,s,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;let i=this.getLoadPosition();if(!O(i))return null;let a=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,a)}getFwdBufferInfoAtPos(e,t,s,i){let r=q.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(r.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(r.nextStart,a.end)-t,i);return q.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){let{config:t}=this,s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){let i=e.nextStart;if(i&&s.start>i){let r=e.buffered;if(r){let a=e.len,o=e.bufferedIndex;for(let c=r.length-1;c>o;c--)r[c].start<s.start&&(a+=r[c].end-r[c].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){let s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=N.MAIN){let s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){let s=t.fragments,i=s.length;if(!i)return null;let{config:r}=this,a=t.fragmentStart,o=r.lowLatencyMode&&!!t.partList,c=null;if(t.live){let d=r.initialLiveManifestSize;if(i<d)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${d})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);let u=this.config.startPosition,f=this.hls.startPosition,g=this.hls.liveSyncPosition,p=((l=c)==null?void 0:l.start)||0,y,v;f!==-1&&f>=a?(y=f,v=f===u?"config":"next load start"):g!==null?(y=g,v="live edge"):(y=e,v="buffer pos"),y<p&&(y=p,v="live frag start"),y<a&&(y=a,v="playlist start"),(this.startPosition!=y||this.nextLoadPosition!=y)&&(this.log(`Setting startPosition to ${y.toFixed(3)} ${f===-1?"":`(from ${u}) `}based on ${v}. live edge: ${g} live frag start: ${p.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=y)}}else e<=a&&(c=s[0]);if(!c){let d=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,d,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){let d=c.sn-t.startSN;h=this.filterReplacedPrimary(s[d+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let s=this.fragmentTracker.getState(e);return s===de.OK||s===de.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,s,i,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){let c=a.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(sa(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(sa(this.config)&&e.type!==N.SUBTITLE){let s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){let a=i.event;if(a){if(a.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}let r=s?.playerQueue;if(r)for(let a=r.length;a--;){let o=r[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,a=!0;for(let o=0,c=e.length;o<c;o++){let l=e[o];if(a=a&&!l.independent,i>-1&&s<l.start)break;let h=l.loaded;h?i=-1:(r||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,s=this.fragPrevious,i=null;if(s){if(e.hasProgramDateTime&&(i=Tc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){let r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){let a=t[r-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Wa(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{let r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){let{config:i}=this,{fragPrevious:r}=this,{fragments:a,endSN:o}=s,{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&h!=null&&h.length&&c);d&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(a=a.concat(c),o=c.sn);let u;if(e<t){var f;let p=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;u=gt(r,a,e,p)}else u=a[a.length-1];if(u){let g=u.sn-s.startSN,p=this.fragmentTracker.getState(u);if((p===de.OK||p===de.PARTIAL&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!d||h[0].fragment.sn>u.sn||!s.live)&&u.level===r.level){let v=a[g+1];u.sn<o&&this.fragmentTracker.getState(v)!==de.OK?u=v:u=null}}return u}alignPlaylists(e,t,s){let i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;let r=e.fragmentStart,a=!t,o=e.alignedSliding&&O(r);if(a||!o&&!r){Xc(s,e);let c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);let i=this.timelineOffset;if(s===-1){let r=this.startTimeOffset!==null,a=r?this.startTimeOffset:e.startTimeOffset;a!==null&&O(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;let{media:t}=this,s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ce(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!==D.FRAG_LOADING_WAITING_RETRY)&&(this.state=D.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){let v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}let i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}let a=t.details===I.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(i,!0);let o=t.errorAction;if(!o){this.state=D.ERROR;return}let{action:c,flags:l,retryCount:h=0,retryConfig:d}=o,u=!!d,f=u&&c===ge.RetryRequest,g=u&&!o.resolved&&l===Re.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&g&&ce(i)&&!i.endList&&p&&!ja(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((f||g)&&h<d.maxNumRetry){var y;let v=wi((y=t.response)==null?void 0:y.code),E=zr(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=D.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){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 ${h+1}/${d.maxNumRetry} in ${E}ms`)}else if(d)if(this.resetFragmentErrors(e),h<d.maxNumRetry)!a&&c!==ge.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===ge.SendAlternateToPenaltyBox?this.state=D.WAITING_LEVEL:this.state=D.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!wi(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=D.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===D.PARSING||this.state===D.PARSED){let t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);let a=!r;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===N.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==D.STOPPED&&(this.state=D.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;let i=q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===D.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==D.STOPPED&&(this.state=D.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${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,s,i){let r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{let h=e.elementaryStreams[l];if(h){let d=h.endPTS-h.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${d})`),c||!1;let u=i?0:to(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:u,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;let c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){let l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=D.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===N.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}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}};function sa(n){return!!n.interstitialsController&&n.enableInterstitialPlayback!==!1}var ws=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,s;if(e.length)e.length===1?s=e[0]:s=Zc(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}};function Zc(n,e){let t=new Uint8Array(e),s=0;for(let i=0;i<n.length;i++){let r=n[i];t.set(r,s),s+=r.length}return t}var hi={exports:{}},ia;function Jc(){return ia||(ia=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,d,u){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,d||c,u),g=t?t+l:l;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,c._eventsCount++),c}function a(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,d;if(this._eventsCount===0)return l;for(d in h=this._events)e.call(h,d)&&l.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,d=this._events[h];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,f=d.length,g=new Array(f);u<f;u++)g[u]=d[u].fn;return g},o.prototype.listenerCount=function(l){var h=t?t+l:l,d=this._events[h];return d?d.fn?1:d.length:0},o.prototype.emit=function(l,h,d,u,f,g){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],v=arguments.length,E,T;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,d),!0;case 4:return y.fn.call(y.context,h,d,u),!0;case 5:return y.fn.call(y.context,h,d,u,f),!0;case 6:return y.fn.call(y.context,h,d,u,f,g),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];y.fn.apply(y.context,E)}else{var S=y.length,x;for(T=0;T<S;T++)switch(y[T].once&&this.removeListener(l,y[T].fn,void 0,!0),v){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,h);break;case 3:y[T].fn.call(y[T].context,h,d);break;case 4:y[T].fn.call(y[T].context,h,d,u);break;default:if(!E)for(x=1,E=new Array(v-1);x<v;x++)E[x-1]=arguments[x];y[T].fn.apply(y[T].context,E)}}return!0},o.prototype.on=function(l,h,d){return r(this,l,h,d,!1)},o.prototype.once=function(l,h,d){return r(this,l,h,d,!0)},o.prototype.removeListener=function(l,h,d,u){var f=t?t+l:l;if(!this._events[f])return this;if(!h)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!u||g.once)&&(!d||g.context===d)&&a(this,f);else{for(var p=0,y=[],v=g.length;p<v;p++)(g[p].fn!==h||u&&!g[p].once||d&&g[p].context!==d)&&y.push(g[p]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&a(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})(hi)),hi.exports}var eh=Jc(),Zr=Ml(eh),Yt="1.6.16",Pt={};function th(){return typeof __HLS_WORKER_BUNDLE__=="function"}function sh(){let n=Pt[Yt];if(n)return n.clientCount++,n;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),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Pt[Yt]=i,i}function ih(n){let e=Pt[n];if(e)return e.clientCount++,e;let t=new self.URL(n,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Pt[n]=i,i}function rh(n){let e=Pt[n||Yt];if(e&&e.clientCount--===1){let{worker:s,objectURL:i}=e;delete Pt[n||Yt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function co(n,e){return e+10<=n.length&&n[e]===51&&n[e+1]===68&&n[e+2]===73&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function Jr(n,e){return e+10<=n.length&&n[e]===73&&n[e+1]===68&&n[e+2]===51&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function qs(n,e){let t=0;return t=(n[e]&127)<<21,t|=(n[e+1]&127)<<14,t|=(n[e+2]&127)<<7,t|=n[e+3]&127,t}function Wt(n,e){let t=e,s=0;for(;Jr(n,e);){s+=10;let i=qs(n,e+6);s+=i,co(n,e+10)&&(s+=10),e+=s}if(s>0)return n.subarray(t,t+s)}function nh(n,e,t,s){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){let f=new Error(`invalid ADTS sampling index:${a}`);n.emit(m.ERROR,m.ERROR,{type:K.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}let o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[a],d=a;(o===5||o===29)&&(d-=3);let u=[o<<3|(d&14)>>1,(d&1)<<7|c<<3];return se.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${a})`),{config:u,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function ho(n,e){return n[e]===255&&(n[e+1]&246)===240}function uo(n,e){return n[e+1]&1?7:9}function en(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function ah(n,e){return e+5<n.length}function Ms(n,e){return e+1<n.length&&ho(n,e)}function oh(n,e){return ah(n,e)&&ho(n,e)&&en(n,e)<=n.length-e}function lh(n,e){if(Ms(n,e)){let t=uo(n,e);if(e+t>=n.length)return!1;let s=en(n,e);if(s<=t)return!1;let i=e+s;return i===n.length||Ms(n,i)}return!1}function fo(n,e,t,s,i){if(!n.samplerate){let r=nh(e,t,s,i);if(!r)return;ie(n,r)}}function go(n){return 1024*9e4/n}function ch(n,e){let t=uo(n,e);if(e+t<=n.length){let s=en(n,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function mo(n,e,t,s,i){let r=go(n.samplerate),a=s+i*r,o=ch(e,t),c;if(o){let{frameLength:d,headerLength:u}=o,f=u+d,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-u),c.set(e.subarray(t+u,e.length),0)):c=e.subarray(t+u,t+f);let p={unit:c,pts:a};return g||n.samples.push(p),{sample:p,length:f,missing:g}}let l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:a},length:l,missing:-1}}function hh(n,e){return Jr(n,e)&&qs(n,e+6)+10<=n.length-e}function dh(n){return n instanceof ArrayBuffer?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function di(n,e=0,t=1/0){return uh(n,e,t,Uint8Array)}function uh(n,e,t,s){let i=fh(n),r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);let a=gh(n)?n.byteOffset:0,o=(a+n.byteLength)/r,c=(a+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function fh(n){return n instanceof ArrayBuffer?n:n.buffer}function gh(n){return n&&n.buffer instanceof ArrayBuffer&&n.byteLength!==void 0&&n.byteOffset!==void 0}function mh(n){let e={key:n.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(n.size<2)return;if(n.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let s=n.data.subarray(1).indexOf(0);if(s===-1)return;let i=Pe(di(n.data,1,s)),r=n.data[2+s],a=n.data.subarray(3+s).indexOf(0);if(a===-1)return;let o=Pe(di(n.data,3+s,a)),c;return i==="-->"?c=Pe(di(n.data,4+s+a)):c=dh(n.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function ph(n){if(n.size<2)return;let e=Pe(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}}function yh(n){if(n.size<2)return;if(n.type==="TXXX"){let t=1,s=Pe(n.data.subarray(t),!0);t+=s.length+1;let i=Pe(n.data.subarray(t));return{key:n.type,info:s,data:i}}let e=Pe(n.data.subarray(1));return{key:n.type,info:"",data:e}}function vh(n){if(n.type==="WXXX"){if(n.size<2)return;let t=1,s=Pe(n.data.subarray(t),!0);t+=s.length+1;let i=Pe(n.data.subarray(t));return{key:n.type,info:s,data:i}}let e=Pe(n.data);return{key:n.type,info:"",data:e}}function Eh(n){return n.type==="PRIV"?ph(n):n.type[0]==="W"?vh(n):n.type==="APIC"?mh(n):yh(n)}function Th(n){let e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=qs(n,4),s=10;return{type:e,size:t,data:n.subarray(s,s+t)}}var rs=10,Sh=10;function po(n){let e=0,t=[];for(;Jr(n,e);){let s=qs(n,e+6);n[e+5]>>6&1&&(e+=rs),e+=rs;let i=e+s;for(;e+Sh<i;){let r=Th(n.subarray(e)),a=Eh(r);a&&t.push(a),e+=r.size+rs}co(n,e)&&(e+=rs)}return t}function yo(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function xh(n){if(n.data.byteLength===8){let e=new Uint8Array(n.data),t=e[3]&1,s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function tn(n){let e=po(n);for(let t=0;t<e.length;t++){let s=e[t];if(yo(s))return xh(s)}}var De=(function(n){return n.audioId3="org.id3",n.dateRange="com.apple.quicktime.HLS",n.emsg="https://aomedia.org/emsg/ID3",n.misbklv="urn:misb:KLV:bin:1910.1",n})({});function Ve(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var qt=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,s,i){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,s){}demux(e,t){this.cachedData&&(e=we(this.cachedData,e),this.cachedData=null);let s=Wt(e,0),i=s?s.length:0,r,a=this._audioTrack,o=this._id3Track,c=s?tn(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&O(c))&&(this.basePTS=Ah(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:De.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){let h=this.appendFrame(a,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else hh(e,i)?(s=Wt(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:De.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){let h=e.slice(r);this.cachedData?this.cachedData=we(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:Ve(),id3Track:o,textTrack:Ve()}}demuxSampleAes(e,t,s){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:Ve(),id3Track:this._id3Track,textTrack:Ve()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},Ah=(n,e,t)=>{if(O(n))return n*90;let s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s},ns=null,Lh=[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],Ih=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],bh=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Rh=[0,1,1,4];function vo(n,e,t,s,i){if(t+24>e.length)return;let r=Eo(e,t);if(r&&t+r.frameLength<=e.length){let a=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*a,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function Eo(n,e){let t=n[e+1]>>3&3,s=n[e+1]>>1&3,i=n[e+2]>>4&15,r=n[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){let a=n[e+2]>>1&1,o=n[e+3]>>6,c=t===3?3-s:s===3?3:4,l=Lh[c*14+i-1]*1e3,d=Ih[(t===3?0:t===2?1:2)*3+r],u=o===3?1:2,f=bh[t][s],g=Rh[s],p=f*8*g,y=Math.floor(f*l/d+a)*g;if(ns===null){let T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ns=T?parseInt(T[1]):0}return ns&&ns<=87&&s===2&&l>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:d,channelCount:u,frameLength:y,samplesPerFrame:p}}}function sn(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function To(n,e){return e+1<n.length&&sn(n,e)}function _h(n,e){return sn(n,e)&&4<=n.length-e}function So(n,e){if(e+1<n.length&&sn(n,e)){let s=Eo(n,e),i=4;s!=null&&s.frameLength&&(i=s.frameLength);let r=e+i;return r===n.length||To(n,r)}return!1}var Yi=class extends qt{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let s=Wt(e,0),i=s?.length||0;if(So(e,i))return!1;for(let r=e.length;i<r;i++)if(lh(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return oh(e,t)}appendFrame(e,t,s){fo(e,this.observer,t,s,e.manifestCodec);let i=mo(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}},xo=(n,e)=>{let t=0,s=5;e+=s;let i=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=n[e];let o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(a[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t},Wi=class extends qt{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){let i=Ao(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;let t=Wt(e,0);if(!t)return!1;let s=t.length;return e[s]===11&&e[s+1]===119&&tn(t)!==void 0&&xo(e,s)<16}};function Ao(n,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;let r=e[t+4]>>6;if(r>=3)return-1;let o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[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][c*3+r]*2;if(t+h>e.length)return-1;let d=e[t+6]>>5,u=0;d===2?u+=2:(d&1&&d!==1&&(u+=2),d&4&&(u+=2));let f=(e[t+6]<<8|e[t+7])>>12-u&1,p=[2,1,2,3,3,4,4,5][d]+f,y=e[t+5]>>3,v=e[t+5]&7,E=new Uint8Array([r<<6|y<<1|v>>2,(v&3)<<6|d<<3|f<<2|c>>4,c<<4&224]),T=1536/o*9e4,S=s+i*T,x=e.subarray(t,t+h);return n.config=E,n.channelCount=p,n.samplerate=o,n.samples.push({unit:x,pts:S}),h}var qi=class extends qt{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=Wt(e,0),s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&tn(t)!==void 0&&xo(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(So(e,s))return se.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return _h(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return vo(e,t,s,this.basePTS,this.frameIndex)}},Dh=/\/emsg[-/]ID3/i,ji=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){let r=this.videoTrack=Ve("video",1),a=this.audioTrack=Ve("audio",1),o=this.txtTrack=Ve("text",1);if(this.id3Track=Ve("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let c=Oa(e);if(c.video){let{id:l,timescale:h,codec:d,supplemental:u}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=d,r.supplemental=u}if(c.audio){let{id:l,timescale:h,codec:d}=c.audio;a.id=l,a.timescale=h,a.codec=d}o.id=Ca.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Bl(e)}demux(e,t){this.timeOffset=t;let s=e,i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=we(this.remainderData,e));let o=Yl(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;let a=this.extractID3Track(i,t);return r.samples=xn(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let i=this.extractID3Track(t,this.timeOffset);return s.samples=xn(e,t),{videoTrack:t,audioTrack:Ve(),id3Track:i,textTrack:Ve()}}extractID3Track(e,t){let s=this.id3Track;if(e.samples.length){let i=X(e.samples,["emsg"]);i&&i.forEach(r=>{let a=ql(r);if(Dh.test(a.schemeIdUri)){let o=ra(a,t),c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);let l=a.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:De.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let o=ra(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:De.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function ra(n,e){return O(n.presentationTime)?n.presentationTime/n.timeScale:e+n.presentationTimeDelta/n.timeScale}var zi=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Kt(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,it.cbc)}decryptAacSample(e,t,s){let i=e[t].unit;if(i.length<=16)return;let r=i.subarray(16,i.length-i.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{let c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t),i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){let s=new Uint8Array(t),i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){let a=Ba(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(a,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}let r=e[t].units;for(;!(s>=r.length);s++){let a=r[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,i,a),!this.decrypter.isSync()))return}}}},Os=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){let r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let s=t.samples,i=s.length;if(i){let r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){let i=t.byteLength,r=e.naluState||0,a=r,o=[],c=0,l,h,d,u=-1,f=0;for(r===-1&&(u=0,f=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,u>=0){let g={data:t.subarray(u,h),type:f};o.push(g)}else{let g=this.getLastNalUnit(e.samples);g&&(a&&c<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),h>0&&(g.data=we(g.data,t.subarray(0,h)),g.state=0))}c<i?(d=this.getNALuType(t,c),u=c,f=d,r=0):r=-1}else r=0}if(u>=0&&r>=0){let g={data:t.subarray(u,i),type:f,state:r};o.push(g)}if(o.length===0){let g=this.getLastNalUnit(e.samples);g&&(g.data=we(g.data,t))}return e.naluState=r,o}},ut=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,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}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),s=this.word>>>32-t;if(e>32&&se.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?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},Xi=class extends Os{parsePES(e,t,s,i){let r=this.parseNALu(e,s.data,i),a=this.VideoSample,o,c=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,d;switch(l.type){case 1:{let p=!1;o=!0;let y=l.data;if(c&&y.length>4){let v=this.readSliceType(y);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var u;(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,Wr(l.data,1,s.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;let p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((f=e.pixelRatio)==null?void 0:f[0])!==y.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];let v=p.subarray(1,4),E="avc1.";for(let T=0;T<3;T++){let S=v[T].toString(16);S.length<2&&(S="0"+S),E+=S}e.codec=E}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(d=a)!=null&&d.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new ut(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let a=0;a<e;a++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){let t=new ut(e),s=0,i=0,r=0,a=0,o,c,l,h=t.readUByte.bind(t),d=t.readBits.bind(t),u=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);h();let E=h();if(d(5),g(3),h(),y(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){let R=u();if(R===3&&g(1),y(),y(),g(1),f())for(c=R!==3?8:12,l=0;l<c;l++)f()&&(l<6?v(16,t):v(64,t))}y();let T=u();if(T===0)u();else if(T===1)for(g(1),p(),p(),o=u(),l=0;l<o;l++)p();y(),g(1);let S=u(),x=u(),_=d(1);_===0&&g(1),g(1),f()&&(s=u(),i=u(),r=u(),a=u());let A=[1,1];if(f()&&f())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((S+1)*16-s*2-i*2),height:(2-_)*(x+1)*16-(_?2:4)*(r+a),pixelRatio:A}}},Qi=class extends Os{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){let r=this.parseNALu(e,s.data,i),a=this.VideoSample,o,c=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,d;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var u;(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,Wr(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ie(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let g in f.params)e.params[g]=f.params[g]}this.pushParameterSet(e.sps,l.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let f=this.readPPS(l.data);for(let g in f)e.params[g]=f[g]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(d=a)!=null&&d.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new ut(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){let t=new ut(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let s=t.readBits(3);t.readBoolean();let i=t.readBits(2),r=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),d=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),y=t.readUByte(),v=t.readUByte(),E=[],T=[];for(let J=0;J<s;J++)E.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let J=s;J<8;J++)t.readBits(2);for(let J=0;J<s;J++)E[J]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[J]&&t.readUByte();t.readUEG();let S=t.readUEG();S==3&&t.skipBits(1);let x=t.readUEG(),_=t.readUEG(),A=t.readBoolean(),R=0,b=0,L=0,P=0;A&&(R+=t.readUEG(),b+=t.readUEG(),L+=t.readUEG(),P+=t.readUEG());let M=t.readUEG(),B=t.readUEG(),V=t.readUEG(),U=t.readBoolean();for(let J=U?0:s;J<=s;J++)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 Te=0;Te<4;Te++)for(let Ce=0;Ce<(Te===3?2:6);Ce++)if(!t.readBoolean())t.readUEG();else{let Oe=Math.min(64,1<<4+(Te<<1));Te>1&&t.readEG();for(let mt=0;mt<Oe;mt++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let F=t.readUEG(),G=0;for(let J=0;J<F;J++){let Te=!1;if(J!==0&&(Te=t.readBoolean()),Te){J===F&&t.readUEG(),t.readBoolean(),t.readUEG();let Ce=0;for(let nt=0;nt<=G;nt++){let Oe=t.readBoolean(),mt=!1;Oe||(mt=t.readBoolean()),(Oe||mt)&&Ce++}G=Ce}else{let Ce=t.readUEG(),nt=t.readUEG();G=Ce+nt;for(let Oe=0;Oe<Ce;Oe++)t.readUEG(),t.readBoolean();for(let Oe=0;Oe<nt;Oe++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let J=t.readUEG();for(let Te=0;Te<J;Te++){for(let Ce=0;Ce<V+4;Ce++)t.readBits(1);t.readBits(1)}}let C=0,w=1,j=1,ee=!0,z=1,Z=0;t.readBoolean(),t.readBoolean();let Ee=!1;if(t.readBoolean()){if(t.readBoolean()){let at=t.readUByte(),un=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Zt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];at>0&&at<16?(w=un[at-1],j=Zt[at-1]):at===255&&(w=t.readBits(16),j=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(),Ee=t.readBoolean(),Ee&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(z=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Zt=t.readBoolean(),fn=t.readBoolean(),kt=!1;(Zt||fn)&&(kt=t.readBoolean(),kt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),kt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let gn=0;gn<=s;gn++){ee=t.readBoolean();let vl=ee||t.readBoolean(),mn=!1;vl?t.readEG():mn=t.readBoolean();let pn=mn?1:t.readUEG()+1;if(Zt)for(let Ct=0;Ct<pn;Ct++)t.readUEG(),t.readUEG(),kt&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(fn)for(let Ct=0;Ct<pn;Ct++)t.readUEG(),t.readUEG(),kt&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),C=t.readUEG())}let ke=x,Ue=_;if(A){let J=1,Te=1;S===1?J=Te=2:S==2&&(J=2),ke=x-J*b-J*R,Ue=_-Te*P-Te*L}let rt=i?["A","B","C"][i]:"",yl=o<<24|c<<16|l<<8|h,ti=0;for(let J=0;J<32;J++)ti=(ti|(yl>>J&1)<<31-J)>>>0;let si=ti.toString(16);return a===1&&si==="2"&&(si="6"),{codecString:`hvc1.${rt}${a}.${si}.${r?"H":"L"}${v}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[d,u,f,g,p,y],general_level_idc:v,bit_depth:M+8,bit_depth_luma_minus8:M,bit_depth_chroma_minus8:B,min_spatial_segmentation_idc:C,chroma_format_idc:S,frame_rate:{fixed:ee,fps:Z/z}},width:ke,height:Ue,pixelRatio:[w,j]}}readPPS(e){let t=new ut(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let i=t.readBoolean(),r=t.readBoolean(),a=1;return r&&i?a=0:r?a=3:i&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},fe=188,Zi=class n{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){let s=n.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){let t=e.length,s=Math.min(fe*5,t-fe)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let c=i;c<t;c+=fe)if(e[c]===71&&(t-c===fe||e[c+fe]===71)){if(o++,a===-1&&(a=c,a!==0&&(s=Math.min(a+fe*99,e.length-fe)+1)),r||(r=Ji(e,c)===0),r&&o>1&&(a===0&&o>2||c+fe>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Ca[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=n.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=n.createTrack("audio",i),this._id3Track=n.createTrack("id3"),this._txtTrack=n.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r,a=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack,h=a.pid,d=a.pesData,u=o.pid,f=c.pid,g=o.pesData,p=c.pesData,y=null,v=this.pmtParsed,E=this._pmtId,T=e.length;if(this.remainderData&&(e=we(this.remainderData,e),T=e.length,this.remainderData=null),T<fe&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};let S=Math.max(0,n.syncOffset(e));T-=(T-S)%fe,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let x=0;for(let A=S;A<T;A+=fe)if(e[A]===71){let R=!!(e[A+1]&64),b=Ji(e,A),L=(e[A+3]&48)>>4,P;if(L>1){if(P=A+5+e[A+4],P===A+fe)continue}else P=A+4;switch(b){case h:R&&(d&&(r=vt(d,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,l,r,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(P,A+fe)),d.size+=A+fe-P);break;case u:if(R){if(g&&(r=vt(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(P,A+fe)),g.size+=A+fe-P);break;case f:R&&(p&&(r=vt(p,this.logger))&&this.parseID3PES(c,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(P,A+fe)),p.size+=A+fe-P);break;case 0:R&&(P+=e[P]+1),E=this._pmtId=Ph(e,P);break;case E:{R&&(P+=e[P]+1);let M=kh(e,P,this.typeSupported,s,this.observer,this.logger);h=M.videoPid,h>0&&(a.pid=h,a.segmentCodec=M.segmentVideoCodec),u=M.audioPid,u>0&&(o.pid=u,o.segmentCodec=M.segmentAudioCodec),f=M.id3Pid,f>0&&(c.pid=f),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${y}'. Backtracking to sync byte @${S} to parse all TS packets.`),y=null,A=S-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=b;break}}else x++;x>0&&er(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=d,o.pesData=g,c.pesData=p;let _={audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(_),_}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,a=s.pesData,o=t.pesData,c=i.pesData,l;if(a&&(l=vt(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=a,o&&(l=vt(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=vt(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){let i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new zi(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Xi:e==="hevc"&&(this.videoParser=new Qi))}decrypt(e,t){return new Promise(s=>{let{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0,i=this.aacOverFlow,r=t.data;if(i){this.aacOverFlow=null;let d=i.missing,u=i.sample.unit.byteLength;if(d===-1)r=we(i.sample.unit,r);else{let f=u-d;i.sample.unit.set(r.subarray(0,d),f),e.samples.push(i.sample),s=i.missing}}let a,o;for(a=s,o=r.length;a<o-1&&!Ms(r,a);a++);if(a!==s){let d,u=a<o-1;if(u?d=`AAC PES did not start with ADTS header,offset:${a}`:d="No ADTS header found in AAC PES",er(this.observer,new Error(d),u,this.logger),!u)return}fo(e,this.observer,r,a,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){let d=go(e.samplerate);c=i.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;a<o;)if(h=mo(e,r,a,c,l),a+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;a<o-1&&!Ms(r,a);a++);}parseMPEGPES(e,t){let s=t.data,i=s.length,r=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(To(s,a)){let c=vo(e,s,a,o,r);if(c)a+=c.length,r++;else break}else a++}parseAC3PES(e,t){{let s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let r=s.length,a=0,o=0,c;for(;o<r&&(c=Ao(e,s,o,i,a++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let s=ie({},t,{type:this._videoTrack?De.emsg:De.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}};function Ji(n,e){return((n[e+1]&31)<<8)+n[e+2]}function Ph(n,e){return(n[e+10]&31)<<8|n[e+11]}function kh(n,e,t,s,i,r){let a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(n[e+1]&15)<<8|n[e+2],c=e+3+o-4,l=(n[e+10]&15)<<8|n[e+11];for(e+=12+l;e<c;){let h=Ji(n,e),d=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!s){ui("ADTS AAC",r);break}case 15:a.audioPid===-1&&(a.audioPid=h);break;case 21:a.id3Pid===-1&&(a.id3Pid=h);break;case 219:if(!s){ui("H.264",r);break}case 27:a.videoPid===-1&&(a.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="mp3");break;case 193:if(!s){ui("AC-3",r);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&d>0){let u=e+5,f=d;for(;f>2;){n[u]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=h,a.segmentAudioCodec="ac3"));let p=n[u+1]+2;u+=p,f-=p}}break;case 194:case 135:return er(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:a.videoPid===-1&&(a.videoPid=h,a.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=d+5}return a}function er(n,e,t,s){s.warn(`parsing error: ${e.message}`),n.emit(m.ERROR,m.ERROR,{type:K.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function ui(n,e){e.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function vt(n,e){let t=0,s,i,r,a,o,c=n.data;if(!n||n.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=we(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>n.size-6)return null;let h=s[7];h&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[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),r=s[8];let d=r+9;if(n.size<=d)return null;n.size-=d;let u=new Uint8Array(n.size);for(let f=0,g=c.length;f<g;f++){s=c[f];let p=s.byteLength;if(d)if(d>p){d-=p;continue}else s=s.subarray(d),p-=d,d=0;u.set(s,t),t+=p}return i&&(i-=r+3),{data:u,pts:a,dts:o,len:i}}return null}var tr=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}}},Ze=Math.pow(2,32)-1,ue=class n{static init(){n.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in n.types)n.types.hasOwnProperty(e)&&(n.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);let t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);n.HDLR_TYPES={video:t,audio:s};let i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);n.STTS=n.STSC=n.STCO=r,n.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),n.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),n.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),n.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);n.FTYP=n.box(n.types.ftyp,a,c,a,o),n.DINF=n.box(n.types.dinf,n.box(n.types.dref,i))}static box(e,...t){let s=8,i=t.length,r=i;for(;i--;)s+=t[i].byteLength;let a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(e,4),i=0,s=8;i<r;i++)a.set(t[i],s),s+=t[i].byteLength;return a}static hdlr(e){return n.box(n.types.hdlr,n.HDLR_TYPES[e])}static mdat(e){return n.box(n.types.mdat,e)}static mdhd(e,t){t*=e;let s=Math.floor(t/(Ze+1)),i=Math.floor(t%(Ze+1));return n.box(n.types.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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return n.box(n.types.mdia,n.mdhd(e.timescale||0,e.duration||0),n.hdlr(e.type),n.minf(e))}static mfhd(e){return n.box(n.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?n.box(n.types.minf,n.box(n.types.smhd,n.SMHD),n.DINF,n.stbl(e)):n.box(n.types.minf,n.box(n.types.vmhd,n.VMHD),n.DINF,n.stbl(e))}static moof(e,t,s){return n.box(n.types.moof,n.mfhd(e),n.traf(s,t))}static moov(e){let t=e.length,s=[];for(;t--;)s[t]=n.trak(e[t]);return n.box.apply(null,[n.types.moov,n.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(n.mvex(e)))}static mvex(e){let t=e.length,s=[];for(;t--;)s[t]=n.trex(e[t]);return n.box.apply(null,[n.types.mvex,...s])}static mvhd(e,t){t*=e;let s=Math.floor(t/(Ze+1)),i=Math.floor(t%(Ze+1)),r=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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&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 n.box(n.types.mvhd,r)}static sdtp(e){let t=e.samples||[],s=new Uint8Array(4+t.length),i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return n.box(n.types.sdtp,s)}static stbl(e){return n.box(n.types.stbl,n.stsd(e),n.box(n.types.stts,n.STTS),n.box(n.types.stsc,n.STSC),n.box(n.types.stsz,n.STSZ),n.box(n.types.stco,n.STCO))}static avc1(e){let t=[],s=[],i,r,a;for(i=0;i<e.sps.length;i++)r=e.sps[i],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],a=r.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(r));let o=n.box(n.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return n.box(n.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&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,n.box(n.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),n.box(n.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...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 n.box(n.types.mp4a,n.audioStsd(e),n.box(n.types.esds,n.esds(e)))}static mp3(e){return n.box(n.types[".mp3"],n.audioStsd(e))}static ac3(e){return n.box(n.types["ac-3"],n.audioStsd(e),n.box(n.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return n.box(n.types.stsd,n.STSD,n.mp4a(e));if(t==="ac3"&&e.config)return n.box(n.types.stsd,n.STSD,n.ac3(e));if(t==="mp3"&&e.codec==="mp3")return n.box(n.types.stsd,n.STSD,n.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return n.box(n.types.stsd,n.STSD,n.avc1(e));if(t==="hevc"&&e.vps)return n.box(n.types.stsd,n.STSD,n.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,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,a=Math.floor(s/(Ze+1)),o=Math.floor(s%(Ze+1));return n.box(n.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,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,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){let s=n.sdtp(e),i=e.id,r=Math.floor(t/(Ze+1)),a=Math.floor(t%(Ze+1));return n.box(n.types.traf,n.box(n.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),n.box(n.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),n.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,n.box(n.types.trak,n.tkhd(e),n.mdia(e))}static trex(e){let t=e.id;return n.box(n.types.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 s=e.samples||[],i=s.length,r=12+16*i,a=new Uint8Array(r),o,c,l,h,d,u;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,d=c.flags,u=c.cts,a.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return n.box(n.types.trun,a)}static initSegment(e){n.types||n.init();let t=n.moov(e);return we(n.FTYP,t)}static hvc1(e){let t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=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),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]),a=r.length;for(let g=0;g<s.length;g+=1){a+=3;for(let p=0;p<s[g].length;p+=1)a+=2+s[g][p].length}let o=new Uint8Array(a);o.set(r,0),a=r.length;let c=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===c?128:0),0,s[g].length]),a),a+=3;for(let p=0;p<s[g].length;p+=1)o.set(new Uint8Array([s[g][p].length>>8,s[g][p].length&255]),a),a+=2,o.set(s[g][p],a),a+=s[g][p].length}let l=n.box(n.types.hvcC,o),h=e.width,d=e.height,u=e.pixelRatio[0],f=e.pixelRatio[1];return n.box(n.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&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]),l,n.box(n.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),n.box(n.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,f>>24,f>>16&255,f>>8&255,f&255])))}};ue.types=void 0;ue.HDLR_TYPES=void 0;ue.STTS=void 0;ue.STSC=void 0;ue.STCO=void 0;ue.STSZ=void 0;ue.VMHD=void 0;ue.SMHD=void 0;ue.STSD=void 0;ue.FTYP=void 0;ue.DINF=void 0;var Lo=9e4;function rn(n,e,t=1,s=!1){let i=n*e*t;return s?Math.round(i):i}function Ch(n,e,t=1,s=!1){return rn(n,e,1/t,s)}function wt(n,e=!1){return rn(n,1e3,1/Lo,e)}function wh(n,e=1){return rn(n,Lo,1/e)}function na(n){let{baseTime:e,timescale:t,trackId:s}=n;return`${e/t} (${e}/${t}) trackId: ${s}`}var Mh=10*1e3,Oh=1024,Fh=1152,Nh=1536,Et=null,fi=null;function aa(n,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1}}}var bt=class extends Ie{constructor(e,t,s,i){if(super("mp4-remuxer",i),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=s,this.ISGenerated=!1,Et===null){let a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Et=a?parseInt(a[1]):0}if(fi===null){let r=navigator.userAgent.match(/Safari\/(\d+)/i);fi=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&na(t)} > ${e&&na(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,s=e[0].pts,i=e.reduce((r,a)=>{let o=a.pts,c=o-r;return c<-4294967296&&(t=!0,o=_e(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,a,o,c){let l,h,d,u,f,g,p=r,y=r,v=e.pid>-1,E=t.pid>-1,T=t.samples.length,S=e.samples.length>0,x=o&&T>0||T>1;if((!v||S)&&(!E||x)||this.ISGenerated||o){if(this.ISGenerated){var A,R,b,L;let V=this.videoTrackConfig;(V&&(t.width!==V.width||t.height!==V.height||((A=t.pixelRatio)==null?void 0:A[0])!==((R=V.pixelRatio)==null?void 0:R[0])||((b=t.pixelRatio)==null?void 0:b[1])!==((L=V.pixelRatio)==null?void 0:L[1]))||!V&&x||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,a));let P=this.isVideoContiguous,M=-1,B;if(x&&(M=Bh(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,M>0){this.warn(`Dropped ${M} out of ${T} video samples due to a missing keyframe`);let V=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(M),t.dropped+=M,y+=(t.samples[0].pts-V)/t.inputTimeScale,B=y}else M===-1&&(this.warn(`No keyframe found out of ${T} video samples`),g=!1);if(this.ISGenerated){if(S&&x){let V=this.getVideoStartPts(t.samples),k=(_e(e.samples[0].pts,V)-V)/t.inputTimeScale;p+=Math.max(0,k),y+=Math.max(0,-k)}if(S){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,a)),h=this.remuxAudio(e,p,this.isAudioContiguous,a,E||x||c===N.AUDIO?y:void 0),x){let V=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,a)),l=this.remuxVideo(t,y,P,V)}}else x&&(l=this.remuxVideo(t,y,P,0));l&&(l.firstKeyFrame=M,l.independent=M!==-1,l.firstKeyFramePTS=B)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Io(s,r,this._initPTS,this._initDTS)),i.samples.length&&(u=bo(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:g,text:u,id3:f}}computeInitPts(e,t,s,i){let r=Math.round(s*t),a=_e(e,r);if(a<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${i}`);a<r+t;)a+=8589934592;return a-r}generateIS(e,t,s,i){let r=e.samples,a=t.samples,o=this.typeSupported,c={},l=this._initPTS,h=!l||i,d="audio/mp4",u,f,g,p=-1;if(h&&(u=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):ue.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,g=e.inputTimeScale,!l||g!==l.timescale?u=f=this.computeInitPts(r[0].pts,g,s,"audio"):h=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:ue.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,g=t.inputTimeScale,!l||g!==l.timescale){let y=this.getVideoStartPts(a),v=_e(a[0].dts,y),E=this.computeInitPts(v,g,s,"video"),T=this.computeInitPts(y,g,s,"video");f=Math.min(f,E),u=Math.min(u,T)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${u/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${u/g} (${u}/${g}) trackId: ${p}`),this._initPTS={baseTime:u,timescale:g,trackId:p},this._initDTS={baseTime:f,timescale:g,trackId:p}):u=g=void 0,{tracks:c,initPTS:u,timescale:g,trackId:p}}remuxVideo(e,t,s,i){let r=e.inputTimeScale,a=e.samples,o=[],c=a.length,l=this._initPTS,h=l.baseTime*r/l.timescale,d=this.nextVideoTs,u=8,f=this.videoSampleDuration,g,p,y=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,E=!1;if(!s||d===null){let C=h+t*r,w=a[0].pts-_e(a[0].dts,a[0].pts);Et&&d!==null&&Math.abs(C-w-(d+h))<15e3?s=!0:d=C-w-h}let T=d+h;for(let C=0;C<c;C++){let w=a[C];w.pts=_e(w.pts,T),w.dts=_e(w.dts,T),w.dts<a[C>0?C-1:C].dts&&(E=!0)}E&&a.sort(function(C,w){let j=C.dts-w.dts,ee=C.pts-w.pts;return j||ee}),g=a[0].dts,p=a[a.length-1].dts;let S=p-g,x=S?Math.round(S/(c-1)):f||e.inputTimeScale/30;if(s){let C=g-T,w=C>x,j=C<-1;if((w||j)&&(w?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${wt(C,!0)} ms (${C}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${wt(-C,!0)} ms (${C}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!j||T>=a[0].pts||Et)){g=T;let ee=a[0].pts-C;if(w)a[0].dts=g,a[0].pts=ee;else{let z=!0;for(let Z=0;Z<a.length&&!(a[Z].dts>ee&&z);Z++){let Ee=a[Z].pts;if(a[Z].dts-=C,a[Z].pts-=C,Z<a.length-1){let pe=a[Z+1].pts,ke=a[Z].pts,Ue=pe<=ke,rt=pe<=Ee;z=Ue==rt}}}this.log(`Video: Initial PTS/DTS adjusted: ${wt(ee,!0)}/${wt(g,!0)}, delta: ${wt(C,!0)} ms`)}}g=Math.max(0,g);let _=0,A=0,R=g;for(let C=0;C<c;C++){let w=a[C],j=w.units,ee=j.length,z=0;for(let Z=0;Z<ee;Z++)z+=j[Z].data.length;A+=z,_+=ee,w.length=z,w.dts<R?(w.dts=R,R+=x/4|0||1):R=w.dts,y=Math.min(w.pts,y),v=Math.max(w.pts,v)}p=a[c-1].dts;let b=A+4*_+8,L;try{L=new Uint8Array(b)}catch(C){this.observer.emit(m.ERROR,m.ERROR,{type:K.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,error:C,bytes:b,reason:`fail allocating video mdat ${b}`});return}let P=new DataView(L.buffer);P.setUint32(0,b),L.set(ue.types.mdat,4);let M=!1,B=Number.POSITIVE_INFINITY,V=Number.POSITIVE_INFINITY,U=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let C=0;C<c;C++){let w=a[C],j=w.units,ee=0;for(let Ee=0,pe=j.length;Ee<pe;Ee++){let ke=j[Ee],Ue=ke.data,rt=ke.data.byteLength;P.setUint32(u,rt),u+=4,L.set(Ue,u),u+=rt,ee+=4+rt}let z;if(C<c-1)f=a[C+1].dts-w.dts,z=a[C+1].pts-w.pts;else{let Ee=this.config,pe=C>0?w.dts-a[C-1].dts:x;if(z=C>0?w.pts-a[C-1].pts:x,Ee.stretchShortVideoTrack&&this.nextAudioTs!==null){let ke=Math.floor(Ee.maxBufferHole*r),Ue=(i?y+i*r:this.nextAudioTs+h)-w.pts;Ue>ke?(f=Ue-pe,f<0?f=pe:M=!0,this.log(`It is approximately ${Ue/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=pe}else f=pe}let Z=Math.round(w.pts-w.dts);B=Math.min(B,f),U=Math.max(U,f),V=Math.min(V,z),k=Math.max(k,z),o.push(aa(w.key,f,ee,Z))}if(o.length){if(Et){if(Et<70){let C=o[0].flags;C.dependsOn=2,C.isNonSync=0}}else if(fi&&k-V<U-B&&x/U<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let C=g;for(let w=0,j=o.length;w<j;w++){let ee=C+o[w].duration,z=C+o[w].cts;if(w<j-1){let Z=ee+o[w+1].cts;o[w].duration=Z-z}else o[w].duration=w?o[w-1].duration:x;o[w].cts=0,C=ee}}}f=M||!f?x:f;let $=p+f;this.nextVideoTs=d=$-h,this.videoSampleDuration=f,this.isVideoContiguous=!0;let Y={data1:ue.moof(e.sequenceNumber++,g,ie(e,{samples:o})),data2:L,startPTS:(y-h)/r,endPTS:(v+f-h)/r,startDTS:(g-h)/r,endDTS:d/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Fh;case"ac3":return Nh;default:return Oh}}remuxAudio(e,t,s,i,r){let a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,c=a/o,l=this.getSamplesPerFrame(e),h=l*c,d=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0,p=e.samples,y=u?0:8,v=this.nextAudioTs||-1,E=d.baseTime*a/d.timescale,T=E+t*a;if(this.isAudioContiguous=s=s||p.length&&v>0&&(i&&Math.abs(T-(v+E))<9e3||Math.abs(_e(p[0].pts,T)-(v+E))<20*h),p.forEach(function(k){k.pts=_e(k.pts,T)}),!s||v<0){let k=p.length;if(p=p.filter($=>$.pts>=0),k!==p.length&&this.warn(`Removed ${p.length-k} of ${k} samples (initPTS ${E} / ${a})`),!p.length)return;r===0?v=0:i&&!g?v=Math.max(0,T-E):v=p[0].pts-E}if(e.segmentCodec==="aac"){let k=this.config.maxAudioFramesDrift;for(let $=0,F=v+E;$<p.length;$++){let G=p[$],Y=G.pts,C=Y-F,w=Math.abs(1e3*C/a);if(C<=-k*h&&g)$===0&&(this.warn(`Audio frame @ ${(Y/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*C/a)} ms.`),this.nextAudioTs=v=Y-E,F=Y);else if(C>=k*h&&w<Mh&&g){let j=Math.round(C/h);for(F=Y-j*h;F<0&&j&&h;)j--,F+=h;$===0&&(this.nextAudioTs=v=F-E),this.warn(`Injecting ${j} audio frames @ ${((F-E)/a).toFixed(3)}s due to ${Math.round(1e3*C/a)} ms gap.`);for(let ee=0;ee<j;ee++){let z=tr.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=G.unit.subarray()),p.splice($,0,{unit:z,pts:F}),F+=h,$++}}G.pts=F,F+=h}}let S=null,x=null,_,A=0,R=p.length;for(;R--;)A+=p[R].unit.byteLength;for(let k=0,$=p.length;k<$;k++){let F=p[k],G=F.unit,Y=F.pts;if(x!==null){let w=f[k-1];w.duration=Math.round((Y-x)/c)}else if(s&&e.segmentCodec==="aac"&&(Y=v+E),S=Y,A>0){A+=y;try{_=new Uint8Array(A)}catch(w){this.observer.emit(m.ERROR,m.ERROR,{type:K.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:A,reason:`fail allocating audio mdat ${A}`});return}u||(new DataView(_.buffer).setUint32(0,A),_.set(ue.types.mdat,4))}else return;_.set(G,y);let C=G.byteLength;y+=C,f.push(aa(!0,l,C,0)),x=Y}let b=f.length;if(!b)return;let L=f[f.length-1];v=x-E,this.nextAudioTs=v+c*L.duration;let P=u?new Uint8Array(0):ue.moof(e.sequenceNumber++,S/c,ie({},e,{samples:f}));e.samples=[];let M=(S-E)/a,B=this.nextAudioTs/a,U={data1:P,data2:_,startPTS:M,endPTS:B,startDTS:M,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,U}};function _e(n,e){let t;if(e===null)return n;for(e<n?t=-8589934592:t=8589934592;Math.abs(n-e)>4294967296;)n+=t;return n}function Bh(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function Io(n,e,t,s){let i=n.samples.length;if(!i)return;let r=n.inputTimeScale;for(let o=0;o<i;o++){let c=n.samples[o];c.pts=_e(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=_e(c.dts-s.baseTime*r/s.timescale,e*r)/r}let a=n.samples;return n.samples=[],{samples:a}}function bo(n,e,t){let s=n.samples.length;if(!s)return;let i=n.inputTimeScale;for(let a=0;a<s;a++){let o=n.samples[a];o.pts=_e(o.pts-t.baseTime*i/t.timescale,e*i)/i}n.samples.sort((a,o)=>a.pts-o.pts);let r=n.samples;return n.samples=[],{samples:r}}var sr=class extends Ie{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:r,video:a}=this.initData=Oa(e);if(t)Kl(e,t);else{let c=r||a;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=oa(r,re.AUDIO,this)),a&&(i=oa(a,re.VIDEO,this));let o={};r&&a?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,a){var o,c;let{initPTS:l,lastEndTime:h}=this,d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};O(h)||(h=this.lastEndTime=r||0);let u=t.samples;if(!u.length)return d;let f={initPTS:void 0,timescale:void 0,trackId:void 0},g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(u),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);let p=Hl(u,g,this),y=g.audio?p[g.audio.id]:null,v=g.video?p[g.video.id]:null,E=as(v,1/0),T=as(y,1/0),S=as(v,0,!0),x=as(y,0,!0),_=r,A=0,R=y&&(!v||!l&&T<E||l&&l.trackId===g.audio.id),b=R?y:v;if(b){let F=b.timescale,G=b.start-r*F,Y=R?g.audio.id:g.video.id;_=b.start/F,A=R?x-T:S-E,(a||!l)&&(Uh(l,_,r,A)||F!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${r} ${G/F} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${_-r} (${G}/${F}) trackId: ${Y}`),l=null,f.initPTS=G,f.timescale=F,f.trackId=Y)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=_,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let L=_-l.baseTime/l.timescale,P=L+A;A>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let M=!!g.audio,B=!!g.video,V="";M&&(V+="audio"),B&&(V+="video");let U=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),k={data1:u,startPTS:L,startDTS:L,endPTS:P,endDTS:P,type:V,hasAudio:M,hasVideo:B,nb:1,dropped:0,encrypted:U};d.audio=M&&!B?k:void 0,d.video=B?k:void 0;let $=v?.sampleCount;if($){let F=v.keyFrameIndex,G=F!==-1;k.nb=$,k.dropped=F===0||this.isVideoContiguous?0:G?F:$,k.independent=G,k.firstKeyFrame=F,G&&v.keyFrameStart&&(k.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=G),this.isVideoContiguous||(this.isVideoContiguous=G),k.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${F}/${$} dropped: ${k.dropped} start: ${k.firstKeyFramePTS||"NA"}`)}return d.initSegment=f,d.id3=Io(s,r,l,l),i.samples.length&&(d.text=bo(i,r,l)),d}};function as(n,e,t=!1){return n?.start!==void 0?(n.start+(t?n.duration:0))/n.timescale:e}function Uh(n,e,t,s){if(n===null)return!0;let i=Math.max(s,1),r=e-n.baseTime/n.timescale;return Math.abs(r-t)>i}function oa(n,e,t){let s=n.codec;return s&&s.length>4?s:e===re.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?xs(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}var ze;try{ze=self.performance.now.bind(self.performance)}catch{ze=Date.now}var ps=[{demux:ji,remux:sr},{demux:Zi,remux:bt},{demux:Yi,remux:bt},{demux:qi,remux:bt}];ps.splice(2,0,{demux:Wi,remux:bt});var Fs=class{constructor(e,t,s,i,r,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=s,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){let r=s.transmuxing;r.executeStart=ze();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);let{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:v,duration:E,initSegmentData:T}=c,S=$h(a,t);if(S&&It(S.method)){let R=this.getDecrypter(),b=Xr(S.method);if(R.isSync()){let L=R.softwareDecrypt(a,S.key.buffer,S.iv.buffer,b);if(s.part>-1){let M=R.flush();L=M&&M.buffer}if(!L)return r.executeEnd=ze(),gi(s);a=new Uint8Array(L)}else return this.asyncResult=!0,this.decryptionPromise=R.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer,b).then(L=>{let P=this.push(L,null,s);return this.decryptionPromise=null,P}),this.decryptionPromise}let x=this.needsProbing(h,d);if(x){let R=this.configureTransmuxer(a);if(R)return this.logger.warn(`[transmuxer] ${R.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:K.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),r.executeEnd=ze(),gi(s)}(h||d||g||x)&&this.resetInitSegment(T,p,y,E,t),(h||g||x)&&this.resetInitialTimestamp(v),l||this.resetContiguity();let _=this.transmux(a,S,f,u,s);this.asyncResult=jt(_);let A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=ze(),_}flush(e){let t=e.transmuxing;t.executeStart=ze();let{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));let a=[],{timeOffset:o}=i;if(s){let d=s.flush();d&&a.push(this.push(d.buffer,null,e))}let{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=ze();let d=[gi(e)];return this.asyncResult?Promise.resolve(d):d}let h=c.flush(o);return jt(h)?(this.asyncResult=!0,h.then(d=>(this.flushRemux(a,d,e),a))):(this.flushRemux(a,h,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){let{audioTrack:i,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===N.MAIN?"level":"track"} ${s.level}`);let h=this.remuxer.remux(i,r,a,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=ze()}resetInitialTimestamp(e){let{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,i,r):a=this.transmuxUnencrypted(e,s,i,r),a}transmuxUnencrypted(e,t,s,i){let{audioTrack:r,videoTrack:a,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){let{config:t,observer:s,typeSupported:i}=this,r;for(let d=0,u=ps.length;d<u;d++){var a;if((a=ps[d].demux)!=null&&a.probe(e,this.logger)){r=ps[d];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Kt(this.config)),e}};function $h(n,e){let t=null;return n.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var gi=n=>({remuxResult:{},chunkMeta:n});function jt(n){return"then"in n&&n.then instanceof Function}var ir=class{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}},rr=class{constructor(e,t,s,i,r,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=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=a}},la=0,Ns=class{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=la++,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=c=>{let l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var d;let u=(d=this.workerContext)==null?void 0:d.objectURL;u&&self.URL.revokeObjectURL(u);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;let l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:K.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};let r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;let a=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new Zr,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);let o=In(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let c=this.hls.logger;if(r.workerPath||th()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=ih(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=sh());let{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ne(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Fs(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Fs(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=la++;let t=this.hls.config,s=In(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ne(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),rh(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,s,i,r,a,o,c,l,h){var d,u;l.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:g}=this,p=a?a.start:r.start,y=r.decryptdata,v=this.frag,E=!(v&&r.cc===v.cc),T=!(v&&l.level===v.level),S=v?l.sn-v.sn:-1,x=this.part?l.part-this.part.index:-1,_=S===0&&l.id>1&&l.id===v?.stats.chunkCount,A=!T&&(S===1||S===0&&(x===1||_&&x<=0)),R=self.performance.now();(T||S||r.stats.parsing.start===0)&&(r.stats.parsing.start=R),a&&(x||!A)&&(a.stats.parsing.start=R);let b=!(v&&((d=r.initSegment)==null?void 0:d.url)===((u=v.initSegment)==null?void 0:u.url)),L=new rr(E,A,c,T,p,b);if(!A||E||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===N.MAIN?"level":"track"}: ${l.level} id: ${l.id}
16
+ ${t.m3u8}`)}function ro(r,e,t=!0){let s=e.startSN+e.skippedSegments-r.startSN,i=r.fragments,n=s>=0,a=0;if(n&&s<i.length)a=i[s].start;else if(n&&e.startSN===r.endSN+1)a=r.fragmentEnd;else if(n&&t)a=r.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=r.fragmentStart;else return;Yi(e,a)}function Yi(r,e){if(e){let t=r.fragments;for(let s=r.skippedSegments;s<t.length;s++)t[s].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function ao(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){let s=r.fragments;if(s.length&&t*4>e){let n=s[s.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function oo(r,e,t){if(!r)return null;let s=r.fragments[e-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===e)?s:e<r.startSN&&t&&t.sn===e?t:null}function sa(r,e,t){return r?lo(r.partList,e,t):null}function lo(r,e,t){if(r)for(let s=r.length;s--;){let i=r[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function co(r){r.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function td(r,e){return r!==e&&e?ia(r)!==ia(e):!1}function ia(r){return r.replace(/\?[^?]*$/,"")}function Nt(r,e){for(let s=0,i=r.length;s<i;s++){var t;if(((t=r[s])==null?void 0:t.cc)===e)return r[s]}return null}function sd(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function na(r,e){let t=r.start+e;r.startPTS=t,r.setStart(t),r.endPTS=t+r.duration}function ho(r,e){let t=e.fragments;for(let s=0,i=t.length;s<i;s++)na(t[s],r);e.fragmentHint&&na(e.fragmentHint,r),e.alignedSliding=!0}function id(r,e){r&&(uo(e,r),e.alignedSliding||ws(e,r),!e.alignedSliding&&!e.skippedSegments&&ro(r,e,!1))}function uo(r,e){if(!sd(e,r))return;let t=Math.min(e.endCC,r.endCC),s=Nt(e.fragments,t),i=Nt(r.fragments,t);if(!s||!i)return;se.log(`Aligning playlist at start of dicontinuity sequence ${t}`);let n=s.start-i.start;ho(n,r)}function ws(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;let t=r.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,n,a=Math.min(e.endCC,r.endCC);e.startCC<a&&r.startCC<a&&(i=Nt(s,a),n=Nt(t,a)),(!i||!n)&&(i=s[Math.floor(s.length/2)],n=Nt(t,i.cc)||t[Math.floor(t.length/2)]);let o=i.programDateTime,c=n.programDateTime;if(!o||!c)return;let l=(c-o)/1e3-(n.start-i.start);ho(l,r)}function Le(r,e,t){be(r,e,t),r.addEventListener(e,t)}function be(r,e,t){r.removeEventListener(e,t)}var nd={toString:function(r){let e="",t=r.length;for(let s=0;s<t;s++)e+=`[${r.start(s).toFixed(3)}-${r.end(s).toFixed(3)}]`;return e}},P={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"},Yt=class extends Ps{constructor(e,t,s,i,n){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:c,mediaBuffer:l,state:d}=this,h=c?c.currentTime:0,u=q.bufferInfo(l||c,h,a.maxBufferHole),g=!u.len;if(this.log(`Media seeking to ${F(h)?h.toFixed(3):h}, state: ${d}, ${g?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){let f=a.maxFragLookUpTolerance,p=o.start-f,y=o.start+o.duration+f;if(g||y<u.start||p>u.end){let v=h>y;(h<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);let f=this.lastCurrentTime;if(h>f&&(this.lastCurrentTime=h),!this.loadingParts){let p=Math.max(u.end,h),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,g&&(this.startPosition=h)),g&&this.state===P.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 Ui(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Vt(e.config)}registerListeners(){let{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===P.STOPPED)return;this.fragmentLoader.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=P.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=q.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>i&&a<t.edge||this.media.currentTime<e.start)return!1;let c=t.partList;if(c!=null&&c.length){let d=c[c.length-1];return q.isBuffered(this.media,d.start+d.duration/2)}let l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}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 s=this.media=this.mediaBuffer=t.media;Le(s,"seeking",this.onMediaSeeking),Le(s,"ended",this.onMediaEnded);let i=this.config;this.levels&&i.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){let s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),be(i,"seeking",this.onMediaSeeking),be(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(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=P.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){let i=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}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,s,i).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===P.FRAG_LOADING||!this.fragCurrent&&a===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(`Frag error: ${n?.message||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:s}=this;if(s.getState(e)===fe.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===fe.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;let i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{let i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{let{hls:i}=this,{frag:n,payload:a}=s,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&bt(o.method)){let c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Zn(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:n}),l}).then(l=>{let d=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:n,payload:l,stats:{tstart:c,tdecrypt:d}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let s=e.frag.stats;this.state!==P.STOPPED&&(this.state=P.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;let n=e.tracks;if(n&&!t.encrypted&&((s=n.audio)!=null&&s.encrypted||(i=n.video)!=null&&i.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(m.ERROR,{type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let s=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:${s?nd.toString(q.getBuffered(s)):"(detached)"})`),de(e)){var i;if(e.type!==B.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=P.IDLE;return}}let n=(i=this.levels)==null?void 0:i[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=P.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:s,part:i,partsLoaded:n}=e,a=!n||n.length===0||n.some(c=>!c),o=new Ht(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var n;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=P.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(m.KEY_LOADED,u),this.state===P.KEY_LOADING&&(this.state=P.IDLE),u}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));let c=this.fragPrevious;if(de(e)&&(!c||e.sn!==c.sn)){let u=this.shouldLoadParts(t.details,e.end);u!==this.loadingParts&&(this.log(`LL-Part loading ${u?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=u)}if(s=Math.max(e.start,s||0),this.loadingParts&&de(e)){let u=a.partList;if(u&&i){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let g=this.getNextPart(u,e,s);if(g>-1){let f=u[g];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${g}/${u.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,f,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,f,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:f,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(u,s))return Promise.resolve(null)}}if(de(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=a.partList)==null?void 0:l.filter(u=>u.loaded).map(u=>`[${u.start}-${u.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),F(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=P.FRAG_LOADING;let d=this.config.progressive&&e.type!==B.SUBTITLE,h;return d&&o?h=o.then(u=>!u||this.fragContextChanged(u.frag)?null:this.fragmentLoader.load(e,i)).catch(u=>this.handleFragLoadError(u)):h=Promise.all([this.fragmentLoader.load(e,d?i:void 0),o]).then(([u])=>(!d&&i&&i(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,s,i){return new Promise((n,a)=>{var o;let c=[],l=(o=s.details)==null?void 0:o.partList,d=h=>{this.fragmentLoader.loadPart(e,h,i).then(u=>{c[h.index]=u;let g=u.part;this.hls.trigger(m.FRAG_LOADED,u);let f=sa(s.details,e.sn,h.index+1)||lo(l,e.sn,h.index+1);if(f)d(f);else return n({frag:e,part:g,partsLoaded:c})}).catch(a)};d(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===V.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}let{frag:s,part:i,level:n}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a);let o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;let n=e.partList[0];if(n.fragment.type===B.SUBTITLE)return!1;let a=n.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=a){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:s}=this,{level:i,sn:n,part:a}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;let o=t[i],c=o.details,l=a>-1?sa(c,n,a):null,d=l?l.fragment:oo(c,n,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:l,level:o}):null}bufferFragmentData(e,t,s,i,n){if(this.state!==P.PARSING)return;let{data1:a,data2:o}=e,c=a;if(o&&(c=Oe(a,o)),!c.length)return;let l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,h={type:e.type,frag:t,part:s,chunkMeta:i,offset:d,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,h),e.dropped&&e.independent&&!s){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let s=t.currentTime,i=q.bufferInfo(t,s,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;let i=this.getLoadPosition();if(!F(i))return null;let a=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,a)}getFwdBufferInfoAtPos(e,t,s,i){let n=q.bufferInfo(e,t,i);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,i);return q.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){let i=e.nextStart;if(i&&s.start>i){let n=e.buffered;if(n){let a=e.len,o=e.bufferedIndex;for(let c=n.length-1;c>o;c--)n[c].start<s.start&&(a+=n[c].end-n[c].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){let s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),n=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return n>=i?(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=B.MAIN){let s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){let s=t.fragments,i=s.length;if(!i)return null;let{config:n}=this,a=t.fragmentStart,o=n.lowLatencyMode&&!!t.partList,c=null;if(t.live){let h=n.initialLiveManifestSize;if(i<h)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${h})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);let u=this.config.startPosition,g=this.hls.startPosition,f=this.hls.liveSyncPosition,p=((l=c)==null?void 0:l.start)||0,y,v;g!==-1&&g>=a?(y=g,v=g===u?"config":"next load start"):f!==null?(y=f,v="live edge"):(y=e,v="buffer pos"),y<p&&(y=p,v="live frag start"),y<a&&(y=a,v="playlist start"),(this.startPosition!=y||this.nextLoadPosition!=y)&&(this.log(`Setting startPosition to ${y.toFixed(3)} ${g===-1?"":`(from ${u}) `}based on ${v}. live edge: ${f} live frag start: ${p.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=y)}}else e<=a&&(c=s[0]);if(!c){let h=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,h,t)}let d=this.filterReplacedPrimary(c,t);if(!d&&c){let h=c.sn-t.startSN;d=this.filterReplacedPrimary(s[h+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let s=this.fragmentTracker.getState(e);return s===fe.OK||s===fe.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,s,i,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=n){let c=a.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(ra(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(ra(this.config)&&e.type!==B.SUBTITLE){let s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){let a=i.event;if(a){if(a.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}let n=s?.playerQueue;if(n)for(let a=n.length;a--;){let o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,n=!1,a=!0;for(let o=0,c=e.length;o<c;o++){let l=e[o];if(a=a&&!l.independent,i>-1&&s<l.start)break;let d=l.loaded;d?i=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),n=d}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,s=this.fragPrevious,i=null;if(s){if(e.hasProgramDateTime&&(i=Rc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){let n=s.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=za(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{let n=this.hls.liveSyncPosition;n!==null&&(i=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){let{config:i}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=s,{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,d=s.partList,h=!!(this.loadingParts&&d!=null&&d.length&&c);h&&!this.bitrateTest&&d[d.length-1].fragment.sn===c.sn&&(a=a.concat(c),o=c.sn);let u;if(e<t){var g;let p=e<this.lastCurrentTime||e>t-l||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:l;u=pt(n,a,e,p)}else u=a[a.length-1];if(u){let f=u.sn-s.startSN,p=this.fragmentTracker.getState(u);if((p===fe.OK||p===fe.PARTIAL&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!h||d[0].fragment.sn>u.sn||!s.live)&&u.level===n.level){let v=a[f+1];u.sn<o&&this.fragmentTracker.getState(v)!==fe.OK?u=v:u=null}}return u}alignPlaylists(e,t,s){let i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&F(n);if(a||!o&&!n){id(s,e);let c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),c}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);let i=this.timelineOffset;if(s===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&F(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;let{media:t}=this,s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&de(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!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){let v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}let i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}let a=t.details===R.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(i,!0);let o=t.errorAction;if(!o){this.state=P.ERROR;return}let{action:c,flags:l,retryCount:d=0,retryConfig:h}=o,u=!!h,g=u&&c===me.RetryRequest,f=u&&!o.resolved&&l===_e.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!g&&f&&de(i)&&!i.endList&&p&&!Qa(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((g||f)&&d<h.maxNumRetry){var y;let v=Mi((y=t.response)==null?void 0:y.code),E=Qn(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){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 ${d+1}/${h.maxNumRetry} in ${E}ms`)}else if(h)if(this.resetFragmentErrors(e),d<h.maxNumRetry)!a&&c!==me.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${d})`);return}else c===me.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Mi(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===P.PARSING||this.state===P.PARSED){let t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,t?.duration||10);let a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===B.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;let i=q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${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,s,i){let n=s.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{let d=e.elementaryStreams[l];if(d){let h=d.endPTS-d.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${h})`),c||!1;let u=i?0:no(n,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:n,level:s,drift:u,type:l,frag:e,start:d.startPTS,end:d.endPTS}),!0}return c},!1)){var o;let c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){let l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===B.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,n;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((n=t&&!s?e.endPTS:(s||e).end)!=null?n:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}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}};function ra(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}var Ms=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,s;if(e.length)e.length===1?s=e[0]:s=rd(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}};function rd(r,e){let t=new Uint8Array(e),s=0;for(let i=0;i<r.length;i++){let n=r[i];t.set(n,s),s+=n.length}return t}var hi={exports:{}},aa;function ad(){return aa||(aa=1,(function(r){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,d){this.fn=c,this.context=l,this.once=d||!1}function n(c,l,d,h,u){if(typeof d!="function")throw new TypeError("The listener must be a function");var g=new i(d,h||c,u),f=t?t+l:l;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],g]:c._events[f].push(g):(c._events[f]=g,c._eventsCount++),c}function a(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],d,h;if(this._eventsCount===0)return l;for(h in d=this._events)e.call(d,h)&&l.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},o.prototype.listeners=function(l){var d=t?t+l:l,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var u=0,g=h.length,f=new Array(g);u<g;u++)f[u]=h[u].fn;return f},o.prototype.listenerCount=function(l){var d=t?t+l:l,h=this._events[d];return h?h.fn?1:h.length:0},o.prototype.emit=function(l,d,h,u,g,f){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],v=arguments.length,E,T;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,h),!0;case 4:return y.fn.call(y.context,d,h,u),!0;case 5:return y.fn.call(y.context,d,h,u,g),!0;case 6:return y.fn.call(y.context,d,h,u,g,f),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];y.fn.apply(y.context,E)}else{var x=y.length,A;for(T=0;T<x;T++)switch(y[T].once&&this.removeListener(l,y[T].fn,void 0,!0),v){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,d);break;case 3:y[T].fn.call(y[T].context,d,h);break;case 4:y[T].fn.call(y[T].context,d,h,u);break;default:if(!E)for(A=1,E=new Array(v-1);A<v;A++)E[A-1]=arguments[A];y[T].fn.apply(y[T].context,E)}}return!0},o.prototype.on=function(l,d,h){return n(this,l,d,h,!1)},o.prototype.once=function(l,d,h){return n(this,l,d,h,!0)},o.prototype.removeListener=function(l,d,h,u){var g=t?t+l:l;if(!this._events[g])return this;if(!d)return a(this,g),this;var f=this._events[g];if(f.fn)f.fn===d&&(!u||f.once)&&(!h||f.context===h)&&a(this,g);else{for(var p=0,y=[],v=f.length;p<v;p++)(f[p].fn!==d||u&&!f[p].once||h&&f[p].context!==h)&&y.push(f[p]);y.length?this._events[g]=y.length===1?y[0]:y:a(this,g)}return this},o.prototype.removeAllListeners=function(l){var d;return l?(d=t?t+l:l,this._events[d]&&a(this,d)):(this._events=new s,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})(hi)),hi.exports}var od=ad(),er=Gl(od),Wt="1.6.16",kt={};function ld(){return typeof __HLS_WORKER_BUNDLE__=="function"}function cd(){let r=kt[Wt];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),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return kt[Wt]=i,i}function dd(r){let e=kt[r];if(e)return e.clientCount++,e;let t=new self.URL(r,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return kt[r]=i,i}function hd(r){let e=kt[r||Wt];if(e&&e.clientCount--===1){let{worker:s,objectURL:i}=e;delete kt[r||Wt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function fo(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 tr(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 js(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 qt(r,e){let t=e,s=0;for(;tr(r,e);){s+=10;let i=js(r,e+6);s+=i,fo(r,e+10)&&(s+=10),e+=s}if(s>0)return r.subarray(t,t+s)}function ud(r,e,t,s){let i=[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 g=new Error(`invalid ADTS sampling index:${a}`);r.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}let o=(n>>6&3)+1,c=e[t+3]>>6&3|(n&1)<<2,l="mp4a.40."+o,d=i[a],h=a;(o===5||o===29)&&(h-=3);let u=[o<<3|(h&14)>>1,(h&1)<<7|c<<3];return se.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${d} (ADTS object type:${o} sampling index:${a})`),{config:u,samplerate:d,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function go(r,e){return r[e]===255&&(r[e+1]&246)===240}function po(r,e){return r[e+1]&1?7:9}function sr(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function fd(r,e){return e+5<r.length}function Os(r,e){return e+1<r.length&&go(r,e)}function gd(r,e){return fd(r,e)&&go(r,e)&&sr(r,e)<=r.length-e}function pd(r,e){if(Os(r,e)){let t=po(r,e);if(e+t>=r.length)return!1;let s=sr(r,e);if(s<=t)return!1;let i=e+s;return i===r.length||Os(r,i)}return!1}function mo(r,e,t,s,i){if(!r.samplerate){let n=ud(e,t,s,i);if(!n)return;ie(r,n)}}function yo(r){return 1024*9e4/r}function md(r,e){let t=po(r,e);if(e+t<=r.length){let s=sr(r,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function vo(r,e,t,s,i){let n=yo(r.samplerate),a=s+i*n,o=md(e,t),c;if(o){let{frameLength:h,headerLength:u}=o,g=u+h,f=Math.max(0,t+g-e.length);f?(c=new Uint8Array(g-u),c.set(e.subarray(t+u,e.length),0)):c=e.subarray(t+u,t+g);let p={unit:c,pts:a};return f||r.samples.push(p),{sample:p,length:g,missing:f}}let l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:a},length:l,missing:-1}}function yd(r,e){return tr(r,e)&&js(r,e+6)+10<=r.length-e}function vd(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function ui(r,e=0,t=1/0){return Ed(r,e,t,Uint8Array)}function Ed(r,e,t,s){let i=Td(r),n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);let a=Sd(r)?r.byteOffset:0,o=(a+r.byteLength)/n,c=(a+e)/n,l=Math.floor(Math.max(0,Math.min(c,o))),d=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,d-l)}function Td(r){return r instanceof ArrayBuffer?r:r.buffer}function Sd(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function xd(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 s=r.data.subarray(1).indexOf(0);if(s===-1)return;let i=ke(ui(r.data,1,s)),n=r.data[2+s],a=r.data.subarray(3+s).indexOf(0);if(a===-1)return;let o=ke(ui(r.data,3+s,a)),c;return i==="-->"?c=ke(ui(r.data,4+s+a)):c=vd(r.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=n,e.description=o,e.data=c,e}function Ad(r){if(r.size<2)return;let e=ke(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function Ld(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1,s=ke(r.data.subarray(t),!0);t+=s.length+1;let i=ke(r.data.subarray(t));return{key:r.type,info:s,data:i}}let e=ke(r.data.subarray(1));return{key:r.type,info:"",data:e}}function Id(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1,s=ke(r.data.subarray(t),!0);t+=s.length+1;let i=ke(r.data.subarray(t));return{key:r.type,info:s,data:i}}let e=ke(r.data);return{key:r.type,info:"",data:e}}function bd(r){return r.type==="PRIV"?Ad(r):r.type[0]==="W"?Id(r):r.type==="APIC"?xd(r):Ld(r)}function Rd(r){let e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=js(r,4),s=10;return{type:e,size:t,data:r.subarray(s,s+t)}}var rs=10,_d=10;function Eo(r){let e=0,t=[];for(;tr(r,e);){let s=js(r,e+6);r[e+5]>>6&1&&(e+=rs),e+=rs;let i=e+s;for(;e+_d<i;){let n=Rd(r.subarray(e)),a=bd(n);a&&t.push(a),e+=n.size+rs}fo(r,e)&&(e+=rs)}return t}function To(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function Pd(r){if(r.data.byteLength===8){let e=new Uint8Array(r.data),t=e[3]&1,s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function ir(r){let e=Eo(r);for(let t=0;t<e.length;t++){let s=e[t];if(To(s))return Pd(s)}}var De=(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 Ye(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var jt=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,s,i){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,s){}demux(e,t){this.cachedData&&(e=Oe(this.cachedData,e),this.cachedData=null);let s=qt(e,0),i=s?s.length:0,n,a=this._audioTrack,o=this._id3Track,c=s?ir(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&F(c))&&(this.basePTS=Dd(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:De.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){let d=this.appendFrame(a,e,i);d?(this.frameIndex++,this.lastPTS=d.sample.pts,i+=d.length,n=i):i=l}else yd(e,i)?(s=qt(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:De.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,n=i):i++;if(i===l&&n!==l){let d=e.slice(n);this.cachedData?this.cachedData=Oe(this.cachedData,d):this.cachedData=d}}return{audioTrack:a,videoTrack:Ye(),id3Track:o,textTrack:Ye()}}demuxSampleAes(e,t,s){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:Ye(),id3Track:this._id3Track,textTrack:Ye()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},Dd=(r,e,t)=>{if(F(r))return r*90;let s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s},as=null,kd=[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],Cd=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],wd=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Md=[0,1,1,4];function So(r,e,t,s,i){if(t+24>e.length)return;let n=xo(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=s+i*a,c={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(c),{sample:c,length:n.frameLength,missing:0}}}function xo(r,e){let t=r[e+1]>>3&3,s=r[e+1]>>1&3,i=r[e+2]>>4&15,n=r[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&n!==3){let a=r[e+2]>>1&1,o=r[e+3]>>6,c=t===3?3-s:s===3?3:4,l=kd[c*14+i-1]*1e3,h=Cd[(t===3?0:t===2?1:2)*3+n],u=o===3?1:2,g=wd[t][s],f=Md[s],p=g*8*f,y=Math.floor(g*l/h+a)*f;if(as===null){let T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);as=T?parseInt(T[1]):0}return as&&as<=87&&s===2&&l>=224e3&&o===0&&(r[e+3]=r[e+3]|128),{sampleRate:h,channelCount:u,frameLength:y,samplesPerFrame:p}}}function nr(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Ao(r,e){return e+1<r.length&&nr(r,e)}function Od(r,e){return nr(r,e)&&4<=r.length-e}function Lo(r,e){if(e+1<r.length&&nr(r,e)){let s=xo(r,e),i=4;s!=null&&s.frameLength&&(i=s.frameLength);let n=e+i;return n===r.length||Ao(r,n)}return!1}var Wi=class extends jt{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let s=qt(e,0),i=s?.length||0;if(Lo(e,i))return!1;for(let n=e.length;i<n;i++)if(pd(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return gd(e,t)}appendFrame(e,t,s){mo(e,this.observer,t,s,e.manifestCodec);let i=vo(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}},Io=(r,e)=>{let t=0,s=5;e+=s;let i=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=r[e];let o=Math.min(s,8),c=8-o;n[0]=4278190080>>>24+c<<c,i[0]=(a[0]&n[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t},qi=class extends jt{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){let i=bo(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;let t=qt(e,0);if(!t)return!1;let s=t.length;return e[s]===11&&e[s+1]===119&&ir(t)!==void 0&&Io(e,s)<16}};function bo(r,e,t,s,i){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],c=e[t+4]&63,d=[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][c*3+n]*2;if(t+d>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 g=(e[t+6]<<8|e[t+7])>>12-u&1,p=[2,1,2,3,3,4,4,5][h]+g,y=e[t+5]>>3,v=e[t+5]&7,E=new Uint8Array([n<<6|y<<1|v>>2,(v&3)<<6|h<<3|g<<2|c>>4,c<<4&224]),T=1536/o*9e4,x=s+i*T,A=e.subarray(t,t+d);return r.config=E,r.channelCount=p,r.samplerate=o,r.samples.push({unit:A,pts:x}),d}var ji=class extends jt{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=qt(e,0),s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&ir(t)!==void 0&&Io(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Lo(e,s))return se.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Od(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return So(e,t,s,this.basePTS,this.frameIndex)}},Fd=/\/emsg[-/]ID3/i,zi=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){let n=this.videoTrack=Ye("video",1),a=this.audioTrack=Ye("audio",1),o=this.txtTrack=Ye("text",1);if(this.id3Track=Ye("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let c=Ba(e);if(c.video){let{id:l,timescale:d,codec:h,supplemental:u}=c.video;n.id=l,n.timescale=o.timescale=d,n.codec=h,n.supplemental=u}if(c.audio){let{id:l,timescale:d,codec:h}=c.audio;a.id=l,a.timescale=d,a.codec=h}o.id=Oa.text,n.sampleDuration=0,n.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Yl(e)}demux(e,t){this.timeOffset=t;let s=e,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Oe(this.remainderData,e));let o=Zl(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;let a=this.extractID3Track(i,t);return n.samples=Ir(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let i=this.extractID3Track(t,this.timeOffset);return s.samples=Ir(e,t),{videoTrack:t,audioTrack:Ye(),id3Track:i,textTrack:Ye()}}extractID3Track(e,t){let s=this.id3Track;if(e.samples.length){let i=X(e.samples,["emsg"]);i&&i.forEach(n=>{let a=ec(n);if(Fd.test(a.schemeIdUri)){let o=oa(a,t),c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);let l=a.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:De.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let o=oa(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:De.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function oa(r,e){return F(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}var Xi=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Vt(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,nt.cbc)}decryptAacSample(e,t,s){let i=e[t].unit;if(i.length<=16)return;let n=i.subarray(16,i.length-i.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t),i=0;for(let n=32;n<e.length-16;n+=160,i+=16)s.set(e.subarray(n,n+16),i);return s}getAvcDecryptedUnit(e,t){let s=new Uint8Array(t),i=0;for(let n=32;n<e.length-16;n+=160,i+=16)e.set(s.subarray(i,i+16),n);return e}decryptAvcSample(e,t,s,i,n){let a=Ga(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(c=>{n.data=this.getAvcDecryptedUnit(a,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}let n=e[t].units;for(;!(s>=n.length);s++){let a=n[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,i,a),!this.decrypter.isSync()))return}}}},Fs=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){let n=s.units;i=n[n.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let s=t.samples,i=s.length;if(i){let n=s[i-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){let i=t.byteLength,n=e.naluState||0,a=n,o=[],c=0,l,d,h,u=-1,g=0;for(n===-1&&(u=0,g=this.getNALuType(t,0),n=0,c=1);c<i;){if(l=t[c++],!n){n=l?0:1;continue}if(n===1){n=l?0:2;continue}if(!l)n=3;else if(l===1){if(d=c-n-1,u>=0){let f={data:t.subarray(u,d),type:g};o.push(f)}else{let f=this.getLastNalUnit(e.samples);f&&(a&&c<=4-a&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-a)),d>0&&(f.data=Oe(f.data,t.subarray(0,d)),f.state=0))}c<i?(h=this.getNALuType(t,c),u=c,g=h,n=0):n=-1}else n=0}if(u>=0&&n>=0){let f={data:t.subarray(u,i),type:g,state:n};o.push(f)}if(o.length===0){let f=this.getLastNalUnit(e.samples);f&&(f.data=Oe(f.data,t))}return e.naluState=n,o}},ft=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,s=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");i.set(e.subarray(s,s+n)),this.word=new DataView(i.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),s=this.word>>>32-t;if(e>32&&se.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?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},Qi=class extends Fs{parsePES(e,t,s,i){let n=this.parseNALu(e,s.data,i),a=this.VideoSample,o,c=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(l=>{var d,h;switch(l.type){case 1:{let p=!1;o=!0;let y=l.data;if(c&&y.length>4){let v=this.readSliceType(y);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var u;(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,jn(l.data,1,s.pts,t.samples);break}case 7:{var g,f;o=!0,c=!0;let p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((g=e.pixelRatio)==null?void 0:g[0])!==y.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];let v=p.subarray(1,4),E="avc1.";for(let T=0;T<3;T++){let x=v[T].toString(16);x.length<2&&(x="0"+x),E+=x}e.codec=E}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new ft(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,n;for(let a=0;a<e;a++)i!==0&&(n=t.readEG(),i=(s+n+256)%256),s=i===0?s:i}readSPS(e){let t=new ft(e),s=0,i=0,n=0,a=0,o,c,l,d=t.readUByte.bind(t),h=t.readBits.bind(t),u=t.readUEG.bind(t),g=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);d();let E=d();if(h(5),f(3),d(),y(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){let I=u();if(I===3&&f(1),y(),y(),f(1),g())for(c=I!==3?8:12,l=0;l<c;l++)g()&&(l<6?v(16,t):v(64,t))}y();let T=u();if(T===0)u();else if(T===1)for(f(1),p(),p(),o=u(),l=0;l<o;l++)p();y(),f(1);let x=u(),A=u(),_=h(1);_===0&&f(1),f(1),g()&&(s=u(),i=u(),n=u(),a=u());let S=[1,1];if(g()&&g())switch(d()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[d()<<8|d(),d()<<8|d()];break}}return{width:Math.ceil((x+1)*16-s*2-i*2),height:(2-_)*(A+1)*16-(_?2:4)*(n+a),pixelRatio:S}}},Zi=class extends Fs{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){let n=this.parseNALu(e,s.data,i),a=this.VideoSample,o,c=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(l=>{var d,h;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var u;(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,jn(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ie(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let g=this.readSPS(l.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let f in g.params)e.params[f]=g.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let g=this.readPPS(l.data);for(let f in g)e.params[f]=g[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new ft(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){let t=new ft(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let s=t.readBits(3);t.readBoolean();let i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),d=t.readUByte(),h=t.readUByte(),u=t.readUByte(),g=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),v=t.readUByte(),E=[],T=[];for(let J=0;J<s;J++)E.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let J=s;J<8;J++)t.readBits(2);for(let J=0;J<s;J++)E[J]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[J]&&t.readUByte();t.readUEG();let x=t.readUEG();x==3&&t.skipBits(1);let A=t.readUEG(),_=t.readUEG(),S=t.readBoolean(),I=0,b=0,L=0,D=0;S&&(I+=t.readUEG(),b+=t.readUEG(),L+=t.readUEG(),D+=t.readUEG());let C=t.readUEG(),$=t.readUEG(),H=t.readUEG(),U=t.readBoolean();for(let J=U?0:s;J<=s;J++)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 xe=0;xe<4;xe++)for(let Me=0;Me<(xe===3?2:6);Me++)if(!t.readBoolean())t.readUEG();else{let Ne=Math.min(64,1<<4+(xe<<1));xe>1&&t.readEG();for(let mt=0;mt<Ne;mt++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let N=t.readUEG(),K=0;for(let J=0;J<N;J++){let xe=!1;if(J!==0&&(xe=t.readBoolean()),xe){J===N&&t.readUEG(),t.readBoolean(),t.readUEG();let Me=0;for(let at=0;at<=K;at++){let Ne=t.readBoolean(),mt=!1;Ne||(mt=t.readBoolean()),(Ne||mt)&&Me++}K=Me}else{let Me=t.readUEG(),at=t.readUEG();K=Me+at;for(let Ne=0;Ne<Me;Ne++)t.readUEG(),t.readBoolean();for(let Ne=0;Ne<at;Ne++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let J=t.readUEG();for(let xe=0;xe<J;xe++){for(let Me=0;Me<H+4;Me++)t.readBits(1);t.readBits(1)}}let w=0,M=1,j=1,ee=!0,z=1,Z=0;t.readBoolean(),t.readBoolean();let Se=!1;if(t.readBoolean()){if(t.readBoolean()){let ot=t.readUByte(),pr=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Jt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ot>0&&ot<16?(M=pr[ot-1],j=Jt[ot-1]):ot===255&&(M=t.readBits(16),j=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(),Se=t.readBoolean(),Se&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(z=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Jt=t.readBoolean(),mr=t.readBoolean(),Ct=!1;(Jt||mr)&&(Ct=t.readBoolean(),Ct&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ct&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let yr=0;yr<=s;yr++){ee=t.readBoolean();let Il=ee||t.readBoolean(),vr=!1;Il?t.readEG():vr=t.readBoolean();let Er=vr?1:t.readUEG()+1;if(Jt)for(let wt=0;wt<Er;wt++)t.readUEG(),t.readUEG(),Ct&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(mr)for(let wt=0;wt<Er;wt++)t.readUEG(),t.readUEG(),Ct&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),w=t.readUEG())}let we=A,Ge=_;if(S){let J=1,xe=1;x===1?J=xe=2:x==2&&(J=2),we=A-J*b-J*I,Ge=_-xe*D-xe*L}let rt=i?["A","B","C"][i]:"",Ll=o<<24|c<<16|l<<8|d,si=0;for(let J=0;J<32;J++)si=(si|(Ll>>J&1)<<31-J)>>>0;let ii=si.toString(16);return a===1&&ii==="2"&&(ii="6"),{codecString:`hvc1.${rt}${a}.${ii}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,d],general_constraint_indicator_flags:[h,u,g,f,p,y],general_level_idc:v,bit_depth:C+8,bit_depth_luma_minus8:C,bit_depth_chroma_minus8:$,min_spatial_segmentation_idc:w,chroma_format_idc:x,frame_rate:{fixed:ee,fps:Z/z}},width:we,height:Ge,pixelRatio:[M,j]}}readPPS(e){let t=new ft(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let i=t.readBoolean(),n=t.readBoolean(),a=1;return n&&i?a=0:n?a=3:i&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},pe=188,Ji=class r{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){let s=r.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){let t=e.length,s=Math.min(pe*5,t-pe)+1,i=0;for(;i<s;){let n=!1,a=-1,o=0;for(let c=i;c<t;c+=pe)if(e[c]===71&&(t-c===pe||e[c+pe]===71)){if(o++,a===-1&&(a=c,a!==0&&(s=Math.min(a+pe*99,e.length-pe)+1)),n||(n=en(e,c)===0),n&&o>1&&(a===0&&o>2||c+pe>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Oa[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=r.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=r.createTrack("audio",i),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=s}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let n,a=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack,d=a.pid,h=a.pesData,u=o.pid,g=c.pid,f=o.pesData,p=c.pesData,y=null,v=this.pmtParsed,E=this._pmtId,T=e.length;if(this.remainderData&&(e=Oe(this.remainderData,e),T=e.length,this.remainderData=null),T<pe&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};let x=Math.max(0,r.syncOffset(e));T-=(T-x)%pe,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let A=0;for(let S=x;S<T;S+=pe)if(e[S]===71){let I=!!(e[S+1]&64),b=en(e,S),L=(e[S+3]&48)>>4,D;if(L>1){if(D=S+5+e[S+4],D===S+pe)continue}else D=S+4;switch(b){case d:I&&(h&&(n=Et(h,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,l,n,!1)),h={data:[],size:0}),h&&(h.data.push(e.subarray(D,S+pe)),h.size+=S+pe-D);break;case u:if(I){if(f&&(n=Et(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(D,S+pe)),f.size+=S+pe-D);break;case g:I&&(p&&(n=Et(p,this.logger))&&this.parseID3PES(c,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(D,S+pe)),p.size+=S+pe-D);break;case 0:I&&(D+=e[D]+1),E=this._pmtId=Nd(e,D);break;case E:{I&&(D+=e[D]+1);let C=Bd(e,D,this.typeSupported,s,this.observer,this.logger);d=C.videoPid,d>0&&(a.pid=d,a.segmentCodec=C.segmentVideoCodec),u=C.audioPid,u>0&&(o.pid=u,o.segmentCodec=C.segmentAudioCodec),g=C.id3Pid,g>0&&(c.pid=g),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${S} after unknown PID '${y}'. Backtracking to sync byte @${x} to parse all TS packets.`),y=null,S=x-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=b;break}}else A++;A>0&&tn(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,o.pesData=f,c.pesData=p;let _={audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(_),_}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:s,id3Track:i,textTrack:n}=e,a=s.pesData,o=t.pesData,c=i.pesData,l;if(a&&(l=Et(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,l,!0),s.pesData=null)):s.pesData=a,o&&(l=Et(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=Et(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){let i=this.demux(e,s,!0,!this.config.progressive),n=this.sampleAes=new Xi(this.observer,this.config,t);return this.decrypt(i,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Qi:e==="hevc"&&(this.videoParser=new Zi))}decrypt(e,t){return new Promise(s=>{let{audioTrack:i,videoTrack:n}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{s(e)}):s(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0,i=this.aacOverFlow,n=t.data;if(i){this.aacOverFlow=null;let h=i.missing,u=i.sample.unit.byteLength;if(h===-1)n=Oe(i.sample.unit,n);else{let g=u-h;i.sample.unit.set(n.subarray(0,h),g),e.samples.push(i.sample),s=i.missing}}let a,o;for(a=s,o=n.length;a<o-1&&!Os(n,a);a++);if(a!==s){let h,u=a<o-1;if(u?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES",tn(this.observer,new Error(h),u,this.logger),!u)return}mo(e,this.observer,n,a,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){let h=yo(e.samplerate);c=i.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,d;for(;a<o;)if(d=vo(e,n,a,c,l),a+=d.length,d.missing){this.aacOverFlow=d;break}else for(l++;a<o-1&&!Os(n,a);a++);}parseMPEGPES(e,t){let s=t.data,i=s.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(Ao(s,a)){let c=So(e,s,a,o,n);if(c)a+=c.length,n++;else break}else a++}parseAC3PES(e,t){{let s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=s.length,a=0,o=0,c;for(;o<n&&(c=bo(e,s,o,i,a++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let s=ie({},t,{type:this._videoTrack?De.emsg:De.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}};function en(r,e){return((r[e+1]&31)<<8)+r[e+2]}function Nd(r,e){return(r[e+10]&31)<<8|r[e+11]}function Bd(r,e,t,s,i,n){let a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(r[e+1]&15)<<8|r[e+2],c=e+3+o-4,l=(r[e+10]&15)<<8|r[e+11];for(e+=12+l;e<c;){let d=en(r,e),h=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!s){fi("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=d);break;case 21:a.id3Pid===-1&&(a.id3Pid=d);break;case 219:if(!s){fi("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=d);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=d,a.segmentAudioCodec="mp3");break;case 193:if(!s){fi("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=d,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&h>0){let u=e+5,g=h;for(;g>2;){r[u]===106&&(t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=d,a.segmentAudioCodec="ac3"));let p=r[u+1]+2;u+=p,g-=p}}break;case 194:case 135:return tn(i,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=d,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=h+5}return a}function tn(r,e,t,s){s.warn(`parsing error: ${e.message}`),r.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function fi(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Et(r,e){let t=0,s,i,n,a,o,c=r.data;if(!r||r.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Oe(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>r.size-6)return null;let d=s[7];d&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,d&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[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=s[8];let h=n+9;if(r.size<=h)return null;r.size-=h;let u=new Uint8Array(r.size);for(let g=0,f=c.length;g<f;g++){s=c[g];let p=s.byteLength;if(h)if(h>p){h-=p;continue}else s=s.subarray(h),p-=h,h=0;u.set(s,t),t+=p}return i&&(i-=n+3),{data:u,pts:a,dts:o,len:i}}return null}var sn=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}}},Je=Math.pow(2,32)-1,ge=class r{static init(){r.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in r.types)r.types.hasOwnProperty(e)&&(r.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);let t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);r.HDLR_TYPES={video:t,audio:s};let i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);r.STTS=r.STSC=r.STCO=n,r.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),r.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),r.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),r.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);r.FTYP=r.box(r.types.ftyp,a,c,a,o),r.DINF=r.box(r.types.dinf,r.box(r.types.dref,i))}static box(e,...t){let s=8,i=t.length,n=i;for(;i--;)s+=t[i].byteLength;let a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(e,4),i=0,s=8;i<n;i++)a.set(t[i],s),s+=t[i].byteLength;return a}static hdlr(e){return r.box(r.types.hdlr,r.HDLR_TYPES[e])}static mdat(e){return r.box(r.types.mdat,e)}static mdhd(e,t){t*=e;let s=Math.floor(t/(Je+1)),i=Math.floor(t%(Je+1));return r.box(r.types.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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return r.box(r.types.mdia,r.mdhd(e.timescale||0,e.duration||0),r.hdlr(e.type),r.minf(e))}static mfhd(e){return r.box(r.types.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(r.types.minf,r.box(r.types.smhd,r.SMHD),r.DINF,r.stbl(e)):r.box(r.types.minf,r.box(r.types.vmhd,r.VMHD),r.DINF,r.stbl(e))}static moof(e,t,s){return r.box(r.types.moof,r.mfhd(e),r.traf(s,t))}static moov(e){let t=e.length,s=[];for(;t--;)s[t]=r.trak(e[t]);return r.box.apply(null,[r.types.moov,r.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(r.mvex(e)))}static mvex(e){let t=e.length,s=[];for(;t--;)s[t]=r.trex(e[t]);return r.box.apply(null,[r.types.mvex,...s])}static mvhd(e,t){t*=e;let s=Math.floor(t/(Je+1)),i=Math.floor(t%(Je+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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&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(r.types.mvhd,n)}static sdtp(e){let t=e.samples||[],s=new Uint8Array(4+t.length),i,n;for(i=0;i<t.length;i++)n=t[i].flags,s[i+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return r.box(r.types.sdtp,s)}static stbl(e){return r.box(r.types.stbl,r.stsd(e),r.box(r.types.stts,r.STTS),r.box(r.types.stsc,r.STSC),r.box(r.types.stsz,r.STSZ),r.box(r.types.stco,r.STCO))}static avc1(e){let t=[],s=[],i,n,a;for(i=0;i<e.sps.length;i++)n=e.sps[i],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(i=0;i<e.pps.length;i++)n=e.pps[i],a=n.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));let o=r.box(r.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return r.box(r.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&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(r.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r.box(r.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...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(r.types.mp4a,r.audioStsd(e),r.box(r.types.esds,r.esds(e)))}static mp3(e){return r.box(r.types[".mp3"],r.audioStsd(e))}static ac3(e){return r.box(r.types["ac-3"],r.audioStsd(e),r.box(r.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return r.box(r.types.stsd,r.STSD,r.mp4a(e));if(t==="ac3"&&e.config)return r.box(r.types.stsd,r.STSD,r.ac3(e));if(t==="mp3"&&e.codec==="mp3")return r.box(r.types.stsd,r.STSD,r.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return r.box(r.types.stsd,r.STSD,r.avc1(e));if(t==="hevc"&&e.vps)return r.box(r.types.stsd,r.STSD,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,s=(e.duration||0)*(e.timescale||0),i=e.width||0,n=e.height||0,a=Math.floor(s/(Je+1)),o=Math.floor(s%(Je+1));return r.box(r.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,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,i>>8&255,i&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let s=r.sdtp(e),i=e.id,n=Math.floor(t/(Je+1)),a=Math.floor(t%(Je+1));return r.box(r.types.traf,r.box(r.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),r.box(r.types.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,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,r.box(r.types.trak,r.tkhd(e),r.mdia(e))}static trex(e){let t=e.id;return r.box(r.types.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 s=e.samples||[],i=s.length,n=12+16*i,a=new Uint8Array(n),o,c,l,d,h,u;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,d=c.size,h=c.flags,u=c.cts,a.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,d>>>24&255,d>>>16&255,d>>>8&255,d&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(r.types.trun,a)}static initSegment(e){r.types||r.init();let t=r.moov(e);return Oe(r.FTYP,t)}static hvc1(e){let t=e.params,s=[e.vps,e.sps,e.pps],i=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),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]),a=n.length;for(let f=0;f<s.length;f+=1){a+=3;for(let p=0;p<s[f].length;p+=1)a+=2+s[f][p].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let c=s.length-1;for(let f=0;f<s.length;f+=1){o.set(new Uint8Array([32+f|(f===c?128:0),0,s[f].length]),a),a+=3;for(let p=0;p<s[f].length;p+=1)o.set(new Uint8Array([s[f][p].length>>8,s[f][p].length&255]),a),a+=2,o.set(s[f][p],a),a+=s[f][p].length}let l=r.box(r.types.hvcC,o),d=e.width,h=e.height,u=e.pixelRatio[0],g=e.pixelRatio[1];return r.box(r.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,d>>8&255,d&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]),l,r.box(r.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r.box(r.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,g>>24,g>>16&255,g>>8&255,g&255])))}};ge.types=void 0;ge.HDLR_TYPES=void 0;ge.STTS=void 0;ge.STSC=void 0;ge.STCO=void 0;ge.STSZ=void 0;ge.VMHD=void 0;ge.SMHD=void 0;ge.STSD=void 0;ge.FTYP=void 0;ge.DINF=void 0;var Ro=9e4;function rr(r,e,t=1,s=!1){let i=r*e*t;return s?Math.round(i):i}function $d(r,e,t=1,s=!1){return rr(r,e,1/t,s)}function Mt(r,e=!1){return rr(r,1e3,1/Ro,e)}function Ud(r,e=1){return rr(r,Ro,1/e)}function la(r){let{baseTime:e,timescale:t,trackId:s}=r;return`${e/t} (${e}/${t}) trackId: ${s}`}var Gd=10*1e3,Kd=1024,Vd=1152,Hd=1536,Tt=null,gi=null;function ca(r,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}var Rt=class extends Re{constructor(e,t,s,i){if(super("mp4-remuxer",i),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=s,this.ISGenerated=!1,Tt===null){let a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Tt=a?parseInt(a[1]):0}if(gi===null){let n=navigator.userAgent.match(/Safari\/(\d+)/i);gi=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&la(t)} > ${e&&la(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,s=e[0].pts,i=e.reduce((n,a)=>{let o=a.pts,c=o-n;return c<-4294967296&&(t=!0,o=Pe(o,s),c=o-n),c>0?n:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,n,a,o,c){let l,d,h,u,g,f,p=n,y=n,v=e.pid>-1,E=t.pid>-1,T=t.samples.length,x=e.samples.length>0,A=o&&T>0||T>1;if((!v||x)&&(!E||A)||this.ISGenerated||o){if(this.ISGenerated){var S,I,b,L;let H=this.videoTrackConfig;(H&&(t.width!==H.width||t.height!==H.height||((S=t.pixelRatio)==null?void 0:S[0])!==((I=H.pixelRatio)==null?void 0:I[0])||((b=t.pixelRatio)==null?void 0:b[1])!==((L=H.pixelRatio)==null?void 0:L[1]))||!H&&A||this.nextAudioTs===null&&x)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));let D=this.isVideoContiguous,C=-1,$;if(A&&(C=Yd(t.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,C>0){this.warn(`Dropped ${C} out of ${T} video samples due to a missing keyframe`);let H=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(C),t.dropped+=C,y+=(t.samples[0].pts-H)/t.inputTimeScale,$=y}else C===-1&&(this.warn(`No keyframe found out of ${T} video samples`),f=!1);if(this.ISGenerated){if(x&&A){let H=this.getVideoStartPts(t.samples),k=(Pe(e.samples[0].pts,H)-H)/t.inputTimeScale;p+=Math.max(0,k),y+=Math.max(0,-k)}if(x){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),d=this.remuxAudio(e,p,this.isAudioContiguous,a,E||A||c===B.AUDIO?y:void 0),A){let H=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,a)),l=this.remuxVideo(t,y,D,H)}}else A&&(l=this.remuxVideo(t,y,D,0));l&&(l.firstKeyFrame=C,l.independent=C!==-1,l.firstKeyFramePTS=$)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=_o(s,n,this._initPTS,this._initDTS)),i.samples.length&&(u=Po(i,n,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:u,id3:g}}computeInitPts(e,t,s,i){let n=Math.round(s*t),a=Pe(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${i}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,s,i){let n=e.samples,a=t.samples,o=this.typeSupported,c={},l=this._initPTS,d=!l||i,h="audio/mp4",u,g,f,p=-1;if(d&&(u=g=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}c.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):ge.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(p=e.id,f=e.inputTimeScale,!l||f!==l.timescale?u=g=this.computeInitPts(n[0].pts,f,s,"audio"):d=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:ge.initSegment([t]),metadata:{width:t.width,height:t.height}},d)if(p=t.id,f=t.inputTimeScale,!l||f!==l.timescale){let y=this.getVideoStartPts(a),v=Pe(a[0].dts,y),E=this.computeInitPts(v,f,s,"video"),T=this.computeInitPts(y,f,s,"video");g=Math.min(g,E),u=Math.min(u,T)}else d=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,d?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${u/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${u/f} (${u}/${f}) trackId: ${p}`),this._initPTS={baseTime:u,timescale:f,trackId:p},this._initDTS={baseTime:g,timescale:f,trackId:p}):u=f=void 0,{tracks:c,initPTS:u,timescale:f,trackId:p}}remuxVideo(e,t,s,i){let n=e.inputTimeScale,a=e.samples,o=[],c=a.length,l=this._initPTS,d=l.baseTime*n/l.timescale,h=this.nextVideoTs,u=8,g=this.videoSampleDuration,f,p,y=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,E=!1;if(!s||h===null){let w=d+t*n,M=a[0].pts-Pe(a[0].dts,a[0].pts);Tt&&h!==null&&Math.abs(w-M-(h+d))<15e3?s=!0:h=w-M-d}let T=h+d;for(let w=0;w<c;w++){let M=a[w];M.pts=Pe(M.pts,T),M.dts=Pe(M.dts,T),M.dts<a[w>0?w-1:w].dts&&(E=!0)}E&&a.sort(function(w,M){let j=w.dts-M.dts,ee=w.pts-M.pts;return j||ee}),f=a[0].dts,p=a[a.length-1].dts;let x=p-f,A=x?Math.round(x/(c-1)):g||e.inputTimeScale/30;if(s){let w=f-T,M=w>A,j=w<-1;if((M||j)&&(M?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Mt(w,!0)} ms (${w}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Mt(-w,!0)} ms (${w}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!j||T>=a[0].pts||Tt)){f=T;let ee=a[0].pts-w;if(M)a[0].dts=f,a[0].pts=ee;else{let z=!0;for(let Z=0;Z<a.length&&!(a[Z].dts>ee&&z);Z++){let Se=a[Z].pts;if(a[Z].dts-=w,a[Z].pts-=w,Z<a.length-1){let ye=a[Z+1].pts,we=a[Z].pts,Ge=ye<=we,rt=ye<=Se;z=Ge==rt}}}this.log(`Video: Initial PTS/DTS adjusted: ${Mt(ee,!0)}/${Mt(f,!0)}, delta: ${Mt(w,!0)} ms`)}}f=Math.max(0,f);let _=0,S=0,I=f;for(let w=0;w<c;w++){let M=a[w],j=M.units,ee=j.length,z=0;for(let Z=0;Z<ee;Z++)z+=j[Z].data.length;S+=z,_+=ee,M.length=z,M.dts<I?(M.dts=I,I+=A/4|0||1):I=M.dts,y=Math.min(M.pts,y),v=Math.max(M.pts,v)}p=a[c-1].dts;let b=S+4*_+8,L;try{L=new Uint8Array(b)}catch(w){this.observer.emit(m.ERROR,m.ERROR,{type:V.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:b,reason:`fail allocating video mdat ${b}`});return}let D=new DataView(L.buffer);D.setUint32(0,b),L.set(ge.types.mdat,4);let C=!1,$=Number.POSITIVE_INFINITY,H=Number.POSITIVE_INFINITY,U=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let w=0;w<c;w++){let M=a[w],j=M.units,ee=0;for(let Se=0,ye=j.length;Se<ye;Se++){let we=j[Se],Ge=we.data,rt=we.data.byteLength;D.setUint32(u,rt),u+=4,L.set(Ge,u),u+=rt,ee+=4+rt}let z;if(w<c-1)g=a[w+1].dts-M.dts,z=a[w+1].pts-M.pts;else{let Se=this.config,ye=w>0?M.dts-a[w-1].dts:A;if(z=w>0?M.pts-a[w-1].pts:A,Se.stretchShortVideoTrack&&this.nextAudioTs!==null){let we=Math.floor(Se.maxBufferHole*n),Ge=(i?y+i*n:this.nextAudioTs+d)-M.pts;Ge>we?(g=Ge-ye,g<0?g=ye:C=!0,this.log(`It is approximately ${Ge/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=ye}else g=ye}let Z=Math.round(M.pts-M.dts);$=Math.min($,g),U=Math.max(U,g),H=Math.min(H,z),k=Math.max(k,z),o.push(ca(M.key,g,ee,Z))}if(o.length){if(Tt){if(Tt<70){let w=o[0].flags;w.dependsOn=2,w.isNonSync=0}}else if(gi&&k-H<U-$&&A/U<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let w=f;for(let M=0,j=o.length;M<j;M++){let ee=w+o[M].duration,z=w+o[M].cts;if(M<j-1){let Z=ee+o[M+1].cts;o[M].duration=Z-z}else o[M].duration=M?o[M-1].duration:A;o[M].cts=0,w=ee}}}g=C||!g?A:g;let G=p+g;this.nextVideoTs=h=G-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;let Y={data1:ge.moof(e.sequenceNumber++,f,ie(e,{samples:o})),data2:L,startPTS:(y-d)/n,endPTS:(v+g-d)/n,startDTS:(f-d)/n,endDTS:h/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Vd;case"ac3":return Hd;default:return Kd}}remuxAudio(e,t,s,i,n){let a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,c=a/o,l=this.getSamplesPerFrame(e),d=l*c,h=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],f=n!==void 0,p=e.samples,y=u?0:8,v=this.nextAudioTs||-1,E=h.baseTime*a/h.timescale,T=E+t*a;if(this.isAudioContiguous=s=s||p.length&&v>0&&(i&&Math.abs(T-(v+E))<9e3||Math.abs(Pe(p[0].pts,T)-(v+E))<20*d),p.forEach(function(k){k.pts=Pe(k.pts,T)}),!s||v<0){let k=p.length;if(p=p.filter(G=>G.pts>=0),k!==p.length&&this.warn(`Removed ${p.length-k} of ${k} samples (initPTS ${E} / ${a})`),!p.length)return;n===0?v=0:i&&!f?v=Math.max(0,T-E):v=p[0].pts-E}if(e.segmentCodec==="aac"){let k=this.config.maxAudioFramesDrift;for(let G=0,N=v+E;G<p.length;G++){let K=p[G],Y=K.pts,w=Y-N,M=Math.abs(1e3*w/a);if(w<=-k*d&&f)G===0&&(this.warn(`Audio frame @ ${(Y/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*w/a)} ms.`),this.nextAudioTs=v=Y-E,N=Y);else if(w>=k*d&&M<Gd&&f){let j=Math.round(w/d);for(N=Y-j*d;N<0&&j&&d;)j--,N+=d;G===0&&(this.nextAudioTs=v=N-E),this.warn(`Injecting ${j} audio frames @ ${((N-E)/a).toFixed(3)}s due to ${Math.round(1e3*w/a)} ms gap.`);for(let ee=0;ee<j;ee++){let z=sn.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(G,0,{unit:z,pts:N}),N+=d,G++}}K.pts=N,N+=d}}let x=null,A=null,_,S=0,I=p.length;for(;I--;)S+=p[I].unit.byteLength;for(let k=0,G=p.length;k<G;k++){let N=p[k],K=N.unit,Y=N.pts;if(A!==null){let M=g[k-1];M.duration=Math.round((Y-A)/c)}else if(s&&e.segmentCodec==="aac"&&(Y=v+E),x=Y,S>0){S+=y;try{_=new Uint8Array(S)}catch(M){this.observer.emit(m.ERROR,m.ERROR,{type:V.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:S,reason:`fail allocating audio mdat ${S}`});return}u||(new DataView(_.buffer).setUint32(0,S),_.set(ge.types.mdat,4))}else return;_.set(K,y);let w=K.byteLength;y+=w,g.push(ca(!0,l,w,0)),A=Y}let b=g.length;if(!b)return;let L=g[g.length-1];v=A-E,this.nextAudioTs=v+c*L.duration;let D=u?new Uint8Array(0):ge.moof(e.sequenceNumber++,x/c,ie({},e,{samples:g}));e.samples=[];let C=(x-E)/a,$=this.nextAudioTs/a,U={data1:D,data2:_,startPTS:C,endPTS:$,startDTS:C,endDTS:$,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,U}};function Pe(r,e){let t;if(e===null)return r;for(e<r?t=-8589934592:t=8589934592;Math.abs(r-e)>4294967296;)r+=t;return r}function Yd(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function _o(r,e,t,s){let i=r.samples.length;if(!i)return;let n=r.inputTimeScale;for(let o=0;o<i;o++){let c=r.samples[o];c.pts=Pe(c.pts-t.baseTime*n/t.timescale,e*n)/n,c.dts=Pe(c.dts-s.baseTime*n/s.timescale,e*n)/n}let a=r.samples;return r.samples=[],{samples:a}}function Po(r,e,t){let s=r.samples.length;if(!s)return;let i=r.inputTimeScale;for(let a=0;a<s;a++){let o=r.samples[a];o.pts=Pe(o.pts-t.baseTime*i/t.timescale,e*i)/i}r.samples.sort((a,o)=>a.pts-o.pts);let n=r.samples;return r.samples=[],{samples:n}}var nn=class extends Re{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:a}=this.initData=Ba(e);if(t)zl(e,t);else{let c=n||a;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}n&&(s=da(n,ne.AUDIO,this)),a&&(i=da(a,ne.VIDEO,this));let o={};n&&a?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,n,a){var o,c;let{initPTS:l,lastEndTime:d}=this,h={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};F(d)||(d=this.lastEndTime=n||0);let u=t.samples;if(!u.length)return h;let g={initPTS:void 0,timescale:void 0,trackId:void 0},f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(u),f=this.initData),!((c=f)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);let p=Ql(u,f,this),y=f.audio?p[f.audio.id]:null,v=f.video?p[f.video.id]:null,E=os(v,1/0),T=os(y,1/0),x=os(v,0,!0),A=os(y,0,!0),_=n,S=0,I=y&&(!v||!l&&T<E||l&&l.trackId===f.audio.id),b=I?y:v;if(b){let N=b.timescale,K=b.start-n*N,Y=I?f.audio.id:f.video.id;_=b.start/N,S=I?A-T:x-E,(a||!l)&&(Wd(l,_,n,S)||N!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${K/N} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${_-n} (${K}/${N}) trackId: ${Y}`),l=null,g.initPTS=K,g.timescale=N,g.trackId=Y)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);l?(g.initPTS=l.baseTime,g.timescale=l.timescale,g.trackId=l.trackId):((!g.timescale||g.trackId===void 0||g.initPTS===void 0)&&(this.warn("Could not set initPTS"),g.initPTS=_,g.timescale=1,g.trackId=-1),this.initPTS=l={baseTime:g.initPTS,timescale:g.timescale,trackId:g.trackId});let L=_-l.baseTime/l.timescale,D=L+S;S>0?this.lastEndTime=D:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let C=!!f.audio,$=!!f.video,H="";C&&(H+="audio"),$&&(H+="video");let U=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),k={data1:u,startPTS:L,startDTS:L,endPTS:D,endDTS:D,type:H,hasAudio:C,hasVideo:$,nb:1,dropped:0,encrypted:U};h.audio=C&&!$?k:void 0,h.video=$?k:void 0;let G=v?.sampleCount;if(G){let N=v.keyFrameIndex,K=N!==-1;k.nb=G,k.dropped=N===0||this.isVideoContiguous?0:K?N:G,k.independent=K,k.firstKeyFrame=N,K&&v.keyFrameStart&&(k.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=K),this.isVideoContiguous||(this.isVideoContiguous=K),k.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${N}/${G} dropped: ${k.dropped} start: ${k.firstKeyFramePTS||"NA"}`)}return h.initSegment=g,h.id3=_o(s,n,l,l),i.samples.length&&(h.text=Po(i,n,l)),h}};function os(r,e,t=!1){return r?.start!==void 0?(r.start+(t?r.duration:0))/r.timescale:e}function Wd(r,e,t,s){if(r===null)return!0;let i=Math.max(s,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>i}function da(r,e,t){let s=r.codec;return s&&s.length>4?s:e===ne.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?As(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}var Xe;try{Xe=self.performance.now.bind(self.performance)}catch{Xe=Date.now}var ys=[{demux:zi,remux:nn},{demux:Ji,remux:Rt},{demux:Wi,remux:Rt},{demux:ji,remux:Rt}];ys.splice(2,0,{demux:qi,remux:Rt});var Ns=class{constructor(e,t,s,i,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=s,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){let n=s.transmuxing;n.executeStart=Xe();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);let{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:u,timeOffset:g,initSegmentChange:f}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:v,duration:E,initSegmentData:T}=c,x=qd(a,t);if(x&&bt(x.method)){let I=this.getDecrypter(),b=Zn(x.method);if(I.isSync()){let L=I.softwareDecrypt(a,x.key.buffer,x.iv.buffer,b);if(s.part>-1){let C=I.flush();L=C&&C.buffer}if(!L)return n.executeEnd=Xe(),pi(s);a=new Uint8Array(L)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(a,x.key.buffer,x.iv.buffer,b).then(L=>{let D=this.push(L,null,s);return this.decryptionPromise=null,D}),this.decryptionPromise}let A=this.needsProbing(d,h);if(A){let I=this.configureTransmuxer(a);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),n.executeEnd=Xe(),pi(s)}(d||h||f||A)&&this.resetInitSegment(T,p,y,E,t),(d||f||A)&&this.resetInitialTimestamp(v),l||this.resetContiguity();let _=this.transmux(a,x,g,u,s);this.asyncResult=zt(_);let S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=Xe(),_}flush(e){let t=e.transmuxing;t.executeStart=Xe();let{decrypter:s,currentTransmuxState:i,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=i;if(s){let h=s.flush();h&&a.push(this.push(h.buffer,null,e))}let{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=Xe();let h=[pi(e)];return this.asyncResult?Promise.resolve(h):h}let d=c.flush(o);return zt(d)?(this.asyncResult=!0,d.then(h=>(this.flushRemux(a,h,e),a))):(this.flushRemux(a,d,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){let{audioTrack:i,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===B.MAIN?"level":"track"} ${s.level}`);let d=this.remuxer.remux(i,n,a,o,l,c,!0,this.id);e.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=Xe()}resetInitialTimestamp(e){let{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,n){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,i,n):a=this.transmuxUnencrypted(e,s,i,n),a}transmuxUnencrypted(e,t,s,i){let{audioTrack:n,videoTrack:a,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,n){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){let{config:t,observer:s,typeSupported:i}=this,n;for(let h=0,u=ys.length;h<u;h++){var a;if((a=ys[h].demux)!=null&&a.probe(e,this.logger)){n=ys[h];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,c=this.remuxer,l=n.remux,d=n.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof d))&&(this.demuxer=new d(s,t,i,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Vt(this.config)),e}};function qd(r,e){let t=null;return r.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var pi=r=>({remuxResult:{},chunkMeta:r});function zt(r){return"then"in r&&r.then instanceof Function}var rn=class{constructor(e,t,s,i,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=s,this.duration=i,this.defaultInitPts=n||null}},an=class{constructor(e,t,s,i,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=s,this.trackSwitch=i,this.timeOffset=n,this.initSegmentChange=a}},ha=0,Bs=class{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=ha++,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=c=>{let l=c.data,d=this.hls;if(!(!d||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.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(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{d.logger[l.data.logType]&&d.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,d.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;let l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;let a=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new er,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);let o=_r(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let c=this.hls.logger;if(n.workerPath||ld()){try{n.workerPath?(c.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=dd(n.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=cd());let{worker:d}=this.workerContext;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:re(n)})}catch(d){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.terminateWorker(),this.error=null,this.transmuxer=new Ns(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Ns(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=ha++;let t=this.hls.config,s=_r(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:re(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),hd(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,s,i,n,a,o,c,l,d){var h,u;l.transmuxing.start=self.performance.now();let{instanceNo:g,transmuxer:f}=this,p=a?a.start:n.start,y=n.decryptdata,v=this.frag,E=!(v&&n.cc===v.cc),T=!(v&&l.level===v.level),x=v?l.sn-v.sn:-1,A=this.part?l.part-this.part.index:-1,_=x===0&&l.id>1&&l.id===v?.stats.chunkCount,S=!T&&(x===1||x===0&&(A===1||_&&A<=0)),I=self.performance.now();(T||x||n.stats.parsing.start===0)&&(n.stats.parsing.start=I),a&&(A||!S)&&(a.stats.parsing.start=I);let b=!(v&&((h=n.initSegment)==null?void 0:h.url)===((u=v.initSegment)==null?void 0:u.url)),L=new an(E,S,c,T,p,b);if(!S||E||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===B.MAIN?"level":"track"}: ${l.level} id: ${l.id}
17
17
  discontinuity: ${E}
18
18
  trackSwitch: ${T}
19
- contiguous: ${A}
19
+ contiguous: ${S}
20
20
  accurateTimeOffset: ${c}
21
21
  timeOffset: ${p}
22
- initSegmentChange: ${b}`);let P=new ir(s,i,t,o,h);this.configureTransmuxer(P)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(g){let P=g.push(e,y,l,L);jt(P)?P.then(M=>{this.handleTransmuxComplete(M)}).catch(M=>{this.transmuxerError(M,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){let i=s.flush(e);jt(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},ca=100,nr=class extends Ht{constructor(e,t,s){super(e,t,s,"audio-stream-controller",N.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:a}){if(s===N.MAIN){let o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:r,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${i/r} (${i}/${r}) trackId: ${a}`),this.mainAnchor=t,this.state===D.WAITING_INIT_PTS){let l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===D.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;let i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;let r=(i||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),c=Wa(a,r,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===D.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=D.STOPPED;return}let s=this.lastCurrentTime;this.stopLoad(),this.setInterval(ca),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=D.IDLE):this.state=D.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case D.IDLE:this.doTickIdle();break;case D.WAITING_TRACK:{let{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=D.WAITING_INIT_PTS}break}case D.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case D.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:s,cache:i,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=D.FRAG_LOADING;let o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=D.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)}doTickIdle(){var e;let{hls:t,levels:s,media:i,trackId:r}=this,a=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[r]))return;let o=s[r],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=D.WAITING_TRACK,this.startFragRequested=!1;return}let l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,re.AUDIO,N.AUDIO));let h=this.getFwdBufferInfo(l,N.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=D.ENDED;return}let d=h.len,u=t.maxBufferLength,f=c.fragments,g=f[0].start,p=this.getLoadPosition(),y=this.flushing?p:h.end;if(this.switchingTrack&&i){let T=p;c.PTSKnown&&T<g&&(h.end>g||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}if(d>=u&&!this.switchingTrack&&y<f[f.length-1].start)return;let v=this.getNextFragment(y,c);if(v&&this.isLoopLoading(v,y)&&(v=this.getNextFragmentLoopLoading(v,c,h,N.MAIN,u)),!v){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,u,v))return;let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&ce(v)&&!v.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===de.OK&&(this.mainFragLoading=E=null),E&&ce(E))){if(v.start>E.end){let S=this.fragmentTracker.getFragAtPos(y,N.MAIN);S&&S.end>E.end&&(E=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(v.start>E.end)return}this.loadFragment(v,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new ft(s))}onAudioTrackSwitching(e,t){let s=!!t.url;this.trackId=t.id;let{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==D.STOPPED&&(this.setInterval(ca),this.state=D.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;let{levels:i}=this,{details:r,id:a,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${o}"`);return}let l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==D.STOPPED&&(this.state=D.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${c.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);let h=i[a],d=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var u;d=this.alignPlaylists(r,h.details,(u=this.levelLastLoaded)==null?void 0:u.details)}r.alignedSliding||(lo(r,l),r.alignedSliding||Cs(r,l),d=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===D.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=D.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:i,payload:r}=e,{config:a,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}let h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}let d=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new Ns(this.hls,N.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[s.cc],g=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){let y=i?i.index:-1,v=y!==-1,E=new Vt(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,v);u.push(r,g,d,"",s,i,h.totalduration,!1,E,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);let{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new ws,complete:!1};p.push(new Uint8Array(r)),this.state!==D.STOPPED&&(this.state=D.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===N.MAIN&&ce(t.frag)&&(this.mainFragLoading=t,this.state===D.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:s,part:i}=t;if(s.type!==N.AUDIO){!this.audioOnly&&s.type===N.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(ce(s)){this.fragPrevious=s;let r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,te({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=D.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(N.AUDIO,t);break;case I.AUDIO_TRACK_LOAD_ERROR:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===D.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Q.AUDIO_TRACK&&(this.state=D.IDLE);break;case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case I.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==re.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==re.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===D.ENDED&&(this.state=D.IDLE);let s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,N.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:c,part:l,level:h}=o,{details:d}=h,{audio:u,text:f,id3:g,initSegment:p}=r;if(this.fragContextChanged(c)||!d){this.fragmentTracker.removeFragment(c);return}if(this.state=D.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){let y=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(h,p.tracks,y,a),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(u){let{startPTS:y,endPTS:v,startDTS:E,endDTS:T}=u;l&&(l.elementaryStreams[re.AUDIO]={startPTS:y,endPTS:v,startDTS:E,endDTS:T}),c.setElementaryStreamInfo(re.AUDIO,y,v,E,T),this.bufferFragmentData(u,c,l,a)}if(g!=null&&(t=g.samples)!=null&&t.length){let y=ie({id:s,frag:c,details:d},g);i.trigger(m.FRAG_PARSING_METADATA,y)}if(f){let y=ie({id:s,frag:c,details:d},f);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==D.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let r=t.audio;r.id=N.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(m.BUFFER_CODECS,t);let o=r.initSegment;if(o!=null&&o.byteLength){let c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){let i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===de.NOT_LOADED||i===de.PARTIAL){var r;if(!ce(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.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=D.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Cs(t.details,a)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;dt({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o},e,ct)||(Is(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.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,te({},e))}},zt=class extends Ie{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){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,s){let i=t?.renditionReports;if(i){let r=-1;for(let a=0;a<i.length;a++){let o=i[a],c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){r=a;break}else c===e.substring(0,c.length)&&(r=a)}if(r!==-1){let a=i[r],o=parseInt(a["LAST-MSN"])||t.lastPartSn,c=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let h=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&h>t.partTarget&&(c+=1)}let l=s&&bn(s);return new Ls(o,c>=0?c:void 0,l)}}}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(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){let{details:i,stats:r}=t,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;i.advancedDateTime=Date.now()-o;let c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){let h=Math.max(c||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(d=>{d.setStart(d.playlistOffset+h)})}if(i.live||s!=null&&s.live){let h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){Hc(s,i,this);let E=i.playlistParsingError;if(E){this.warn(E);let T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var l;let{networkDetails:S}=t;T.trigger(m.ERROR,{type:K.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:E,reason:E.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:S,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);let d=this.hls.mainForwardBufferInfo,u=d?d.end-d.len:0,f=(i.edge-u)*1e3,g=io(i,f);if(i.requestScheduled+g<a?i.requestScheduled=a:i.requestScheduled+=g,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let p,y,v;if(i.canBlockReload&&i.endSN&&i.advanced){let E=this.hls.config.lowLatencyMode,T=i.lastPartSn,S=i.endSN,x=i.lastPartIndex,_=x!==-1,A=T===S;_?A?(y=S+1,v=E?0:x):(y=T,v=E?x+1:i.maxPartIndex):y=S+1;let R=i.age,b=R+i.ageHeader,L=Math.min(b-i.partTarget,i.targetduration*1.5);if(L>0){if(b>i.targetduration*3)this.log(`Playlist last advanced ${R.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&b-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${L} with playlist age: ${i.age}`),L=0;else{let P=Math.floor(L/i.targetduration);if(y+=P,v!==void 0){let M=Math.round(L%i.targetduration/i.partTarget);v+=M}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${L} skip sn ${P} to part ${v}`)}i.tuneInGoal=L}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v),E||!A){i.requestScheduled=a,this.loadingPlaylist(h,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(h,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){let i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}let r=self.performance.now(),a=i.requestScheduled;if(r>=a){this.loadingPlaylist(e,t);return}let o=a-r;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,s,i){let r=bn(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=gs.No),new Ls(s,i,r)}checkRetry(e){let t=e.details,s=bs(e),i=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===ge.RetryRequest||!i.resolved&&r===ge.SendAlternateToPenaltyBox);if(c){var l;if(a>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let h=zr(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return c}};function Ro(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!Xt(n[t].attrs,e[t].attrs))return!1;return!0}function Xt(n,e,t){let s=n["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>n[i]!==e[i])}function ar(n,e){return e.label.toLowerCase()===n.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(n.lang||"").toLowerCase())}var or=class extends zt{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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.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:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.audioGroups||null,i=this.groupIds,r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(u=>!s||s.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,f)=>{u.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let c=this.hls.config.audioPreference;if(!r&&c){let u=He(c,o,ct);if(u>-1)r=o[u];else{let f=He(c,this.tracks);r=this.tracks[f]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));let h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,h);let d=this.trackId;if(l!==-1&&d===-1)this.setAudioTrack(l);else if(o.length&&d===-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(m.ERROR,{type:K.MEDIA_ERROR,details:I.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(e,t){t.fatal||!t.context||t.context.type===Q.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){let i=this.currentTrack;if(i&&dt(e,i,ct))return i;let r=He(e,this.tracksInGroup,ct);if(r>-1){let a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(i){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=Ec(e,t.levels,s,a,ct);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=He(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,te({},i)),r))return;let a=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let s=0;s<t.length;s++){let i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||dt(e,i,ct)))return s}if(e){let{name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){let h=t[l];if(dt({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:c},h,ct))return l}for(let l=0;l<t.length;l++){let h=t[l];if(Xt(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){let h=t[l];if(Xt(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Is(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}},lr=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;let i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;let a=(s=this.tracks[e])==null?void 0:s.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: ${b}`);let D=new rn(s,i,t,o,d);this.configureTransmuxer(D)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(f){let D=f.push(e,y,l,L);zt(D)?D.then(C=>{this.handleTransmuxComplete(C)}).catch(C=>{this.transmuxerError(C,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(D)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){let i=s.flush(e);zt(i)?i.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},ua=100,on=class extends Yt{constructor(e,t,s){super(e,t,s,"audio-stream-controller",B.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:n,trackId:a}){if(s===B.MAIN){let o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${i/n} (${i}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===P.WAITING_INIT_PTS){let l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;let i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;let n=(i||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),c=za(a,n,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=P.STOPPED;return}let s=this.lastCurrentTime;this.stopLoad(),this.setInterval(ua),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=P.IDLE):this.state=P.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{let{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:s,cache:i,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;let o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),n&&super._handleFragmentLoadComplete(c)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=P.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)}doTickIdle(){var e;let{hls:t,levels:s,media:i,trackId:n}=this,a=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[n]))return;let o=s[n],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}let l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ne.AUDIO,B.AUDIO));let d=this.getFwdBufferInfo(l,B.AUDIO);if(d===null)return;if(!this.switchingTrack&&this._streamEnded(d,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}let h=d.len,u=t.maxBufferLength,g=c.fragments,f=g[0].start,p=this.getLoadPosition(),y=this.flushing?p:d.end;if(this.switchingTrack&&i){let T=p;c.PTSKnown&&T<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(h>=u&&!this.switchingTrack&&y<g[g.length-1].start)return;let v=this.getNextFragment(y,c);if(v&&this.isLoopLoading(v,y)&&(v=this.getNextFragmentLoopLoading(v,c,d,B.MAIN,u)),!v){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(d,u,v))return;let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&de(v)&&!v.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===fe.OK&&(this.mainFragLoading=E=null),E&&de(E))){if(v.start>E.end){let x=this.fragmentTracker.getFragAtPos(y,B.MAIN);x&&x.end>E.end&&(E=x,this.mainFragLoading={frag:x,targetBufferTime:null})}if(v.start>E.end)return}this.loadFragment(v,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new gt(s))}onAudioTrackSwitching(e,t){let s=!!t.url;this.trackId=t.id;let{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==P.STOPPED&&(this.setInterval(ua),this.state=P.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;let{levels:i}=this,{details:n,id:a,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${o}"`);return}let l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${c.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let d=i[a],h=0;if(n.live||(s=d.details)!=null&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(d.details){var u;h=this.alignPlaylists(n,d.details,(u=this.levelLastLoaded)==null?void 0:u.details)}n.alignedSliding||(uo(n,l),n.alignedSliding||ws(n,l),h=n.fragmentStart)}d.details=n,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:i,payload:n}=e,{config:a,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}let d=l.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}let h=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new Bs(this.hls,B.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let g=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){let y=i?i.index:-1,v=y!==-1,E=new Ht(s.level,s.sn,s.stats.chunkCount,n.byteLength,y,v);u.push(n,f,h,"",s,i,d.totalduration,!1,E,g)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${d.startSN} ,${d.endSN}],track ${o}`);let{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Ms,complete:!1};p.push(new Uint8Array(n)),this.state!==P.STOPPED&&(this.state=P.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===B.MAIN&&de(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:s,part:i}=t;if(s.type!==B.AUDIO){!this.audioOnly&&s.type===B.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(de(s)){this.fragPrevious=s;let n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,te({},n)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Q.AUDIO_TRACK&&(this.state=P.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ne.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ne.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);let s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,B.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let s="audio",{hls:i}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:c,part:l,level:d}=o,{details:h}=d,{audio:u,text:g,id3:f,initSegment:p}=n;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=P.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){let y=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(d,p.tracks,y,a),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(u){let{startPTS:y,endPTS:v,startDTS:E,endDTS:T}=u;l&&(l.elementaryStreams[ne.AUDIO]={startPTS:y,endPTS:v,startDTS:E,endDTS:T}),c.setElementaryStreamInfo(ne.AUDIO,y,v,E,T),this.bufferFragmentData(u,c,l,a)}if(f!=null&&(t=f.samples)!=null&&t.length){let y=ie({id:s,frag:c,details:h},f);i.trigger(m.FRAG_PARSING_METADATA,y)}if(g){let y=ie({id:s,frag:c,details:h},g);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=B.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(m.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){let i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===fe.NOT_LOADED||i===fe.PARTIAL){var n;if(!de(e))this._loadInitSegment(e,t);else 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=P.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&ws(t.details,a)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:s,assocLang:i,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;ut({name:t,lang:s,assocLang:i,characteristics:n,audioCodec:a,channels:o},e,dt)||(bs(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.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,te({},e))}},Xt=class extends Re{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){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,s){let i=t?.renditionReports;if(i){let n=-1;for(let a=0;a<i.length;a++){let o=i[a],c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){n=a;break}else c===e.substring(0,c.length)&&(n=a)}if(n!==-1){let a=i[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn,c=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let d=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&d>t.partTarget&&(c+=1)}let l=s&&Pr(s);return new Is(o,c>=0?c:void 0,l)}}}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(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){let{details:i,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;i.advancedDateTime=Date.now()-o;let c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){let d=Math.max(c||0,0);i.appliedTimelineOffset=d,i.fragments.forEach(h=>{h.setStart(h.playlistOffset+d)})}if(i.live||s!=null&&s.live){let d="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){Qc(s,i,this);let E=i.playlistParsingError;if(E){this.warn(E);let T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var l;let{networkDetails:x}=t;T.trigger(m.ERROR,{type:V.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:E,reason:E.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:x,stats:n});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=n.loading.start);let h=this.hls.mainForwardBufferInfo,u=h?h.end-h.len:0,g=(i.edge-u)*1e3,f=ao(i,g);if(i.requestScheduled+f<a?i.requestScheduled=a:i.requestScheduled+=f,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let p,y,v;if(i.canBlockReload&&i.endSN&&i.advanced){let E=this.hls.config.lowLatencyMode,T=i.lastPartSn,x=i.endSN,A=i.lastPartIndex,_=A!==-1,S=T===x;_?S?(y=x+1,v=E?0:A):(y=T,v=E?A+1:i.maxPartIndex):y=x+1;let I=i.age,b=I+i.ageHeader,L=Math.min(b-i.partTarget,i.targetduration*1.5);if(L>0){if(b>i.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&b-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${L} with playlist age: ${i.age}`),L=0;else{let D=Math.floor(L/i.targetduration);if(y+=D,v!==void 0){let C=Math.round(L%i.targetduration/i.partTarget);v+=C}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${L} skip sn ${D} to part ${v}`)}i.tuneInGoal=L}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v),E||!S){i.requestScheduled=a,this.loadingPlaylist(d,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(d,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){let i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=i.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,s,i){let n=Pr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,n=ps.No),new Is(s,i,n)}checkRetry(e){let t=e.details,s=Rs(e),i=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=i||{},c=!!i&&!!o&&(n===me.RetryRequest||!i.resolved&&n===me.SendAlternateToPenaltyBox);if(c){var l;if(a>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let d=Qn(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,i.resolved=!0}return c}};function Do(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Qt(r[t].attrs,e[t].attrs))return!1;return!0}function Qt(r,e,t){let s=r["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>r[i]!==e[i])}function ln(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}var cn=class extends Xt{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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.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:s,groupId:i,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.audioGroups||null,i=this.groupIds,n=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(u=>!s||s.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,g)=>{u.id=g});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let c=this.hls.config.audioPreference;if(!n&&c){let u=We(c,o,dt);if(u>-1)n=o[u];else{let g=We(c,this.tracks);n=this.tracks[g]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,d);let h=this.trackId;if(l!==-1&&h===-1)this.setAudioTrack(l);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(m.ERROR,{type:V.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(e,t){t.fatal||!t.context||t.context.type===Q.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){let i=this.currentTrack;if(i&&ut(e,i,dt))return i;let n=We(e,this.tracksInGroup,dt);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(i){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=bc(e,t.levels,s,a,dt);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=We(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,i=t[e],n=i.details&&!i.details.live;if(e===this.trackId&&i===s&&n||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,te({},i)),n))return;let a=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let s=0;s<t.length;s++){let i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||ut(e,i,dt)))return s}if(e){let{name:s,lang:i,assocLang:n,characteristics:a,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){let d=t[l];if(ut({name:s,lang:i,assocLang:n,characteristics:a,audioCodec:o,channels:c},d,dt))return l}for(let l=0;l<t.length;l++){let d=t[l];if(Qt(e.attrs,d.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){let d=t[l];if(Qt(e.attrs,d.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&bs(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=e.id,i=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${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(m.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:i,deliveryDirectives:t||null,track:e})}},dn=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;let i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let i=t[0];try{i.execute()}catch(n){var s;if(i.onError(n),this.queues===null||this.tracks===null)return;let a=(s=this.tracks[e])==null?void 0:s.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,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}},ha=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,_o="HlsJsTrackRemovedError",cr=class extends Error{constructor(e){super(e),this.name=_o}},hr=class extends Ie{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{let{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=wl(st(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){let{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this),e.off(m.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let s={};if(this.operationQueue){let r=this.isUpdating();r||this.operationQueue.removeBlockers();let a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?ie(s,i.tracks):this.sourceBuffers.forEach(r=>{let[a]=r;a&&(s[a]=ie({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){let e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){let s=this.media=t.media;this.transferData=this.overrides=void 0;let i=st(this.appendSource);if(i){let r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),r)this._objectUrl=s.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");let c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&a instanceof c,da(s),Gh(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&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
- required tracks: ${ne(s,(c,l)=>c==="initSegment"?void 0:l)};
27
- transfer tracks: ${ne(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!Da(i,s)){t.mediaSource=null,t.tracks=void 0;let c=e.currentTime,l=this.details,h=Math.max(c,l?.fragments[0].start||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{let l=c,h=i[l];if(h){let d=h.buffer;if(d){let u=this.fragmentTracker,f=h.id;if(u.hasFragments(f)||u.hasParts(f)){let y=q.getBuffered(d);u.detectEvictedFragments(l,y,f,null,!0)}let g=mi(l),p=[l,d];this.sourceBuffers[g]=p,d.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),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 s=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:i,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=r.readyState==="open";try{let c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(i.removeAttribute("src"),this.appendSource&&da(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[mi(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new lr(this.tracks)}onBufferCodecs(e,t){var s;let i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;let d=t[c],{id:u,codec:f,levelCodec:g,container:p,metadata:y,supplemental:v}=d,E=i[c],T=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],S=T!=null&&T.buffer?T:E,x=S?.pendingCodec||S?.codec,_=S?.levelCodec;E||(E=i[c]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:g,metadata:y,id:u});let A=fs(x,_),R=A?.replace(ha,"$1"),b=fs(f,g),L=(h=b)==null?void 0:h.replace(ha,"$1");b&&A&&R!==L&&(c.slice(0,5)==="audio"&&(b=xs(b,this.appendSource)),this.log(`switching codec ${x} to ${b}`),b!==(E.pendingCodec||E.codec)&&(E.pendingCodec=b),E.container=p,this.appendChangeType(c,p,b))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){let i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,N.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o;let c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&q.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,N.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:s}=this,{data:i,type:r,parent:a,frag:o,part:c,chunkMeta:l,offset:h}=t,d=l.buffering[r],{sn:u,cc:f}=o,g=self.performance.now();d.start=g;let p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=g),y&&y.start===0&&(y.start=g);let v=s.audio,E=!1;r==="audio"&&v?.container==="audio/mpeg"&&(E=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);let T=s.video,S=T?.buffer;if(S&&u!=="initSegment"){let A=c||o,R=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){let L=A.start+A.duration*.05,P=S.buffered,M=this.currentOp("video");!P.length&&!M?this.blockAudio(A):!M&&!q.isBuffered(S,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(A)}else if(r==="video"){let b=A.end;if(R){let L=R.frag.start;(b>L||b<this.lastVideoAppendEnd||q.isBuffered(S,L))&&this.unblockAudio()}this.lastVideoAppendEnd=b}}let x=(c||o).start,_={label:`append-${r}`,execute:()=>{var A;d.executeStart=self.performance.now();let R=(A=this.tracks[r])==null?void 0:A.buffer;R&&(E?this.updateTimestampOffset(R,x,.1,r,u,f):h!==void 0&&O(h)&&this.updateTimestampOffset(R,h,1e-6,r,u,f)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{let A=self.performance.now();d.executeEnd=d.end=A,p.first===0&&(p.first=A),y&&y.first===0&&(y.first=A);let R={};this.sourceBuffers.forEach(([b,L])=>{b&&(R[b]=q.getBuffered(L))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:r,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:R})},onError:A=>{var R;let b={type:K.MEDIA_ERROR,parent:o.type,details:I.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:A,err:A,fatal:!1},L=(R=this.media)==null?void 0:R.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)b.details=I.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!L)b.errorAction=Lt(!0);else if(A.name===_o&&this.sourceBufferCount===0)b.errorAction=Lt(!0);else{let P=++this.appendErrors[r];this.warn(`Failed ${P}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${L||"no media error"})`),(P>=this.hls.config.appendErrorMaxRetry||L)&&(b.fatal=!0)}this.hls.trigger(m.ERROR,b)}};this.log(`queuing "${r}" append sn: ${u}${c?" p: "+c.index:""} of ${o.type===N.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(_,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){let{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,r),a)})}onFragParsed(e,t){let{frag:s,part:i}=t,r=[],a=i?i.elementaryStreams:s.elementaryStreams;a[re.AUDIOVIDEO]?r.push("audiovideo"):(a[re.AUDIO]&&r.push("audio"),a[re.VIDEO]&&r.push("video"));let o=()=>{let c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);let l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,r).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;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 i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if(!a||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(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.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===I.BUFFER_APPEND_ERROR&&t.frag){var s;let i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;O(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;let i=e.config,r=s.currentTime,a=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(O(o)&&o>=0){let l=Math.max(o,a),h=Math.floor(r/a)*a-l;this.flushBackBuffer(r,a,h)}let c=i.frontBufferFlushThreshold;if(O(c)&&c>0){let l=Math.max(i.maxBufferLength,c),h=Math.max(l,a),d=Math.floor(r/a)*a+h;this.flushFrontBuffer(r,a,d)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){let o=q.getBuffered(r);if(o.length>0&&s>o.start(0)){var a;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});let c=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){let a=q.getBuffered(r),o=a.length;if(o<2)return;let c=a.start(o-1),l=a.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;let{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;let i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){let l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}let r=(e=this.overrides)==null?void 0:e.duration;if(r)return O(r)?{duration:r}:null;let a=this.media.duration,o=O(s.duration)?s.duration:0;return i>o&&i>a||!O(a)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){let i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(O(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ne(s)}`),this.tracksReady){var i;let r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,s])=>{if(t){let i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.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(m.ERROR,{type:K.MEDIA_ERROR,details:I.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(let r in e){let a=r,o=e[a];if(this.isPending(o)){let c=this.getTrackCodec(o,a),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(a)?" Queued":""} ${ne(o)}`);try{let h=s.addSourceBuffer(l),d=mi(a),u=[a,h];t[d]=u,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:a,mimeType:l,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){let s=e.supplemental,i=e.codec;s&&(t==="video"||t==="audiovideo")&&$t(s,"video")&&(i=ec(i,s));let r=fs(i,e.levelCodec);return r?t.slice(0,5)==="audio"?xs(r,this.appendSource):r:""}trackSourceBuffer(e,t){let s=t.buffer;if(!s)return;let i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,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",(r,a)=>{let o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;let s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;let i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});let r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,a){let o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){let{media:i,mediaSource:r}=this,a=this.tracks[e],o=a?.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let c=O(i.duration)?i.duration:1/0,l=O(r.duration)?r.duration:1/0,h=Math.max(0,t),d=Math.min(s,c,l);d>h&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),o.remove(h,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let s=this.tracks[t],i=s?.buffer;if(!i)throw new cr(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}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}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:s}=this,i=t.map(a=>this.appendBlocker(a));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;let i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){let i=this.tracks[e];if(!i)return;let r=i.buffer;if(!r)return;let a=s.bind(this,e);i.listeners.push({event:t,listener:a}),r.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}};function da(n){let e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function Gh(n,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}function mi(n){return n==="audio"?1:0}var dr=class n{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&O(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,n.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;let i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0,r=e.length-1,a=Math.max(t,s);for(let o=0;o<e.length;o+=1){let c=e[o];if((c.width>=a||c.height>=a)&&i(c,e[o+1])){r=o;break}}return r}},Kh={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Ae=Kh,Vh={HLS:"h"},Hh=Vh,Xe=class n{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof n?s:new n(s))),this.value=e,this.params=t}},Yh="Dict";function Wh(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function qh(n,e,t,s){return new Error(`failed to ${n} "${Wh(e)}" as ${t}`,{cause:s})}function Ye(n,e,t){return qh("serialize",n,e,t)}var Bs=class{constructor(e){this.description=e}},ua="Bare Item",jh="Boolean";function zh(n){if(typeof n!="boolean")throw Ye(n,jh);return n?"?1":"?0"}function Xh(n){return btoa(String.fromCharCode(...n))}var Qh="Byte Sequence";function Zh(n){if(ArrayBuffer.isView(n)===!1)throw Ye(n,Qh);return`:${Xh(n)}:`}var Jh="Integer";function ed(n){return n<-999999999999999||999999999999999<n}function Do(n){if(ed(n))throw Ye(n,Jh);return n.toString()}function td(n){return`@${Do(n.getTime()/1e3)}`}function Po(n,e){if(n<0)return-Po(-n,e);let t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){let i=Math.floor(n*t);return(i%2===0?i:i+1)/t}else return Math.round(n*t)/t}var sd="Decimal";function id(n){let e=Po(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ye(n,sd);let t=e.toString();return t.includes(".")?t:`${t}.0`}var rd="String",nd=/[\x00-\x1f\x7f]+/;function ad(n){if(nd.test(n))throw Ye(n,rd);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function od(n){return n.description||n.toString().slice(7,-1)}var ld="Token";function fa(n){let e=od(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ye(e,ld);return e}function ur(n){switch(typeof n){case"number":if(!O(n))throw Ye(n,ua);return Number.isInteger(n)?Do(n):id(n);case"string":return ad(n);case"symbol":return fa(n);case"boolean":return zh(n);case"object":if(n instanceof Date)return td(n);if(n instanceof Uint8Array)return Zh(n);if(n instanceof Bs)return fa(n);default:throw Ye(n,ua)}}var cd="Key";function fr(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw Ye(n,cd);return n}function nn(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${fr(e)}`:`;${fr(e)}=${ur(t)}`).join("")}function ko(n){return n instanceof Xe?`${ur(n.value)}${nn(n.params)}`:ur(n)}function hd(n){return`(${n.value.map(ko).join(" ")})${nn(n.params)}`}function dd(n,e={whitespace:!0}){if(typeof n!="object"||n==null)throw Ye(n,Yh);let t=n instanceof Map?n.entries():Object.entries(n),s=e?.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Xe||(r=new Xe(r));let a=fr(i);return r.value===!0?a+=nn(r.params):(a+="=",Array.isArray(r.value)?a+=hd(r):a+=ko(r)),a}).join(`,${s}`)}function Co(n,e){return dd(n,e)}var Ge="CMCD-Object",le="CMCD-Request",ot="CMCD-Session",Je="CMCD-Status",ud={br:Ge,ab:Ge,d:Ge,ot:Ge,tb:Ge,tpb:Ge,lb:Ge,tab:Ge,lab:Ge,url:Ge,pb:le,bl:le,tbl:le,dl:le,ltc:le,mtp:le,nor:le,nrr:le,rc:le,sn:le,sta:le,su:le,ttfb:le,ttfbb:le,ttlb:le,cmsdd:le,cmsds:le,smrt:le,df:le,cs:le,ts:le,cid:ot,pr:ot,sf:ot,sid:ot,st:ot,v:ot,msd:ot,bs:Je,bsd:Je,cdn:Je,rtp:Je,bg:Je,pt:Je,ec:Je,e:Je},fd={REQUEST:le};function gd(n){return Object.keys(n).reduce((e,t)=>{var s;return(s=n[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function md(n,e){let t={};if(!n)return t;let s=Object.keys(n),i=e?gd(e):{};return s.reduce((r,a)=>{var o;let c=ud[a]||i[a]||fd.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[a]=n[a],r},t)}function pd(n){return["ot","sf","st","e","sta"].includes(n)}function yd(n){return typeof n=="number"?O(n):n!=null&&n!==""&&n!==!1}var wo="event";function vd(n,e){let t=new URL(n),s=new URL(e);if(t.origin!==s.origin)return n;let i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}var ys=n=>Math.round(n),gr=(n,e)=>Array.isArray(n)?n.map(t=>gr(t,e)):n instanceof Xe&&typeof n.value=="string"?new Xe(gr(n.value,e),n.params):(e.baseUrl&&(n=vd(n,e.baseUrl)),e.version===1?encodeURIComponent(n):n),os=n=>ys(n/100)*100,Ed=(n,e)=>{let t=n;return e.version>=2&&(n instanceof Xe&&typeof n.value=="string"?t=new Xe([n]):typeof n=="string"&&(t=[n])),gr(t,e)},Td={br:ys,d:ys,bl:os,dl:os,mtp:os,nor:Ed,rtp:os,tb:ys},Mo="request",Oo="response",an=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Sd=["e"],xd=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function js(n){return xd.test(n)}function Ad(n){return an.includes(n)||Sd.includes(n)||js(n)}var Fo=["d","dl","nor","ot","rtp","su"];function Ld(n){return an.includes(n)||Fo.includes(n)||js(n)}var Id=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function bd(n){return an.includes(n)||Fo.includes(n)||Id.includes(n)||js(n)}var Rd=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function _d(n){return Rd.includes(n)||js(n)}var Dd={[Oo]:bd,[wo]:Ad,[Mo]:Ld};function No(n,e={}){let t={};if(n==null||typeof n!="object")return t;let s=e.version||n.v||1,i=e.reportingMode||Mo,r=s===1?_d:Dd[i],a=Object.keys(n).filter(r),o=e.filter;typeof o=="function"&&(a=a.filter(o));let c=i===Oo||i===wo;c&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");let l=ie({},Td,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return a.sort().forEach(d=>{let u=n[d],f=l[d];if(typeof f=="function"&&(u=f(u,h)),d==="v"){if(s===1)return;u=s}d=="pr"&&u===1||(c&&d==="ts"&&!O(u)&&(u=Date.now()),yd(u)&&(pd(d)&&typeof u=="string"&&(u=new Bs(u)),t[d]=u))}),t}function Pd(n,e={}){let t={};if(!n)return t;let s=No(n,e),i=md(s,e?.customHeaderMap);return Object.entries(i).reduce((r,[a,o])=>{let c=Co(o,{whitespace:!1});return c&&(r[a]=c),r},t)}function kd(n,e,t){return ie(n,Pd(e,t))}var Cd="CMCD";function wd(n,e={}){return n?Co(No(n,e),{whitespace:!1}):""}function Md(n,e={}){if(!n)return"";let t=wd(n,e);return encodeURIComponent(t)}function Od(n,e={}){if(!n)return"";let t=Md(n,e);return`${Cd}=${t}`}var ga=/CMCD=[^&#]+/;function Fd(n,e,t){let s=Od(e,t);if(!s)return n;if(ga.test(n))return n.replace(ga,s);let i=n.includes("?")?"&":"?";return`${n}${i}${s}`}var mr=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Ae.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{let{frag:r,part:a}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(a||r).duration*1e3,ot:c};(c===Ae.VIDEO||c===Ae.AUDIO||c==Ae.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));let h=a?this.getNextPart(a):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;let t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Hh.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ie(t,this.createData());let s=t.ot===Ae.INIT||t.ot===Ae.VIDEO||t.ot===Ae.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((a,o)=>(i.includes(o)&&(a[o]=t[o]),a),{}));let r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),kd(e.headers,t,r)):e.url=Fd(e.url,t,r)}getNextFrag(e){var t;let s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){let i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;let{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){let{sn:a}=i;for(let o=r.length-1;o>=0;o--){let c=r[o];if(c.index===s&&c.fragment.sn===a)return r[o+1]}}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return Ae.TIMED_TEXT;if(e.sn==="initSegment")return Ae.INIT;if(t==="audio")return Ae.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ae.VIDEO:Ae.MUXED}getTopBandwidth(e){let t=0,s,i=this.hls;if(e===Ae.AUDIO)s=i.audioTracks;else{let r=i.maxAutoLevel,a=r>-1?r+1:i.levels.length;s=i.levels.slice(0,a)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,s=e===Ae.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}},Nd=3e5,pr=class extends Ie{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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:s}=t;if(s?.action===ge.SendAlternateToPenaltyBox&&s.flags===Re.MoveAllAlternatesMatchingHost){let i=this.levels,r=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:c,type:l}=t.context;o&&i?a=this.getPathwayForGroupId(o,l,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a),t.details===I.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${ne(r)} penalized: ${ne(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}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,s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Nd&&delete s[r]});for(let r=0;r<e.length;r++){let a=e[r];if(a in s)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,ao(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});let l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){let i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===Q.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===Q.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){let t=this.levels;if(!t)return;let s={},i={};e.forEach(r=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===a))return;let l=this.getLevelsForPathway(o).map(h=>{let d=new ae(h.attrs);d["PATHWAY-ID"]=a;let u=d.AUDIO&&`${d.AUDIO}_clone_${a}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;u&&(s[d.AUDIO]=u,d.AUDIO=u),f&&(i[d.SUBTITLES]=f,d.SUBTITLES=f);let g=Bo(h.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new ft({attrs:d,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)p.addGroupId("audio",`${h.audioGroups[y]}_clone_${a}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)p.addGroupId("text",`${h.subtitleGroups[y]}_clone_${a}`);return p});t.push(...l),ma(this.audioTracks,s,c,a),ma(this.subtitleTracks,i,c,a)})}loadSteeringManifest(e){let t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){let h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}let r={responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},c={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,d,u,f)=>{this.log(`Loaded steering manifest: "${i}"`);let g=h.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":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=g;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||u.url),y&&this.clonePathways(y);let E={steeringManifest:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,E),v&&this.updatePathwayPriority(v)},onError:(h,d,u,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${d.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){let p=this.loader;if(typeof p?.getResponseHeader=="function"){let y=p.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,g)},onTimeout:(h,d,u)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;let i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function ma(n,e,t,s){n&&Object.keys(e).forEach(i=>{let r=n.filter(a=>a.groupId===i).map(a=>{let o=ie({},a);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=Bo(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Bo(n,e,t,s){let{HOST:i,PARAMS:r,[t]:a}=s,o;e&&(o=a?.[e],o&&(n=o));let c=new self.URL(n);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}var Us=class n extends Ie{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._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=n.CDMCleanupPromise?[n.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{let{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Mt(this.config));let o=a.map(oi).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o=ms(a);if(s!=="sinf"||o!==oe.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{let f=he(new Uint8Array(i)),g=Qr(JSON.parse(f).sinf),p=Na(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${r} Failed to parse sinf: ${f}`);return}let l=ye(c),{keyIdToKeySessionPromise:h,mediaKeySessions:d}=this,u=h[l];for(let f=0;f<d.length;f++){let g=d[f],p=g.decryptdata;if(!p.keyId)continue;let y=ye(p.keyId);if(Ps(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(u=h[y],!u)continue;if(p.pssh)break;delete h[y],p.pssh=new Uint8Array(i),p.keyId=c,u=h[l]=u.then(()=>this.generateRequestWithPreferredKeySession(g,s,i,"encrypted-event-key-match")),u.catch(v=>this.handleError(v));break}}u||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${d.length}.`))}).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=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t?.[e];if(i)return i.licenseUrl;if(e===oe.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,s=(a,o,c)=>!!a&&c.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),r=t.map(a=>a.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{let c=l=>{let h=l.shift();this.getMediaKeysPromise(h,i,r).then(d=>a({keySystem:h,mediaKeys:d})).catch(d=>{l.length?c(l):d instanceof Se?o(d):o(new Se({type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};c(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Za===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;let r=Oc(e,t,s,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ne(r)}`),o=this.requestMediaKeySystemAccess(e,r);let c=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);let h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let d=c.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(u,e,f):u)));return d.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),d})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${ye(e.keyId||[])} keyUri: ${e.uri}`);let i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let s=this.createMediaKeySessionContext(e),i=ls(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){let s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${ye(e.decryptdata.keyId||[])}
28
- } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>oi(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{let r=oi(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}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=Mt(this.config),s=e.map(ms).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){let i=Bd(e,t[s]);if(i)return i}}loadKey(e){let t=e.keyInfo.decryptdata,s=ls(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){let o=pa(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}let r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let a=this.keyIdToKeySessionPromise[s];if(!a){let o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{let l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Se){let c=te({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);let l=new Se(c,o.message);this.handleError(l,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Se){t&&(e.data.frag=t);let s=e.data.decryptdata;this.error(`${e.message}${s?` (${ye(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=ls(e),s=this.keyIdToKeySessionPromise[t];if(!s){let i=ms(e.keyFormat),r=i?[i]:Mt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Mt(this.config)),e.length===0)throw new Se({type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ne({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,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(r).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;let a=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(a)try{let g=a.call(this.hls,t,s,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,s=g.initData?g.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);let o=ls(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);let l=new Zr,h=e._onmessage=g=>{let p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}let{messageType:y,message:v}=g;this.log(`"${y}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(E=>{l.eventNames().length?l.emit("error",E):this.handleError(E)}):y==="license-release"?e.keySystem===oe.FAIRPLAY&&this.updateKeySession(e,Ki("acknowledged")).then(()=>this.removeSession(e)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${y}"`)},d=(g,p)=>{p.keyStatus=g;let y;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?y=pa(g,p.decryptdata):g==="expired"?y=new Error(`key expired (keyId: ${o})`):g==="released"?y=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},u=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}let y=this.getKeyStatuses(e);if(!Object.keys(y).some(S=>y[S]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${ne(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let E=y[o];if(E)d(E,e);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let x=this.getKeyStatus(e.decryptdata);if(x&&x!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${x} from other session.`),d(x,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),E="internal-error",d(E,e)},1e3)),this.log(`No status for keyId ${o} (${ne(y)}).`)}};xe(e.mediaKeysSession,"message",h),xe(e.mediaKeysSession,"keystatuseschange",u);let f=new Promise((g,p)=>{l.on("error",p),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new Se({type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){let o=i;i=s,s=o}let r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===oe.PLAYREADY&&r.length===16){let o=ye(r);t[o]=s,Xa(r)}let a=ye(r);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){let t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,g,p)=>{a(u.data)},onError:(u,f,g,p)=>{o(new Se({type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:te({url:c.url,data:void 0},u)},`"${e}" certificate request failed (${r}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{o(new Se({type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(u,f,g)=>{o(new Error("aborted"))}};i.load(c,h,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new Se({type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Se({type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){let s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let d=0,u=r.length;d<u;d++){var a,o;h=r[d];let f=(a=h.querySelector("name"))==null?void 0:a.textContent,g=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}let c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Ki(atob(l))}setupLicenseXHR(e,t,s,i){let r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){let s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);let l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,a,e)}catch(h){this.error(h)}i(c)}else{let c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Se({type:K.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==oe.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let s=t.media;this.media=s,xe(s,"encrypted",this.onMediaEncrypted),xe(s,"waitingforkey",this.onWaitingForKey);let i=this.mediaResolved;i?i():this.mediaKeys=s.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._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Dt.clearKeyUriToKeyIdMap();let r=i.length;n.CDMCleanupPromise=Promise.all(i.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:K.OTHER_ERROR,details:I.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(m.ERROR,{type:K.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${ye(i?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));let{drmSystemOptions:o}=this.config;return(Nc(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:K.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:K.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}};Us.CDMCleanupPromise=void 0;function ls(n){if(!n)throw new Error("Could not read keyId of undefined decryptdata");if(n.keyId===null)throw new Error("keyId is null");return ye(n.keyId)}function Bd(n,e){if(n.keyId&&e.mediaKeysSession.keyStatuses.has(n.keyId))return e.mediaKeysSession.keyStatuses.get(n.keyId);if(n.matches(e.decryptdata))return e.keyStatus}var Se=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}};function pa(n,e){let t=n==="output-restricted",s=t?I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:I.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Se({type:K.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${n}"`)}var yr=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(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let s=this.hls.config;if(s.capLevelOnFPSDrop){let i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){let i=performance.now();if(t){if(this.lastTime){let r=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*a/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),c>0&&a>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function Uo(n,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=n,e.dispatchEvent(t)}function $o(n,e){let t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){se.debug(`[texttrack-utils]: ${s}`);try{let i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,n.addCue(i)}catch(i){se.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(n.mode=t)}function xt(n,e){let t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues)for(let s=n.cues.length;s--;)e&&n.cues[s].removeEventListener("enter",e),n.removeCue(n.cues[s]);t==="disabled"&&(n.mode=t)}function vr(n,e,t,s){let i=n.mode;if(i==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){let r=$d(n.cues,e,t);for(let a=0;a<r.length;a++)(!s||s(r[a]))&&n.removeCue(r[a])}i==="disabled"&&(n.mode=i)}function Ud(n,e){if(e<=n[0].startTime)return 0;let t=n.length-1;if(e>n[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<n[r].startTime)i=r-1;else if(e>n[r].startTime&&s<t)s=r+1;else return r;return n[s].startTime-e<e-n[i].startTime?s:i}function $d(n,e,t){let s=[],i=Ud(n,e);if(i>-1)for(let r=i,a=n.length;r<a;r++){let o=n[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function vs(n){let e=[];for(let t=0;t<n.length;t++){let s=n[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(n[t])}return e}var Er=class extends zt{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=null,s=vs(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}let i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},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(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let s=this.media;if(!s)return;let i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;vs(s.textTracks).forEach(a=>{xt(a)})}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:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.subtitleGroups||null,i=this.groupIds,r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(a=>i?.indexOf(a)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,d)=>{h.id=d});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;let o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;let h=He(o,a);if(h>-1)r=a[h];else{let d=He(o,this.tracks);r=this.tracks[d]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));let l={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){let t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){let r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||dt(r,e)))return i}if(e){for(let i=0;i<t.length;i++){let r=t[i];if(Xt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let r=t[i];if(Xt(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let s=0;s<t.length;s++){let i=t[s];if(ar(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Q.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&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)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let s=this.currentTrack;if(s&&dt(e,s))return s;let i=He(e,this.tracksInGroup);if(i>-1){let r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{let r=He(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=vs(e.textTracks),s=this.currentTrack,i;if(s&&(i=t.filter(r=>ar(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){let r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!O(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}let r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));let{id:a,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:c,type:l,url:h});let d=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(d)}};function Gd(){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 r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function Nt(n){let e=5381,t=n.length;for(;t;)e=e*33^n.charCodeAt(--t);return(e>>>0).toString()}var Rt=.025,$s=(function(n){return n[n.Point=0]="Point",n[n.Range=1]="Range",n})({});function Kd(n,e,t){return`${n.identifier}-${t+1}-${Nt(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 s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}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 pi(e,t)}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,s=pi(t,e);return t-s<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=O(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 pi(e,t)}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)<Rt))}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"?$s.Range:$s.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 Vd(this)}};function pi(n,e){return n-e.start<e.duration/2&&!(Math.abs(n-(e.start+e.duration))<Rt)?e.start:e.start+e.duration}function Go(n,e,t){let s=new self.URL(n,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function yi(n,e){for(;(t=n.assetList[++e])!=null&&t.error;)var t;return e}function Vd(n){return`["${n.identifier}" ${n.cue.pre?"<pre>":n.cue.post?"<post>":""}${n.timelineStart.toFixed(2)}-${n.resumeTime.toFixed(2)}]`}function St(n){let e=n.timelineStart,t=n.duration||0;return`["${n.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var Sr=class{constructor(e,t,s,i){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(m.PLAYOUT_LIMIT_REACHED,{})};let r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;let a=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,a),r.once(m.AUDIO_TRACK_LOADED,a),r.once(m.SUBTITLE_TRACK_LOADED,a),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{let h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(m.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=Go(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;let s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=q.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){let s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=q.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 s=t-this.startOffset;if(s>0&&s<e)return s}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 s=e-t;if(Math.abs(s)>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,s=this.duration;return Math.min(Math.max(0,e-t),s)}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=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${St(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},ya=.033,xr=class extends Ie{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((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);let i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){let s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){let s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){let r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){let t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){let s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){let a=s[r];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||r===i-1))return r}}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 s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){let s=e.main.details,{dateRanges:i}=s,r=this.events,a=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];a.length&&a.sort((l,h)=>{let d=l.cue.pre,u=l.cue.post,f=h.cue.pre,g=h.cue.post;if(d&&!f)return-1;if(f&&!d||u&&!g)return 1;if(g&&!u)return-1;if(!d&&!f&&!u&&!g){let p=l.startTime,y=h.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=a,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){let i=this.events||[];if(i.length||t.length||this.length<2){let r=this.items,a=this.parseSchedule(i,e);(s||t.length||r?.length!==a.length||a.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){let i=[],r=Object.keys(e);for(let a=0;a<r.length;a++){let o=r[a],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new Tr(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){let s=[],i=t.main.details,r=i.live?1/0:i.edge,a=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,d)=>{let u=h.cue.pre,f=h.cue.post,g=e[d-1]||null,p=h.appendInPlace,y=f?r:h.startOffset,v=h.duration,E=h.timelineOccupancy===$s.Range?v:0,T=h.resumptionOffset,S=g?.startTime===y,x=y+h.cumulativeDuration,_=p?x+v:y+T;if(u||!f&&y<=0){let R=l;l+=E,h.timelineStart=x;let b=a;a+=v,s.push({event:h,start:x,end:_,playout:{start:b,end:a},integrated:{start:R,end:l}})}else if(y<=r){if(!S){let L=y-c;if(L>ya){let P=c,M=l;l+=L;let B=a;a+=L;let V={previousEvent:e[d-1]||null,nextEvent:h,start:P,end:P+L,playout:{start:B,end:a},integrated:{start:M,end:l}};s.push(V)}else L>0&&g&&(g.cumulativeDuration+=L,s[s.length-1].end=y)}f&&(_=x),h.timelineStart=x;let R=l;l+=E;let b=a;a+=v,s.push({event:h,start:x,end:_,playout:{start:b,end:a},integrated:{start:R,end:l}})}else return;let A=h.resumeTime;f||A>r?c=r:c=A}),c<r){var o;let h=c,d=l,u=r-c;l+=u;let f=a;a+=u,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+u,playout:{start:f,end:a},integrated:{start:d,end:l}})}this.setDurations(r,a,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){let s=t.main.details,i=s.live?1/0:s.edge,r=0,a=-1;e.forEach((o,c)=>{let l=o.cue.pre,h=o.cue.post,d=l?0:h?i:o.startTime;this.updateAssetDurations(o),a===d?o.cumulativeDuration=r:(r=0,a=d),!h&&o.snapOptions.in&&(o.resumeAnchor=gt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<ya&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=O(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){let s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Rt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${c}`),!1;let l=gt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let h=a==="audio"?.175:0;return Math.abs(l.start-s)<Rt+h||Math.abs(l.end-s)<Rt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,s=0,i=!1,r=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);let l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Fe(n){return`[${n.event?'"'+n.event.identifier+'"':"primary"}: ${n.start.toFixed(2)}-${n.end.toFixed(2)}]`}var Ar=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let s=e.assetListUrl,i;try{i=Go(s,this.hls.sessionId,e.baseUrl)}catch(u){let f=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,u,s);this.hls.trigger(m.ERROR,f);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);let r=this.hls.config,a=r.loader,o=new a(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,g,p)=>{let y=u.data,v=y?.ASSETS;if(!Array.isArray(v)){let E=this.assignAssetListError(e,I.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,p);this.hls.trigger(m.ERROR,E);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(u,f,g,p)=>{let y=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${u.code} ${u.text} (${f.url})`),f.url,p,g);this.hls.trigger(m.ERROR,y)},onTimeout:(u,f,g)=>{let p=this.assignAssetListError(e,I.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,u,g);this.hls.trigger(m.ERROR,p)}};return o.load(c,h,d),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,a){return e.error=s,{type:K.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:a,stats:r}}};function va(n){var e;n==null||(e=n.play())==null||e.catch(()=>{})}function Tt(n,e){return`[${n}] Advancing timeline position to ${e}`}var Lr=class extends Ie{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;let i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;let a=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=s,this.bufferedPos=s;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var c;let f=this.findItemIndex(o),g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a&&g>f){let p=this.schedule.findJumpRestrictedIndex(f+1,g);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(g);return}let l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}let h=l.timelineStart,d=l.duration||0;if(a&&s<h||s>=h+d){var u;(u=o.event)!=null&&u.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;let i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;let o=this.findItemIndex(i);this.setSchedulePosition(o+1)}let r=this.playingAsset;if(!r)return;let a=r.timelineStart+(r.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{let r=this.schedule;if(!r)return;let a=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(p=>p.identifier),d=!!(o.length||h.length);(d||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
29
- Schedule: ${c.map(p=>Fe(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let u=null,f=null;a&&(u=this.updateItem(a,this.timelinePos),this.itemsMatch(a,u)?this.playingItem=u:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);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))),s.forEach(p=>{p.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){let y=p.assetItem.timelineStart,v=p.timelineOffset-y;if(v)try{p.timelineOffset=y}catch(E){Math.abs(v)>Rt&&this.warn(`${E} ("${p.assetId}" ${p.timelineOffset}->${y})`)}}}),d||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:h}),this.isInterstitial(a)&&h.includes(a.event.identifier)){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 xr(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.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=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Le(e,"play",this.onPlay),Le(e,"pause",this.onPause),Le(e,"seeking",this.onSeeking),Le(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let s=this.media=t.media;xe(s,"seeking",this.onSeeking),xe(s,"timeupdate",this.onTimeupdate),xe(s,"play",this.onPlay),xe(s,"pause",this.onPause)}onMediaAttached(e,t){let s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();let r=this.findItemIndex(s);this.setSchedulePosition(r)}}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 s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){let r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.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,s=d=>d&&e.getAssetPlayer(d.identifier),i=(d,u,f,g,p)=>{if(d){let y=d[u].start,v=d.event;if(v){if(u==="playout"||v.timelineOccupancy!==$s.Point){let E=s(f);E?.interstitial===v&&(y+=E.assetItem.startOffset+E[p])}}else{let E=g==="bufferedPos"?a():e[g];y+=E-d.start}return y}return 0},r=(d,u)=>{var f;if(d!==0&&u!=="primary"&&(f=e.schedule)!=null&&f.length){var g;let p=e.schedule.findItemIndexAtTime(d),y=(g=e.schedule.items)==null?void 0:g[p];if(y){let v=y[u].start-y.start;return d+v}}return d},a=()=>{let d=e.bufferedPos;return d===Number.MAX_VALUE?o("primary"):Math.max(d,0)},o=d=>{var u,f;return(u=e.primaryDetails)!=null&&u.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[d])||0},c=(d,u)=>{var f,g;let p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${u}"`);let y=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(d,u),E=(g=e.schedule.items)==null?void 0:g[v],T=e.getBufferingPlayer(),S=T?.interstitial,x=S?.appendInPlace,_=y&&e.itemsMatch(y,E);if(y&&(x||_)){let A=s(e.playingAsset),R=A?.media||e.primaryMedia;if(R){let b=u==="primary"?R.currentTime:i(y,u,e.playingAsset,"timelinePos","currentTime"),L=d-b,P=(x?b:R.currentTime)+L;if(P>=0&&(!A||x||P<=A.duration)){R.currentTime=P;return}}}if(E){let A=d;if(u!=="primary"){let b=E[u].start,L=d-b;A=E.start+L}let R=!e.isInterstitial(E);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(R||E.event.appendInPlace)){let b=e.media||(x?T?.media:null);b&&(b.currentTime=A)}else if(y){let b=e.findItemIndex(y);if(v>b){let P=e.schedule.findJumpRestrictedIndex(b+1,v);if(P>b){e.setSchedulePosition(P);return}}let L=0;if(R)e.timelinePos=A,e.checkBuffer();else{let P=E.event.assetList,M=d-(E[u]||E).start;for(let B=P.length;B--;){let V=P[B];if(V.duration&&M>=V.startOffset&&M<V.startOffset+V.duration){L=B;break}}}e.setSchedulePosition(v,L)}}},l=()=>{let d=e.effectivePlayingItem;if(e.isInterstitial(d))return d;let u=t();return e.isInterstitial(u)?u:null},h={get bufferedEnd(){let d=t(),u=e.bufferingItem;if(u&&u===d){var f;return i(u,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-u.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let d=l(),u=e.effectivePlayingItem;return u&&u===d?i(u,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-u.playout.start:0},set currentTime(d){let u=l(),f=e.effectivePlayingItem;f&&f===u&&c(d+f.playout.start,"playout")},get duration(){let d=l();return d?d.playout.end-d.playout.start:0},get assetPlayers(){var d;let u=(d=l())==null?void 0:d.event.assetList;return u?u.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var d;let u=(d=l())==null?void 0:d.event;return u&&e.effectivePlayingAsset?u.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var d;return((d=e.schedule)==null||(d=d.events)==null?void 0:d.slice(0))||[]},get schedule(){var d;return((d=e.schedule)==null||(d=d.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let d=t();return e.findItemIndex(d)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let d=e.effectivePlayingItem;return e.findItemIndex(d)},primary:{get bufferedEnd(){return a()},get currentTime(){let d=e.timelinePos;return d>0?d:0},set currentTime(d){c(d,"primary")},get duration(){return o("primary")},get seekableStart(){var d;return((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(d){c(d,"integrated")},get duration(){return o("integrated")},get seekableStart(){var d;return r(((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0,"integrated")}},skip:()=>{let d=e.effectivePlayingItem,u=d?.event;if(u&&!u.restrictions.skip){let f=e.findItemIndex(d);if(u.appendInPlace){let g=d.playout.start+d.event.duration;c(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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);let r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!O(r)))return r}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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){let s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}let r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ne(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null,a=this.hls,o=e!==a,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource,h;if(a.media)c&&(r=a.transferMedia(),this.detachedData=r),h="Primary";else if(l){let g=this.getBufferingPlayer();g?(r=g.transferMedia(),h=`${g}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ne(r)}`);else if(!this.detachedData||a.media===t){let g=this.playerQueue;g.length>1&&g.forEach(p=>{if(o&&p.interstitial.appendInPlace!==c){let y=p.interstitial;this.clearInterstitial(p.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let d=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",u=d&&r?r:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);let f=this.schedule;if(u===r&&f){let g=o&&e.assetId===f.assetIdAtEnd;u.overrides={duration:f.duration,endOfStream:!o||g,cueRemoval:!o}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){let r=this.hls.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Tt("checkStart (preroll)",r));let a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(r>=0||!this.primaryLive){this.log(Tt("checkStart",r));let a=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(Tt("checkStart (playing item)",i.start));let r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){let s=e.event,i=s.findAssetIndex(t),r=yi(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;let o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){let i=yi(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){let r=this.schedule.items;if(r){let a=t+1,o=r.length;if(a>=o){this.setSchedulePosition(-1);return}let c=e.resumeTime;this.timelinePos<c&&(this.log(Tt("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){let r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){let s=this.schedule;if(!s)return;let i=t.parentIdentifier,r=s.getEvent(i);if(r){let a=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(e,t){var s;let i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;let r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Fe(r)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let h=a.event,d=this.playingAsset,u=d?.identifier,f=u?this.getAssetPlayer(u):null;if(f&&u&&(!this.eventItemsMatch(a,r)||t!==void 0&&u!==h.assetList[t].identifier)){var c;let g=h.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${h.assetList.length} ${St(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:g,event:h,schedule:i.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(u,r),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Fe(a)}`),h.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();let g=(l=this.schedule)==null?void 0:l.items;if(r&&g){let p=this.findItemIndex(r);this.advanceSchedule(p,g,t,a,o)}return}}this.advanceSchedule(e,i,t,a,o)}advanceSchedule(e,t,s,i,r){let a=this.schedule;if(!a)return;let o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{let d=h.interstitial,u=a.findEventIndex(d.identifier);(u<e||u>e+1)&&this.clearInterstitial(d,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let h=o.event;if(s===void 0){s=a.findAssetIndex(h,this.timelinePos);let g=yi(h,s-1);if(h.isAssetPastPlayoutLimit(g)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=g}let d=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let u=this.preloadAssets(h,s);if(this.eventItemsMatch(o,d||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Fe(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=h.assetList[s];if(!f){this.advanceAfterAssetEnded(h,e,s||0);return}if(u||(u=this.getAssetPlayer(f.identifier)),u===null||u.destroyed){let g=h.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${h}`),u=this.createAssetPlayer(h,f,s),u.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(u,s,t,e,c),this.shouldPlay&&va(u.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&va(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.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,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Fe(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(Tt("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;let a=(r=this.schedule)==null?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Fe(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let s=e.start;if(this.primaryLive){let i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let i=this.primaryMedia;if(!i)return;let r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Tt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;let i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||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(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let s=this.hls.levels[t.level];if(!s.details)return;let i=te(te({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=te(te({},this.altSelection),{},{audio:s});return}let r=te(te({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){let s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=te(te({},this.altSelection),{},{subtitles:s});return}let r=te(te({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){let s=_n(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){let s=_n(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){let s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){let i=this.timelinePos;this.bufferedPos=i,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 r=t[i];if(r.cue.post){var s;let a=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;let i=(s=this.schedule)==null?void 0:s.items;if(e&&i){let r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});let s=e.end+.25,i=q.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Fe(e)} (was ${Fe(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;let s=(t=this.schedule)==null?void 0:t.items;if(!s)return;let i=q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){let i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;let h=this.findItemIndex(r),d=Math.min(h+1,t.length-1),u=t[d];if((c===-1&&r&&e>=r.end||(l=u.event)!=null&&l.appendInPlace&&e+.01>=u.start)&&(c=d),this.isInterstitial(r)){let f=r.event;if(d-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,c>h&&c>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 s&&a&&!this.itemsMatch(a,r)&&(c===o?this.bufferedToItem(a):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{let r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){let{items:i,events:r}=s;if(!i||!r)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 c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Fe(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,d)=>{let u=this.getAssetPlayer(h.identifier);u&&(d===l&&u.loadSource(),u.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.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 s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;let i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){let s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){let a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,a=e.cue.once;if(r){let c=e.timelineStart;if(e.appendInPlace){var o;let u=this.playingItem;!this.isInterstitial(u)&&(u==null||(o=u.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){let u=h-c;u>0&&(l=Math.round(u*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);let d=this.assetListLoader.loadAssetList(e,l);d&&(e.assetListLoader=d)}else if(!a&&i){for(let l=t;l<i;l++){let h=e.assetList[l],d=this.getAssetPlayerQueueIndex(h.identifier);(d===-1||this.playerQueue[d].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}let c=e.assetList[t];if(c){let l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;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 s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,a){let o={parentIdentifier:e.identifier,identifier:Kd(e,a,t),duration:r,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){let i=this.hls,r=i.userConfig,a=r.videoPreference,o=i.loadLevelObj||i.levels[i.currentLevel];(a||o)&&(a=ie({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack],h=0;if(this.primaryLive||e.appendInPlace){let S=this.timelinePos-t.timelineStart;if(S>1){let x=t.duration;x&&S<x&&(h=S)}}let d=t.identifier,u=te(te({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));let f=u.cmcd;f!=null&&f.sessionId&&f.contentId&&(u.cmcd=ie({},f,{contentId:Nt(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);let g=new Sr(this.HlsPlayerClass,u,e,t);this.playerQueue.push(g),e.assetList[s]=t;let p=!0,y=S=>{if(S.live){var x;let R=new Error(`Interstitials MUST be VOD assets ${e}`),b={fatal:!0,type:K.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:R},L=((x=this.schedule)==null?void 0:x.findEventIndex(e.identifier))||-1;this.handleAssetItemError(b,e,L,s,R.message);return}let _=S.edge-S.fragmentStart,A=t.duration;(p||A===null||_>A)&&(p=!1,this.log(`Interstitial asset "${d}" duration change ${A} > ${_}`),t.duration=_,this.updateSchedule())};g.on(m.LEVEL_UPDATED,(S,{details:x})=>y(x)),g.on(m.LEVEL_PTS_UPDATED,(S,{details:x})=>y(x)),g.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(S,x)=>{let _=this.getAssetPlayer(d);if(_&&x.tracks){_.off(m.BUFFER_CODECS,v),_.tracks=x.tracks;let A=this.primaryMedia;this.bufferingAsset===_.assetItem&&A&&!_.media&&this.bufferAssetPlayer(_,A)}};g.on(m.BUFFER_CODECS,v);let E=()=>{var S;let x=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${x}`),!x||!this.schedule)return;let _=this.schedule.findEventIndex(e.identifier),A=(S=this.schedule.items)==null?void 0:S[_];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};g.on(m.BUFFERED_TO_END,E);let T=S=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;let _=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,_,S)};return g.once(m.MEDIA_ENDED,T(s)),g.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),g.on(m.ERROR,(S,x)=>{if(!this.schedule)return;let _=this.getAssetPlayer(d);if(x.details===I.BUFFER_STALLED_ERROR){if(_!=null&&_.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${x.error} ${e}`)}),g.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;let x=new Error(`Asset player destroyed unexpectedly ${d}`),_={fatal:!0,type:K.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(_,e,this.schedule.findEventIndex(e.identifier),s,x.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${St(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){let s=this.getAssetPlayerQueueIndex(e);if(s!==-1){let i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Fe(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){let{interstitial:a,assetItem:o,assetId:c}=e,l=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${St(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;let{interstitial:r,assetItem:a}=e,o=this.schedule.findEventIndex(r.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=a;let l=this.getBufferingPlayer();if(l===e)return;let h=r.appendInPlace;if(h&&l?.interstitial.appendInPlace===!1)return;let d=l?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!Da(d,e.tracks)){let u=new Error(`Asset ${St(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),f={fatal:!0,type:K.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},g=r.findAssetIndex(a);this.handleAssetItemError(f,r,o,g,u.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,s=this.primaryMedia;if(!t||!s)return;let i=s.currentTime,r=t.findAssetIndex(e,i),a=e.assetList[r];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let c=o.currentTime||i-a.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){let h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===I.BUFFER_STALLED_ERROR)return;let a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&St(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,h=this.schedule.items,d=ie({},e,{fatal:!1,errorAction:Lt(!0),asset:a,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;let u=this.playingAsset,f=this.bufferingAsset,g=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(p=>!p.error))t.error=g;else for(let p=i;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):u&&u.identifier===o?this.advanceAfterAssetEnded(t,s,i):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,s=this.effectivePlayingItem,i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Fe(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);let a=this.updateItem(s,i);this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;let r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;let r=t.event,a=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;let c=r.timelineStart,l=r.duration,h=0;o.forEach((p,y)=>{let v=parseFloat(p.DURATION);this.createAsset(r,y,h,c+h,v,p.URI),h+=v}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);let d=this.waitingItem,u=d?.event.identifier===a;this.updateSchedule();let f=(i=this.bufferingItem)==null?void 0:i.event;if(u){var g;let p=this.schedule.findEventIndex(a),y=(g=this.schedule.items)==null?void 0:g[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(y)}this.setSchedulePosition(p)}else if(f?.identifier===a){let p=r.assetList[0];if(p){let y=this.getAssetPlayer(p.identifier);if(f.appendInPlace){let v=this.primaryMedia;y&&v&&this.bufferAssetPlayer(y,v)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case I.ASSET_LIST_PARSING_ERROR:case I.ASSET_LIST_LOAD_ERROR:case I.ASSET_LIST_LOAD_TIMEOUT:{let s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case I.BUFFER_STALLED_ERROR:{let s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Ea=500,Ir=class extends Ht{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",N.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(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=D.IDLE,this.setInterval(Ea),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:s,success:i}=t;if(this.fragContextChanged(s)||(ce(s)&&(this.fragPrevious=s),this.state=D.IDLE),!i)return;let r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a,o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){a=r[l];break}let c=s.start+s.duration;a?a.end=c:(a={start:o,end:c},r.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){let r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,N.SUBTITLE)}}onError(e,t){let s=t.frag;s?.type===N.SUBTITLE&&(t.details===I.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==D.STOPPED&&(this.state=D.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Ro(this.levels,t)){this.levels=t.map(s=>new ft(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{let i=new ft(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,N.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}let i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==D.STOPPED&&this.setInterval(Ea)}onSubtitleTrackLoaded(e,t){var s;let{currentTrackId:i,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let c=r[o];if(o>=r.length||!c)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 l=0;if(a.live||(s=c.details)!=null&&s.live){if(a.deltaUpdateFailed)return;let d=this.mainDetails;if(!d){this.startFragRequested=!1;return}let u=d.fragments[0];if(!c.details)a.hasProgramDateTime&&d.hasProgramDateTime?(Cs(a,d),l=a.fragmentStart):u&&(l=u.start,Hi(a,l));else{var h;l=this.alignPlaylists(a,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&u&&(l=u.start,Hi(a,l))}d&&!this.startFragRequested&&this.setStartPosition(d,l)}c.details=a,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===D.IDLE&&(gt(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&It(i.method)){let a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,Xr(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{let c=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=D.IDLE})}}doTick(){if(!this.media){this.state=D.IDLE;return}if(this.state===D.IDLE){let{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;let{config:i}=this,r=this.getLoadPosition(),a=q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=a,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(c>h)return;let d=l.fragments,u=d.length,f=l.edge,g=null,p=this.fragPrevious;if(o<f){let E=i.maxFragLookUpTolerance,T=o>f-E?0:E;g=gt(p,d,Math.max(d[0].start,o),T),!g&&p&&p.start<d[0].start&&(g=d[0])}else g=d[u-1];if(g=this.filterReplacedPrimary(g,s.details),!g)return;let y=g.sn-l.startSN,v=d[y-1];if(v&&v.cc===g.cc&&this.fragmentTracker.getState(v)===de.NOT_LOADED&&(g=v),this.fragmentTracker.getState(g)===de.NOT_LOADED){let E=this.mapToInitFragWhenRequired(g);E&&this.loadFragment(E,s,o)}}}loadFragment(e,t,s){ce(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new br(this.tracksBuffered[this.currentTrackId]||[])}},br=class{constructor(e){this.buffered=void 0;let t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}},Hd={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},Ko=n=>String.fromCharCode(Hd[n]||n),Ne=15,je=100,Yd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Wd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},qd={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},jd={25:2,26:4,29:6,30:8,31:10,27:13,28:15},zd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Rr=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let s=typeof t=="function"?t():t;se.log(`${this.time} [${e}] ${s}`)}}},lt=function(e){let t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},Gs=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){let t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){let i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},_r=class{constructor(){this.uchar=" ",this.penState=new Gs}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},Dr=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Gs,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<je;t++)this.chars.push(new _r);this.logger=e}equals(e){for(let t=0;t<je;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<je;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<je;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}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>je&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=je)}moveCursor(e){let t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].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=Ko(e);if(this.pos>=je){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<je;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 s=0;s<je;s++){let i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Bt=class{constructor(e){this.rows=[],this.currRow=Ne-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Ne;t++)this.rows.push(new Dr(e));this.logger=e}reset(){for(let e=0;e<Ne;e++)this.rows[e].clear();this.currRow=Ne-1}equals(e){let t=!0;for(let s=0;s<Ne;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Ne;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Ne;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 = "+ne(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<Ne;o++)this.rows[o].clear();let r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[r].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(a.rows[r+l])}}this.currRow=t;let s=this.rows[this.currRow];if(e.indent!==null){let r=e.indent,a=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}let i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ne(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=[],s="",i=-1;for(let r=0;r<Ne;r++){let a=this.rows[r].getTextString();a&&(i=r+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
30
- `)),s}getTextAndFormat(){return this.rows}},Ks=class{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Bt(s),this.nonDisplayedMemory=new Bt(s),this.lastOutputScreen=new Bt(s),this.currRollUpRow=this.displayedMemory.rows[Ne-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Ne-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);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 s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+ne(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))}},Vs=class{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Qd(),this.logger=void 0;let i=this.logger=new Rr;this.channels=[null,new Ks(e,t,i),new Ks(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){let i=t[s]&127,r=t[s+1]&127,a=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+lt([t[s],t[s+1]])+"] -> ("+lt([i,r])+")");let c=this.cmdHistory;if(i>=16&&i<=31){if(Xd(i,r,c)){cs(null,null,c),this.logger.log(3,()=>"Repeated command ("+lt([i,r])+") is dropped");continue}cs(i,r,this.cmdHistory),a=this.parseCmd(i,r),a||(a=this.parseMidrow(i,r)),a||(a=this.parsePAC(i,r)),a||(a=this.parseBackgroundAttributes(i,r))}else cs(null,null,c);if(!a&&(o=this.parseChars(i,r),o)){let h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+lt([i,r])+" orig: "+lt([t[s],t[s+1]]))}}parseCmd(e,t){let s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;let r=e===20||e===21||e===23?1:2,a=this.channels[r];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=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+lt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s,i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;let a=e<=23?1:2;t>=64&&t<=95?s=a===1?Yd[e]:qd[e]:s=a===1?Wd[e]:jd[e];let o=this.channels[a];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let s,i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Ko(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+lt(i).join(",")),i}parseBackgroundAttributes(e,t){let s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r,a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=zd[r],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.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}cs(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let s=this.channels[t];s&&s.cueSplitAtTime(e)}}};function cs(n,e,t){t.a=n,t.b=e}function Xd(n,e,t){return t.a===n&&t.b===e}function Qd(){return{a:null,b:null}}var on=(function(){if(ks!=null&&ks.VTTCue)return self.VTTCue;let n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;let l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(n,o)}function i(o){return t(e,o)}function r(o,...c){let l=1;for(;l<arguments.length;l++){let h=arguments[l];for(let d in h)o[d]=h[d]}return o}function a(o,c,l){let h=this,d={enumerable:!0};h.hasBeenReset=!1;let u="",f=!1,g=o,p=c,y=l,v=null,E="",T=!0,S="auto",x="start",_=50,A="middle",R=50,b="middle";Object.defineProperty(h,"id",r({},d,{get:function(){return u},set:function(L){u=""+L}})),Object.defineProperty(h,"pauseOnExit",r({},d,{get:function(){return f},set:function(L){f=!!L}})),Object.defineProperty(h,"startTime",r({},d,{get:function(){return g},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");g=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},d,{get:function(){return p},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");p=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},d,{get:function(){return y},set:function(L){y=""+L,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},d,{get:function(){return v},set:function(L){v=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},d,{get:function(){return E},set:function(L){let P=s(L);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},d,{get:function(){return T},set:function(L){T=!!L,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},d,{get:function(){return S},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},d,{get:function(){return x},set:function(L){let P=i(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");x=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},d,{get:function(){return _},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");_=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},d,{get:function(){return A},set:function(L){let P=i(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");A=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},d,{get:function(){return R},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");R=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},d,{get:function(){return b},set:function(L){let P=i(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");b=P,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})(),Pr=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Vo(n){function e(s,i,r,a){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(a||0)}let t=n.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 kr=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){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 s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}};function Ho(n,e,t,s){let i=s?n.split(s):[n];for(let r in i){if(typeof i[r]!="string")continue;let a=i[r].split(t);if(a.length!==2)continue;let o=a[0],c=a[1];e(o,c)}}var Cr=new on(0,0,""),hs=Cr.align==="middle"?"middle":"center";function Zd(n,e,t){let s=n;function i(){let o=Vo(n);if(o===null)throw new Error("Malformed timestamp: "+s);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,c){let l=new kr;Ho(o,function(u,f){let g;switch(u){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){l.set(u,t[p].region);break}break;case"vertical":l.alt(u,f,["rl","lr"]);break;case"line":g=f.split(","),l.integer(u,g[0]),l.percent(u,g[0])&&l.set("snapToLines",!1),l.alt(u,g[0],["auto"]),g.length===2&&l.alt("lineAlign",g[1],["start",hs,"end"]);break;case"position":g=f.split(","),l.percent(u,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",hs,"end","line-left","line-right","auto"]);break;case"size":l.percent(u,f);break;case"align":l.alt(u,f,["start",hs,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&Cr.line===-1&&(h=-1),c.line=h,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",hs);let d=l.get("position","auto");d==="auto"&&Cr.position===50&&(d=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=d}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);n=n.slice(3),a(),e.endTime=i(),a(),r(n,e)}function Yo(n){return n.replace(/<br(?: \/)?>/gi,`
31
- `)}var wr=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Pr,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 s(){let r=t.buffer,a=0;for(r=Yo(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
32
- `;)++a;let o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
33
- `&&++a,t.buffer=r.slice(a),o}function i(r){Ho(r,function(a,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();let o=r.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:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new on(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Zd(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let o=r.indexOf("-->")!==-1;if(!r||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
- `),t.cue.text+=r}continue;case"BADCUE":r||(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
-
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}},Jd=/\r\n|\n\r|\n|\r/g,vi=function(e,t,s=0){return e.slice(s,s+t.length)===t},eu=function(e){let t=parseInt(e.slice(-3)),s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!O(t)||!O(s)||!O(i)||!O(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*r,t};function ln(n,e,t){return Nt(n.toString())+Nt(e.toString())+Nt(t)}var tu=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(a=r)!=null&&a.new;){var a;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function su(n,e,t,s,i,r,a){let o=new wr,c=Pe(new Uint8Array(n)).trim().replace(Jd,`
25
+ ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}},fa=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ko="HlsJsTrackRemovedError",hn=class extends Error{constructor(e){super(e),this.name=ko}},un=class extends Re{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{let{media:i,mediaSource:n}=this;s&&this.log("Media source opened"),!(!i||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=Ul(it(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){let{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this),e.off(m.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let s={};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 i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?ie(s,i.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(s[a]=ie({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){let e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){let s=this.media=t.media;this.transferData=this.overrides=void 0;let i=it(this.appendSource);if(i){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=s.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");let c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&a instanceof c,ga(s),jd(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let s=this.tracks,i=t.tracks,n=i?Object.keys(i):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&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
+ required tracks: ${re(s,(c,l)=>c==="initSegment"?void 0:l)};
27
+ transfer tracks: ${re(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!Ca(i,s)){t.mediaSource=null,t.tracks=void 0;let c=e.currentTime,l=this.details,d=Math.max(c,l?.fragments[0].start||0);if(d-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${d} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=d;return}this.transferData=void 0,n.forEach(c=>{let l=c,d=i[l];if(d){let h=d.buffer;if(h){let u=this.fragmentTracker,g=d.id;if(u.hasFragments(g)||u.hasParts(g)){let y=q.getBuffered(h);u.detectEvictedFragments(l,y,g,null,!0)}let f=mi(l),p=[l,h];this.sourceBuffers[f]=p,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,d)}}}),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 s=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:i,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let c=n.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),n.removeSourceBuffer(c[l]);o&&n.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(i.removeAttribute("src"),this.appendSource&&ga(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[mi(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new dn(this.tracks)}onBufferCodecs(e,t){var s;let i=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(c=>!i[c]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${n}" SourceBuffers`);return}n.forEach(c=>{var l,d;let h=t[c],{id:u,codec:g,levelCodec:f,container:p,metadata:y,supplemental:v}=h,E=i[c],T=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],x=T!=null&&T.buffer?T:E,A=x?.pendingCodec||x?.codec,_=x?.levelCodec;E||(E=i[c]={buffer:void 0,listeners:[],codec:g,supplemental:v,container:p,levelCodec:f,metadata:y,id:u});let S=gs(A,_),I=S?.replace(fa,"$1"),b=gs(g,f),L=(d=b)==null?void 0:d.replace(fa,"$1");b&&S&&I!==L&&(c.slice(0,5)==="audio"&&(b=As(b,this.appendSource)),this.log(`switching codec ${A} to ${b}`),b!==(E.pendingCodec||E.codec)&&(E.pendingCodec=b),E.container=p,this.appendChangeType(c,p,b))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){let i=`${t};codecs=${s}`,n={label:`change-type=${i}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),a.codec=s,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 s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,B.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o;let c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&q.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,B.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:s}=this,{data:i,type:n,parent:a,frag:o,part:c,chunkMeta:l,offset:d}=t,h=l.buffering[n],{sn:u,cc:g}=o,f=self.performance.now();h.start=f;let p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=f),y&&y.start===0&&(y.start=f);let v=s.audio,E=!1;n==="audio"&&v?.container==="audio/mpeg"&&(E=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);let T=s.video,x=T?.buffer;if(x&&u!=="initSegment"){let S=c||o,I=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){let L=S.start+S.duration*.05,D=x.buffered,C=this.currentOp("video");!D.length&&!C?this.blockAudio(S):!C&&!q.isBuffered(x,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(S)}else if(n==="video"){let b=S.end;if(I){let L=I.frag.start;(b>L||b<this.lastVideoAppendEnd||q.isBuffered(x,L))&&this.unblockAudio()}this.lastVideoAppendEnd=b}}let A=(c||o).start,_={label:`append-${n}`,execute:()=>{var S;h.executeStart=self.performance.now();let I=(S=this.tracks[n])==null?void 0:S.buffer;I&&(E?this.updateTimestampOffset(I,A,.1,n,u,g):d!==void 0&&F(d)&&this.updateTimestampOffset(I,d,1e-6,n,u,g)),this.appendExecutor(i,n)},onStart:()=>{},onComplete:()=>{let S=self.performance.now();h.executeEnd=h.end=S,p.first===0&&(p.first=S),y&&y.first===0&&(y.first=S);let I={};this.sourceBuffers.forEach(([b,L])=>{b&&(I[b]=q.getBuffered(L))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:n,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:I})},onError:S=>{var I;let b={type:V.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:c,chunkMeta:l,error:S,err:S,fatal:!1},L=(I=this.media)==null?void 0:I.error;if(S.code===DOMException.QUOTA_EXCEEDED_ERR||S.name=="QuotaExceededError"||"quota"in S)b.details=R.BUFFER_FULL_ERROR;else if(S.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!L)b.errorAction=It(!0);else if(S.name===ko&&this.sourceBufferCount===0)b.errorAction=It(!0);else{let D=++this.appendErrors[n];this.warn(`Failed ${D}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${L||"no media error"})`),(D>=this.hls.config.appendErrorMaxRetry||L)&&(b.fatal=!0)}this.hls.trigger(m.ERROR,b)}};this.log(`queuing "${n}" append sn: ${u}${c?" p: "+c.index:""} of ${o.type===B.MAIN?"level":"track"} ${o.level} cc: ${g}`),this.append(_,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){let{type:s,startOffset:i,endOffset:n}=t;s?this.append(this.getFlushOp(s,i,n),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,n),a)})}onFragParsed(e,t){let{frag:s,part:i}=t,n=[],a=i?i.elementaryStreams:s.elementaryStreams;a[ne.AUDIOVIDEO]?n.push("audiovideo"):(a[ne.AUDIO]&&n.push("audio"),a[ne.VIDEO]&&n.push("video"));let o=()=>{let c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);let l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,n).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;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 i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if(!a||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(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.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===R.BUFFER_APPEND_ERROR&&t.frag){var s;let i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;F(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;let i=e.config,n=s.currentTime,a=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(F(o)&&o>=0){let l=Math.max(o,a),d=Math.floor(n/a)*a-l;this.flushBackBuffer(n,a,d)}let c=i.frontBufferFlushThreshold;if(F(c)&&c>0){let l=Math.max(i.maxBufferLength,c),d=Math.max(l,a),h=Math.floor(n/a)*a+d;this.flushFrontBuffer(n,a,h)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,n])=>{if(n){let o=q.getBuffered(n);if(o.length>0&&s>o.start(0)){var a;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});let c=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,n])=>{if(n){let a=q.getBuffered(n),o=a.length;if(o<2)return;let c=a.start(o-1),l=a.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;let{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;let i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){let l=Math.max(0,t.fragmentStart),d=Math.max(l,i);return{duration:1/0,start:l,end:d}}return{duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return F(n)?{duration:n}:null;let a=this.media.duration,o=F(s.duration)?s.duration:0;return i>o&&i>a||!F(a)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){let i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(F(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${re(s)}`),this.tracksReady){var i;let n=(i=this.transferData)==null?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,s])=>{if(t){let i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.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(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)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 c=this.getTrackCodec(o,a),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(a)?" Queued":""} ${re(o)}`);try{let d=s.addSourceBuffer(l),h=mi(a),u=[a,d];t[h]=u,o.buffer=d}catch(d){var i;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:a,mimeType:l,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){let s=e.supplemental,i=e.codec;s&&(t==="video"||t==="audiovideo")&&Gt(s,"video")&&(i=oc(i,s));let n=gs(i,e.levelCodec);return n?t.slice(0,5)==="audio"?As(n,this.appendSource):n:""}trackSourceBuffer(e,t){let s=t.buffer;if(!s)return;let i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,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.hls.trigger(m.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;let s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;let i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});let n=this.currentOp(e);n&&n.onError(i)}updateTimestampOffset(e,t,s,i,n,a){let o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){let{media:i,mediaSource:n}=this,a=this.tracks[e],o=a?.buffer;if(!i||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let c=F(i.duration)?i.duration:1/0,l=F(n.duration)?n.duration:1/0,d=Math.max(0,t),h=Math.min(s,c,l);h>d&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`),o.remove(d,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let s=this.tracks[t],i=s?.buffer;if(!i)throw new hn(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}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}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:s}=this,i=t.map(a=>this.appendBlocker(a));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;let i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){let i=this.tracks[e];if(!i)return;let n=i.buffer;if(!n)return;let a=s.bind(this,e);i.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}};function ga(r){let e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function jd(r,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function mi(r){return r==="audio"?1:0}var fn=class r{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&F(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let s=t.filter((i,n)=>this.isLevelAllowed(i)&&n<=e);return this.clientRect=null,r.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;let i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0,n=e.length-1,a=Math.max(t,s);for(let o=0;o<e.length;o+=1){let c=e[o];if((c.width>=a||c.height>=a)&&i(c,e[o+1])){n=o;break}}return n}},zd={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Ie=zd,Xd={HLS:"h"},Qd=Xd,Qe=class r{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof r?s:new r(s))),this.value=e,this.params=t}},Zd="Dict";function Jd(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 eh(r,e,t,s){return new Error(`failed to ${r} "${Jd(e)}" as ${t}`,{cause:s})}function qe(r,e,t){return eh("serialize",r,e,t)}var $s=class{constructor(e){this.description=e}},pa="Bare Item",th="Boolean";function sh(r){if(typeof r!="boolean")throw qe(r,th);return r?"?1":"?0"}function ih(r){return btoa(String.fromCharCode(...r))}var nh="Byte Sequence";function rh(r){if(ArrayBuffer.isView(r)===!1)throw qe(r,nh);return`:${ih(r)}:`}var ah="Integer";function oh(r){return r<-999999999999999||999999999999999<r}function Co(r){if(oh(r))throw qe(r,ah);return r.toString()}function lh(r){return`@${Co(r.getTime()/1e3)}`}function wo(r,e){if(r<0)return-wo(-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}var ch="Decimal";function dh(r){let e=wo(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw qe(r,ch);let t=e.toString();return t.includes(".")?t:`${t}.0`}var hh="String",uh=/[\x00-\x1f\x7f]+/;function fh(r){if(uh.test(r))throw qe(r,hh);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function gh(r){return r.description||r.toString().slice(7,-1)}var ph="Token";function ma(r){let e=gh(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw qe(e,ph);return e}function gn(r){switch(typeof r){case"number":if(!F(r))throw qe(r,pa);return Number.isInteger(r)?Co(r):dh(r);case"string":return fh(r);case"symbol":return ma(r);case"boolean":return sh(r);case"object":if(r instanceof Date)return lh(r);if(r instanceof Uint8Array)return rh(r);if(r instanceof $s)return ma(r);default:throw qe(r,pa)}}var mh="Key";function pn(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw qe(r,mh);return r}function ar(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${pn(e)}`:`;${pn(e)}=${gn(t)}`).join("")}function Mo(r){return r instanceof Qe?`${gn(r.value)}${ar(r.params)}`:gn(r)}function yh(r){return`(${r.value.map(Mo).join(" ")})${ar(r.params)}`}function vh(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw qe(r,Zd);let t=r instanceof Map?r.entries():Object.entries(r),s=e?.whitespace?" ":"";return Array.from(t).map(([i,n])=>{n instanceof Qe||(n=new Qe(n));let a=pn(i);return n.value===!0?a+=ar(n.params):(a+="=",Array.isArray(n.value)?a+=yh(n):a+=Mo(n)),a}).join(`,${s}`)}function Oo(r,e){return vh(r,e)}var Ve="CMCD-Object",le="CMCD-Request",lt="CMCD-Session",et="CMCD-Status",Eh={br:Ve,ab:Ve,d:Ve,ot:Ve,tb:Ve,tpb:Ve,lb:Ve,tab:Ve,lab:Ve,url:Ve,pb:le,bl:le,tbl:le,dl:le,ltc:le,mtp:le,nor:le,nrr:le,rc:le,sn:le,sta:le,su:le,ttfb:le,ttfbb:le,ttlb:le,cmsdd:le,cmsds:le,smrt:le,df:le,cs:le,ts:le,cid:lt,pr:lt,sf:lt,sid:lt,st:lt,v:lt,msd:lt,bs:et,bsd:et,cdn:et,rtp:et,bg:et,pt:et,ec:et,e:et},Th={REQUEST:le};function Sh(r){return Object.keys(r).reduce((e,t)=>{var s;return(s=r[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function xh(r,e){let t={};if(!r)return t;let s=Object.keys(r),i=e?Sh(e):{};return s.reduce((n,a)=>{var o;let c=Eh[a]||i[a]||Th.REQUEST,l=(o=n[c])!==null&&o!==void 0?o:n[c]={};return l[a]=r[a],n},t)}function Ah(r){return["ot","sf","st","e","sta"].includes(r)}function Lh(r){return typeof r=="number"?F(r):r!=null&&r!==""&&r!==!1}var Fo="event";function Ih(r,e){let t=new URL(r),s=new URL(e);if(t.origin!==s.origin)return r;let i=t.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;i[0]===n[0];)i.shift(),n.shift();for(;n.length;)n.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}var vs=r=>Math.round(r),mn=(r,e)=>Array.isArray(r)?r.map(t=>mn(t,e)):r instanceof Qe&&typeof r.value=="string"?new Qe(mn(r.value,e),r.params):(e.baseUrl&&(r=Ih(r,e.baseUrl)),e.version===1?encodeURIComponent(r):r),ls=r=>vs(r/100)*100,bh=(r,e)=>{let t=r;return e.version>=2&&(r instanceof Qe&&typeof r.value=="string"?t=new Qe([r]):typeof r=="string"&&(t=[r])),mn(t,e)},Rh={br:vs,d:vs,bl:ls,dl:ls,mtp:ls,nor:bh,rtp:ls,tb:vs},No="request",Bo="response",or=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],_h=["e"],Ph=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function zs(r){return Ph.test(r)}function Dh(r){return or.includes(r)||_h.includes(r)||zs(r)}var $o=["d","dl","nor","ot","rtp","su"];function kh(r){return or.includes(r)||$o.includes(r)||zs(r)}var Ch=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function wh(r){return or.includes(r)||$o.includes(r)||Ch.includes(r)||zs(r)}var Mh=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Oh(r){return Mh.includes(r)||zs(r)}var Fh={[Bo]:wh,[Fo]:Dh,[No]:kh};function Uo(r,e={}){let t={};if(r==null||typeof r!="object")return t;let s=e.version||r.v||1,i=e.reportingMode||No,n=s===1?Oh:Fh[i],a=Object.keys(r).filter(n),o=e.filter;typeof o=="function"&&(a=a.filter(o));let c=i===Bo||i===Fo;c&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");let l=ie({},Rh,e.formatters),d={version:s,reportingMode:i,baseUrl:e.baseUrl};return a.sort().forEach(h=>{let u=r[h],g=l[h];if(typeof g=="function"&&(u=g(u,d)),h==="v"){if(s===1)return;u=s}h=="pr"&&u===1||(c&&h==="ts"&&!F(u)&&(u=Date.now()),Lh(u)&&(Ah(h)&&typeof u=="string"&&(u=new $s(u)),t[h]=u))}),t}function Nh(r,e={}){let t={};if(!r)return t;let s=Uo(r,e),i=xh(s,e?.customHeaderMap);return Object.entries(i).reduce((n,[a,o])=>{let c=Oo(o,{whitespace:!1});return c&&(n[a]=c),n},t)}function Bh(r,e,t){return ie(r,Nh(e,t))}var $h="CMCD";function Uh(r,e={}){return r?Oo(Uo(r,e),{whitespace:!1}):""}function Gh(r,e={}){if(!r)return"";let t=Uh(r,e);return encodeURIComponent(t)}function Kh(r,e={}){if(!r)return"";let t=Gh(r,e);return`${$h}=${t}`}var ya=/CMCD=[^&#]+/;function Vh(r,e,t){let s=Kh(e,t);if(!s)return r;if(ya.test(r))return r.replace(ya,s);let i=r.includes("?")?"&":"?";return`${r}${i}${s}`}var yn=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Ie.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=i=>{try{let{frag:n,part:a}=i,o=this.hls.levels[n.level],c=this.getObjectType(n),l={d:(a||n).duration*1e3,ot:c};(c===Ie.VIDEO||c===Ie.AUDIO||c==Ie.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));let d=a?this.getNextPart(a):this.getNextFrag(n);d!=null&&d.url&&d.url!==n.url&&(l.nor=d.url),this.apply(i,l)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;let t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Qd.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ie(t,this.createData());let s=t.ot===Ie.INIT||t.ot===Ie.VIDEO||t.ot===Ie.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((a,o)=>(i.includes(o)&&(a[o]=t[o]),a),{}));let n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Bh(e.headers,t,n)):e.url=Vh(e.url,t,n)}getNextFrag(e){var t;let s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){let i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;let{index:s,fragment:i}=e,n=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=i;for(let o=n.length-1;o>=0;o--){let c=n[o];if(c.index===s&&c.fragment.sn===a)return n[o+1]}}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return Ie.TIMED_TEXT;if(e.sn==="initSegment")return Ie.INIT;if(t==="audio")return Ie.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ie.VIDEO:Ie.MUXED}getTopBandwidth(e){let t=0,s,i=this.hls;if(e===Ie.AUDIO)s=i.audioTracks;else{let n=i.maxAutoLevel,a=n>-1?n+1:i.levels.length;s=i.levels.slice(0,a)}return s.forEach(n=>{n.bitrate>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,s=e===Ie.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(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,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(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)}}}},Hh=3e5,vn=class extends Re{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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:s}=t;if(s?.action===me.SendAlternateToPenaltyBox&&s.flags===_e.MoveAllAlternatesMatchingHost){let i=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:c,type:l}=t.context;o&&i?a=this.getPathwayForGroupId(o,l,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),s.resolved=this.pathwayId!==a),t.details===R.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${re(n)} penalized: ${re(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}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,s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(n=>{i-s[n]>Hh&&delete s[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in s)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,co(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});let l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){let i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let n=0;n<i.length;n++)if(t===Q.AUDIO_TRACK&&i[n].hasAudioGroup(e)||t===Q.SUBTITLE_TRACK&&i[n].hasSubtitleGroup(e))return i[n].pathwayId;return s}clonePathways(e){let t=this.levels;if(!t)return;let s={},i={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":c}=n;if(t.some(d=>d.pathwayId===a))return;let l=this.getLevelsForPathway(o).map(d=>{let h=new ae(d.attrs);h["PATHWAY-ID"]=a;let u=h.AUDIO&&`${h.AUDIO}_clone_${a}`,g=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;u&&(s[h.AUDIO]=u,h.AUDIO=u),g&&(i[h.SUBTITLES]=g,h.SUBTITLES=g);let f=Go(d.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new gt({attrs:h,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:f,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let y=1;y<d.audioGroups.length;y++)p.addGroupId("audio",`${d.audioGroups[y]}_clone_${a}`);if(d.subtitleGroups)for(let y=1;y<d.subtitleGroups.length;y++)p.addGroupId("text",`${d.subtitleGroups[y]}_clone_${a}`);return p});t.push(...l),va(this.audioTracks,s,c,a),va(this.subtitleTracks,i,c,a)})}loadSteeringManifest(e){let t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){let d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+d)}let n={responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},c={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(d,h,u,g)=>{this.log(`Loaded steering manifest: "${i}"`);let f=d.data;if(f?.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;let{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=f;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||u.url),y&&this.clonePathways(y);let E={steeringManifest:f,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,E),v&&this.updatePathwayPriority(v)},onError:(d,h,u,g)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${h.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let f=this.timeToLoad*1e3;if(d.code===429){let p=this.loader;if(typeof p?.getResponseHeader=="function"){let y=p.getResponseHeader("Retry-After");y&&(f=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,f)},onTimeout:(d,h,u)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(n,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;let i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function va(r,e,t,s){r&&Object.keys(e).forEach(i=>{let n=r.filter(a=>a.groupId===i).map(a=>{let o=ie({},a);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=Go(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});r.push(...n)})}function Go(r,e,t,s){let{HOST:i,PARAMS:n,[t]:a}=s,o;e&&(o=a?.[e],o&&(r=o));let c=new self.URL(r);return i&&!o&&(c.host=i),n&&Object.keys(n).sort().forEach(l=>{l&&c.searchParams.set(l,n[l])}),c.href}var Us=class r extends Re{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._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=r.CDMCleanupPromise?[r.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{let{initDataType:s,initData:i}=t,n=`"${t.type}" event: init data type: "${s}"`;if(this.debug(n),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Ot(this.config));let o=a.map(li).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o=ms(a);if(s!=="sinf"||o!==oe.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{let g=ue(new Uint8Array(i)),f=Jn(JSON.parse(g).sinf),p=Ua(f);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${n} Failed to parse sinf: ${g}`);return}let l=ve(c),{keyIdToKeySessionPromise:d,mediaKeySessions:h}=this,u=d[l];for(let g=0;g<h.length;g++){let f=h[g],p=f.decryptdata;if(!p.keyId)continue;let y=ve(p.keyId);if(ks(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(u=d[y],!u)continue;if(p.pssh)break;delete d[y],p.pssh=new Uint8Array(i),p.keyId=c,u=d[l]=u.then(()=>this.generateRequestWithPreferredKeySession(f,s,i,"encrypted-event-key-match")),u.catch(v=>this.handleError(v));break}}u||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${h.length}.`))}).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=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t?.[e];if(i)return i.licenseUrl;if(e===oe.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,s=(a,o,c)=>!!a&&c.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),n=t.map(a=>a.videoCodec).filter(s);return i.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let c=l=>{let d=l.shift();this.getMediaKeysPromise(d,i,n).then(h=>a({keySystem:d,mediaKeys:h})).catch(h=>{l.length?c(l):h instanceof Ae?o(h):o(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};c(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return to===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;let n=Kc(e,t,s,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${re(n)}`),o=this.requestMediaKeySystemAccess(e,n);let c=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);let d=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let h=c.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,d.then(g=>g?this.setMediaKeysServerCertificate(u,e,g):u)));return h.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),h})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${ve(e.keyId||[])} keyUri: ${e.uri}`);let i=s.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let s=this.createMediaKeySessionContext(e),i=cs(t),n="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){let s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${ve(e.decryptdata.keyId||[])}
28
+ } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>li(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{let n=li(i);n?t(n):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}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=Ot(this.config),s=e.map(ms).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){let i=Yh(e,t[s]);if(i)return i}}loadKey(e){let t=e.keyInfo.decryptdata,s=cs(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){let o=Ea(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}let n=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let a=this.keyIdToKeySessionPromise[s];if(!a){let o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{let l="cenc",d=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,d,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Ae){let c=te({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);let l=new Ae(c,o.message);this.handleError(l,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ae){t&&(e.data.frag=t);let s=e.data.decryptdata;this.error(`${e.message}${s?` (${ve(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=cs(e),s=this.keyIdToKeySessionPromise[t];if(!s){let i=ms(e.keyFormat),n=i?[i]:Ot(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Ot(this.config)),e.length===0)throw new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${re({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let i=Promise.all(s).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(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var n;let a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{let f=a.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=f.initData?f.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);let o=cs(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);let l=new er,d=e._onmessage=f=>{let p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}let{messageType:y,message:v}=f;this.log(`"${y}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(E=>{l.eventNames().length?l.emit("error",E):this.handleError(E)}):y==="license-release"?e.keySystem===oe.FAIRPLAY&&this.updateKeySession(e,Vi("acknowledged")).then(()=>this.removeSession(e)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${y}"`)},h=(f,p)=>{p.keyStatus=f;let y;f.startsWith("usable")?l.emit("resolved"):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?y=Ea(f,p.decryptdata):f==="expired"?y=new Error(`key expired (keyId: ${o})`):f==="released"?y=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},u=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}let y=this.getKeyStatuses(e);if(!Object.keys(y).some(x=>y[x]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${re(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let E=y[o];if(E)h(E,e);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let A=this.getKeyStatus(e.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),h(A,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),E="internal-error",h(E,e)},1e3)),this.log(`No status for keyId ${o} (${re(y)}).`)}};Le(e.mediaKeysSession,"message",d),Le(e.mediaKeysSession,"keystatuseschange",u);let g=new Promise((f,p)=>{l.on("error",p),l.on("resolved",f)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(f=>{throw new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>g).catch(f=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw f}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){let o=i;i=s,s=o}let n="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===oe.PLAYREADY&&n.length===16){let o=ve(n);t[o]=s,Ja(n)}let a=ve(n);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){let t=this.config,s=t.loader,i=new s(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let c={responseType:"arraybuffer",url:n},l=t.certLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,g,f,p)=>{a(u.data)},onError:(u,g,f,p)=>{o(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:te({url:c.url,data:void 0},u)},`"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,g,f)=>{o(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(u,g,f)=>{o(new Error("aborted"))}};i.load(c,d,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,n)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(a=>{n(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){let s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let i=new DOMParser().parseFromString(s,"application/xml"),n=i.querySelectorAll("HttpHeader");if(n.length>0){let d;for(let h=0,u=n.length;h<u;h++){var a,o;d=n[h];let g=(a=d.querySelector("name"))==null?void 0:a.textContent,f=(o=d.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}let c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Vi(atob(l))}setupLicenseXHR(e,t,s,i){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,s,i)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,s,i)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){let s=this.config.keyLoadPolicy.default;return new Promise((i,n)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);let l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,a,e)}catch(d){this.error(d)}i(c)}else{let c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)n(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let d=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t).then(i,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==oe.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let s=t.media;this.media=s,Le(s,"encrypted",this.onMediaEncrypted),Le(s,"waitingforkey",this.onWaitingForKey);let i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){let e=this.media;e&&(be(e,"encrypted",this.onMediaEncrypted),be(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Dt.clearKeyUriToKeyIdMap();let n=i.length;r.CDMCleanupPromise=Promise.all(i.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.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(m.ERROR,{type:V.OTHER_ERROR,details:R.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()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let s=t.reduce((i,n)=>(i.indexOf(n.keyFormat)===-1&&i.push(n.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${ve(i?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));let{drmSystemOptions:o}=this.config;return(Hc(o)?new Promise((l,d)=>{self.setTimeout(()=>d(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(d)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}};Us.CDMCleanupPromise=void 0;function cs(r){if(!r)throw new Error("Could not read keyId of undefined decryptdata");if(r.keyId===null)throw new Error("keyId is null");return ve(r.keyId)}function Yh(r,e){if(r.keyId&&e.mediaKeysSession.keyStatuses.has(r.keyId))return e.mediaKeysSession.keyStatuses.get(r.keyId);if(r.matches(e.decryptdata))return e.keyStatus}var Ae=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}};function Ea(r,e){let t=r==="output-restricted",s=t?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ae({type:V.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}var En=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(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let s=this.hls.config;if(s.capLevelOnFPSDrop){let i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){let i=performance.now();if(t){if(this.lastTime){let n=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*a/n,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),c>0&&a>l.config.fpsDroppedMonitoringThreshold*o){let d=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=d)&&(d=d-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function Ko(r,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=r,e.dispatchEvent(t)}function Vo(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(s){se.debug(`[texttrack-utils]: ${s}`);try{let i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,r.addCue(i)}catch(i){se.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(r.mode=t)}function At(r,e){let t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let s=r.cues.length;s--;)e&&r.cues[s].removeEventListener("enter",e),r.removeCue(r.cues[s]);t==="disabled"&&(r.mode=t)}function Tn(r,e,t,s){let i=r.mode;if(i==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){let n=qh(r.cues,e,t);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&r.removeCue(n[a])}i==="disabled"&&(r.mode=i)}function Wh(r,e){if(e<=r[0].startTime)return 0;let t=r.length-1;if(e>r[t].endTime)return-1;let s=0,i=t,n;for(;s<=i;)if(n=Math.floor((i+s)/2),e<r[n].startTime)i=n-1;else if(e>r[n].startTime&&s<t)s=n+1;else return n;return r[s].startTime-e<e-r[i].startTime?s:i}function qh(r,e,t){let s=[],i=Wh(r,e);if(i>-1)for(let n=i,a=r.length;n<a;n++){let o=r[n];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function Es(r){let e=[];for(let t=0;t<r.length;t++){let s=r[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(r[t])}return e}var Sn=class extends Xt{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=null,s=Es(this.media.textTracks);for(let n=0;n<s.length;n++)if(s[n].mode==="hidden")t=s[n];else if(s[n].mode==="showing"){t=s[n];break}let i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},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(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let s=this.media;if(!s)return;let i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;Es(s.textTracks).forEach(a=>{At(a)})}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:s,groupId:i,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.subtitleGroups||null,i=this.groupIds,n=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(a=>i?.indexOf(a)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(d=>d.default)&&(this.selectDefaultTrack=!1),a.forEach((d,h)=>{d.id=h});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;let d=We(o,a);if(d>-1)n=a[d];else{let h=We(o,this.tracks);n=this.tracks[h]}}let c=this.findTrackId(n);c===-1&&n&&(c=this.findTrackId(null));let l={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){let t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){let n=t[i];if(!(s&&!n.default||!s&&!e)&&(!e||ut(n,e)))return i}if(e){for(let i=0;i<t.length;i++){let n=t[i];if(Qt(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let n=t[i];if(Qt(e.attrs,n.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let s=0;s<t.length;s++){let i=t[s];if(ln(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Q.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&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)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let s=this.currentTrack;if(s&&ut(e,s))return s;let i=We(e,this.tracksInGroup);if(i>-1){let n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}else{if(s)return null;{let n=We(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 s=e.id,i=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${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(m.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=Es(e.textTracks),s=this.currentTrack,i;if(s&&(i=t.filter(n=>ln(s,n))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==i&&(n.mode="disabled")}),i){let n=this.subtitleDisplay?"showing":"hidden";i.mode!==n&&(i.mode=n)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!F(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}let n=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&n)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));let{id:a,groupId:o="",name:c,type:l,url:d}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:c,type:l,url:d});let h=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(h)}};function jh(){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 n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?n:n&3|8).toString(16)})}}}function Bt(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}var _t=.025,Gs=(function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r})({});function zh(r,e,t){return`${r.identifier}-${t+1}-${Bt(e)}`}var xn=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 s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}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 yi(e,t)}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,s=yi(t,e);return t-s<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=F(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 yi(e,t)}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)<_t))}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"?Gs.Range:Gs.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 Xh(this)}};function yi(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<_t)?e.start:e.start+e.duration}function Ho(r,e,t){let s=new self.URL(r,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function vi(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function Xh(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function xt(r){let e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var An=class{constructor(e,t,s,i){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(m.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=s,this.assetItem=i;let a=()=>{this.hasDetails=!0};n.once(m.LEVEL_LOADED,a),n.once(m.AUDIO_TRACK_LOADED,a),n.once(m.SUBTITLE_TRACK_LOADED,a),n.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(m.BUFFER_APPENDED,()=>{let d=this.bufferedEnd;this.reachedPlayout(d)&&(this._bufferedEosTime=d,n.trigger(m.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=Ho(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;let s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,n=q.bufferInfo(e,i,0);return this.getAssetTime(n.end)>=s-.02}reachedPlayout(e){let s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=q.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 s=t-this.startOffset;if(s>0&&s<e)return s}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 s=e-t;if(Math.abs(s)>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,s=this.duration;return Math.min(Math.max(0,e-t),s)}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=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${xt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},Ta=.033,Ln=class extends Re{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((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);let i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(n=i[s])!=null&&n.event;){var n;s--}return s}findItemIndexAtTime(e,t){let s=this.items;if(s)for(let i=0;i<s.length;i++){let n=s[i];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return i}return-1}findJumpRestrictedIndex(e,t){let s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){let n=s[i].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return i}return-1}findEventIndex(e){let t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){let s=e.assetList,i=s.length;if(i>1)for(let n=0;n<i;n++){let a=s[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===i-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 s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){let s=e.main.details,{dateRanges:i}=s,n=this.events,a=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=n?n.filter(l=>!o.includes(l.identifier)):[];a.length&&a.sort((l,d)=>{let h=l.cue.pre,u=l.cue.post,g=d.cue.pre,f=d.cue.post;if(h&&!g)return-1;if(g&&!h||u&&!f)return 1;if(f&&!u)return-1;if(!h&&!g&&!u&&!f){let p=l.startTime,y=d.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-d.dateRange.tagOrder}),this.events=a,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){let i=this.events||[];if(i.length||t.length||this.length<2){let n=this.items,a=this.parseSchedule(i,e);(s||t.length||n?.length!==a.length||a.some((c,l)=>Math.abs(c.playout.start-n[l].playout.start)>.005||Math.abs(c.playout.end-n[l].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){let i=[],n=Object.keys(e);for(let a=0;a<n.length;a++){let o=n[a],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new xn(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){let s=[],i=t.main.details,n=i.live?1/0:i.edge,a=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((d,h)=>{let u=d.cue.pre,g=d.cue.post,f=e[h-1]||null,p=d.appendInPlace,y=g?n:d.startOffset,v=d.duration,E=d.timelineOccupancy===Gs.Range?v:0,T=d.resumptionOffset,x=f?.startTime===y,A=y+d.cumulativeDuration,_=p?A+v:y+T;if(u||!g&&y<=0){let I=l;l+=E,d.timelineStart=A;let b=a;a+=v,s.push({event:d,start:A,end:_,playout:{start:b,end:a},integrated:{start:I,end:l}})}else if(y<=n){if(!x){let L=y-c;if(L>Ta){let D=c,C=l;l+=L;let $=a;a+=L;let H={previousEvent:e[h-1]||null,nextEvent:d,start:D,end:D+L,playout:{start:$,end:a},integrated:{start:C,end:l}};s.push(H)}else L>0&&f&&(f.cumulativeDuration+=L,s[s.length-1].end=y)}g&&(_=A),d.timelineStart=A;let I=l;l+=E;let b=a;a+=v,s.push({event:d,start:A,end:_,playout:{start:b,end:a},integrated:{start:I,end:l}})}else return;let S=d.resumeTime;g||S>n?c=n:c=S}),c<n){var o;let d=c,h=l,u=n-c;l+=u;let g=a;a+=u,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:d+u,playout:{start:g,end:a},integrated:{start:h,end:l}})}this.setDurations(n,a,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){let s=t.main.details,i=s.live?1/0:s.edge,n=0,a=-1;e.forEach((o,c)=>{let l=o.cue.pre,d=o.cue.post,h=l?0:d?i:o.startTime;this.updateAssetDurations(o),a===h?o.cumulativeDuration=n:(n=0,a=h),!d&&o.snapOptions.in&&(o.resumeAnchor=pt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Ta&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let g=F(o.resumeOffset)?o.resumeOffset:o.duration;n+=g})}primaryCanResumeInPlaceAt(e,t){let s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>_t?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${c}`),!1;let l=pt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let d=a==="audio"?.175:0;return Math.abs(l.start-s)<_t+d||Math.abs(l.end-s)<_t+d?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,s=0,i=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),n||(n=!!o.error);let l=o.error?0:o.duration||0;s+=l}i&&!n?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Be(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}var In=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let s=e.assetListUrl,i;try{i=Ho(s,this.hls.sessionId,e.baseUrl)}catch(u){let g=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,u,s);this.hls.trigger(m.ERROR,g);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),c={responseType:"json",url:i.href},l=n.interstitialAssetListLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,g,f,p)=>{let y=u.data,v=y?.ASSETS;if(!Array.isArray(v)){let E=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,g,p);this.hls.trigger(m.ERROR,E);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(u,g,f,p)=>{let y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${u.code} ${u.text} (${g.url})`),g.url,p,f);this.hls.trigger(m.ERROR,y)},onTimeout:(u,g,f)=>{let p=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,u,f);this.hls.trigger(m.ERROR,p)}};return o.load(c,d,h),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,n,a){return e.error=s,{type:V.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:a,stats:n}}};function Sa(r){var e;r==null||(e=r.play())==null||e.catch(()=>{})}function St(r,e){return`[${r}] Advancing timeline position to ${e}`}var bn=class extends Re{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;let i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;let a=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=s,this.bufferedPos=s;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var c;let g=this.findItemIndex(o),f=this.schedule.findItemIndexAtTime(s);if(f===-1&&(f=g+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${g} to ${f})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a&&f>g){let p=this.schedule.findJumpRestrictedIndex(g+1,f);if(p>g){this.setSchedulePosition(p);return}}this.setSchedulePosition(f);return}let l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){let g=o.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,g))}return}let d=l.timelineStart,h=l.duration||0;if(a&&s<d||s>=d+h){var u;(u=o.event)!=null&&u.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;let i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;let o=this.findItemIndex(i);this.setSchedulePosition(o+1)}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,n)},this.onScheduleUpdate=(s,i)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],c=n.items||[],l=n.durations,d=s.map(p=>p.identifier),h=!!(o.length||d.length);(h||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
29
+ Schedule: ${c.map(p=>Be(p))} pos: ${this.timelinePos}`),d.length&&this.log(`Removed events ${d}`);let u=null,g=null;a&&(u=this.updateItem(a,this.timelinePos),this.itemsMatch(a,u)?this.playingItem=u:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let f=this.bufferingItem;if(f&&(g=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,g)?this.bufferingItem=g:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),s.forEach(p=>{p.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){let y=p.assetItem.timelineStart,v=p.timelineOffset-y;if(v)try{p.timelineOffset=y}catch(E){Math.abs(v)>_t&&this.warn(`${E} ("${p.assetId}" ${p.timelineOffset}->${y})`)}}}),h||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:d}),this.isInterstitial(a)&&d.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(u,a),f&&g!==u&&this.trimInPlace(g,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new In(e),this.schedule=new Ln(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.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=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){be(e,"play",this.onPlay),be(e,"pause",this.onPause),be(e,"seeking",this.onSeeking),be(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let s=this.media=t.media;Le(s,"seeking",this.onSeeking),Le(s,"timeupdate",this.onTimeupdate),Le(s,"play",this.onPlay),Le(s,"pause",this.onPause)}onMediaAttached(e,t){let s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();let n=this.findItemIndex(s);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 s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),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,s=h=>h&&e.getAssetPlayer(h.identifier),i=(h,u,g,f,p)=>{if(h){let y=h[u].start,v=h.event;if(v){if(u==="playout"||v.timelineOccupancy!==Gs.Point){let E=s(g);E?.interstitial===v&&(y+=E.assetItem.startOffset+E[p])}}else{let E=f==="bufferedPos"?a():e[f];y+=E-h.start}return y}return 0},n=(h,u)=>{var g;if(h!==0&&u!=="primary"&&(g=e.schedule)!=null&&g.length){var f;let p=e.schedule.findItemIndexAtTime(h),y=(f=e.schedule.items)==null?void 0:f[p];if(y){let v=y[u].start-y.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,g;return(u=e.primaryDetails)!=null&&u.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[h])||0},c=(h,u)=>{var g,f;let p=e.effectivePlayingItem;if(p!=null&&(g=p.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${u}"`);let y=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(h,u),E=(f=e.schedule.items)==null?void 0:f[v],T=e.getBufferingPlayer(),x=T?.interstitial,A=x?.appendInPlace,_=y&&e.itemsMatch(y,E);if(y&&(A||_)){let S=s(e.playingAsset),I=S?.media||e.primaryMedia;if(I){let b=u==="primary"?I.currentTime:i(y,u,e.playingAsset,"timelinePos","currentTime"),L=h-b,D=(A?b:I.currentTime)+L;if(D>=0&&(!S||A||D<=S.duration)){I.currentTime=D;return}}}if(E){let S=h;if(u!=="primary"){let b=E[u].start,L=h-b;S=E.start+L}let I=!e.isInterstitial(E);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(I||E.event.appendInPlace)){let b=e.media||(A?T?.media:null);b&&(b.currentTime=S)}else if(y){let b=e.findItemIndex(y);if(v>b){let D=e.schedule.findJumpRestrictedIndex(b+1,v);if(D>b){e.setSchedulePosition(D);return}}let L=0;if(I)e.timelinePos=S,e.checkBuffer();else{let D=E.event.assetList,C=h-(E[u]||E).start;for(let $=D.length;$--;){let H=D[$];if(H.duration&&C>=H.startOffset&&C<H.startOffset+H.duration){L=$;break}}}e.setSchedulePosition(v,L)}}},l=()=>{let h=e.effectivePlayingItem;if(e.isInterstitial(h))return h;let u=t();return e.isInterstitial(u)?u:null},d={get bufferedEnd(){let h=t(),u=e.bufferingItem;if(u&&u===h){var g;return i(u,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-u.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){let h=l(),u=e.effectivePlayingItem;return u&&u===h?i(u,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-u.playout.start:0},set currentTime(h){let u=l(),g=e.effectivePlayingItem;g&&g===u&&c(h+g.playout.start,"playout")},get duration(){let h=l();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;let u=(h=l())==null?void 0:h.event.assetList;return u?u.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var h;let u=(h=l())==null?void 0:h.event;return u&&e.effectivePlayingAsset?u.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};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 l()?d: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){c(h,"primary")},get duration(){return o("primary")},get seekableStart(){var h;return((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){c(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){var h;return n(((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{let h=e.effectivePlayingItem,u=h?.event;if(u&&!u.restrictions.skip){let g=e.findItemIndex(h);if(u.appendInPlace){let f=h.playout.start+h.event.duration;c(f+.001,"playout")}else e.advanceAfterAssetEnded(u,g,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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);let n=(t=i)==null?void 0:t.currentTime;if(!(n===void 0||!F(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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){let s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${re(n)}`),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource,d;if(a.media)c&&(n=a.transferMedia(),this.detachedData=n),d="Primary";else if(l){let f=this.getBufferingPlayer();f?(n=f.transferMedia(),d=`${f}`):d="detached MediaSource"}else d="detached media";if(!n){if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${re(n)}`);else if(!this.detachedData||a.media===t){let f=this.playerQueue;f.length>1&&f.forEach(p=>{if(o&&p.interstitial.appendInPlace!==c){let y=p.interstitial;this.clearInterstitial(p.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let h=n&&"mediaSource"in n&&((i=n.mediaSource)==null?void 0:i.readyState)!=="closed",u=h&&n?n:t;this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`);let g=this.schedule;if(u===n&&g){let f=o&&e.assetId===g.assetIdAtEnd;u.overrides={duration:g.duration,endOfStream:!o||f,cueRemoval:!o}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){let n=this.hls.startPosition;if(this.timelinePos=n,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(St("checkStart (preroll)",n));let a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){this.log(St("checkStart",n));let a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(St("checkStart (playing item)",i.start));let n=e.findItemIndex(i);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){let s=e.event,i=s.findAssetIndex(t),n=vi(s,i);if(!s.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;let o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){let i=vi(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){let n=this.schedule.items;if(n){let a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}let c=e.resumeTime;this.timelinePos<c&&(this.log(St("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){let n=e.assetList[i];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){let s=this.schedule;if(!s)return;let i=t.parentIdentifier,n=s.getEvent(i);if(n){let a=s.findEventIndex(i),o=s.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var s;let i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;let n=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&Be(n)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let d=a.event,h=this.playingAsset,u=h?.identifier,g=u?this.getAssetPlayer(u):null;if(g&&u&&(!this.eventItemsMatch(a,n)||t!==void 0&&u!==d.assetList[t].identifier)){var c;let f=d.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${d.assetList.length} ${xt(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:f,event:d,schedule:i.slice(0),scheduleIndex:e,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(d,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(u,n),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${d} ${Be(a)}`),d.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:d,schedule:i.slice(0),scheduleIndex:e}),d.cue.once)){var l;this.updateSchedule();let f=(l=this.schedule)==null?void 0:l.items;if(n&&f){let p=this.findItemIndex(n);this.advanceSchedule(p,f,t,a,o)}return}}this.advanceSchedule(e,i,t,a,o)}advanceSchedule(e,t,s,i,n){let a=this.schedule;if(!a)return;let o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(d=>{let h=d.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 d=o.event;if(s===void 0){s=a.findAssetIndex(d,this.timelinePos);let f=vi(d,s-1);if(d.isAssetPastPlayoutLimit(f)||d.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(d,e,s);return}s=f}let h=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let u=this.preloadAssets(d,s);if(this.eventItemsMatch(o,h||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Be(o)} ${d.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${d}`);return}if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${d}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let g=d.assetList[s];if(!g){this.advanceAfterAssetEnded(d,e,s||0);return}if(u||(u=this.getAssetPlayer(g.identifier)),u===null||u.destroyed){let f=d.assetList.length;this.warn(`asset ${s+1}/${f} player destroyed ${d}`),u=this.createAssetPlayer(d,g,s),u.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(u,s,t,e,c),this.shouldPlay&&Sa(u.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Sa(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.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,s){var i,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Be(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(St("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;let a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Be(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let s=e.start;if(this.primaryLive){let i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let i=this.primaryMedia;if(!i)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(St("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;let i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||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(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let s=this.hls.levels[t.level];if(!s.details)return;let i=te(te({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=te(te({},this.altSelection),{},{audio:s});return}let n=te(te({},i),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=te(te({},this.altSelection),{},{subtitles:s});return}let n=te(te({},i),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){let s=kr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){let s=kr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){let s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){let i=this.timelinePos;this.bufferedPos=i,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 n=t[i];if(n.cue.post){var s;let a=this.schedule.findEventIndex(n.identifier),o=(s=this.schedule.items)==null?void 0:s[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;let i=(s=this.schedule)==null?void 0:s.items;if(e&&i){let n=this.findItemIndex(e,t);return i[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 s=e.end+.25,i=q.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Be(e)} (was ${Be(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;let s=(t=this.schedule)==null?void 0:t.items;if(!s)return;let i=q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){let i=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;let d=this.findItemIndex(n),h=Math.min(d+1,t.length-1),u=t[h];if((c===-1&&n&&e>=n.end||(l=u.event)!=null&&l.appendInPlace&&e+.01>=u.start)&&(c=h),this.isInterstitial(n)){let g=n.event;if(h-o>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,c>d&&c>o)this.bufferedToItem(u);else{let g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&u.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(u)&&this.preloadAssets(u.event,0)}}else s&&a&&!this.itemsMatch(a,n)&&(c===o?this.bufferedToItem(a):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{let n=this.getAssetPlayer(i.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){let{items:i,events:n}=s;if(!i||!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 c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Be(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((d,h)=>{let u=this.getAssetPlayer(d.identifier);u&&(h===l&&u.loadSource(),u.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:i.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 s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;let i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){let s=e.event,i=s.assetList.length===0&&!s.assetListLoader,n=s.cue.once;if(i||!n){let a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let s=e.assetUrl,i=e.assetList.length,n=i===0&&!e.assetListLoader,a=e.cue.once;if(n){let c=e.timelineStart;if(e.appendInPlace){var o;let u=this.playingItem;!this.isInterstitial(u)&&(u==null||(o=u.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,d=0;if(!this.playingItem&&this.primaryLive&&(d=this.hls.startPosition,d===-1&&(d=this.hls.liveSyncPosition||0)),d&&!(e.cue.pre||e.cue.post)){let u=d-c;u>0&&(l=Math.round(u*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${d} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);let h=this.assetListLoader.loadAssetList(e,l);h&&(e.assetListLoader=h)}else if(!a&&i){for(let l=t;l<i;l++){let d=e.assetList[l],h=this.getAssetPlayerQueueIndex(d.identifier);(h===-1||this.playerQueue[h].destroyed)&&!d.error&&this.createAssetPlayer(e,d,l)}let c=e.assetList[t];if(c){let l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;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 s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,n,a){let o={parentIdentifier:e.identifier,identifier:zh(e,a,t),duration:n,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){let i=this.hls,n=i.userConfig,a=n.videoPreference,o=i.loadLevelObj||i.levels[i.currentLevel];(a||o)&&(a=ie({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack],d=0;if(this.primaryLive||e.appendInPlace){let x=this.timelinePos-t.timelineStart;if(x>1){let A=t.duration;A&&x<A&&(d=x)}}let h=t.identifier,u=te(te({},n),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:c||n.audioPreference,subtitlePreference:l||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));let g=u.cmcd;g!=null&&g.sessionId&&g.contentId&&(u.cmcd=ie({},g,{contentId:Bt(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);let f=new An(this.HlsPlayerClass,u,e,t);this.playerQueue.push(f),e.assetList[s]=t;let p=!0,y=x=>{if(x.live){var A;let I=new Error(`Interstitials MUST be VOD assets ${e}`),b={fatal:!0,type:V.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},L=((A=this.schedule)==null?void 0:A.findEventIndex(e.identifier))||-1;this.handleAssetItemError(b,e,L,s,I.message);return}let _=x.edge-x.fragmentStart,S=t.duration;(p||S===null||_>S)&&(p=!1,this.log(`Interstitial asset "${h}" duration change ${S} > ${_}`),t.duration=_,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(x,{details:A})=>y(A)),f.on(m.LEVEL_PTS_UPDATED,(x,{details:A})=>y(A)),f.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(x,A)=>{let _=this.getAssetPlayer(h);if(_&&A.tracks){_.off(m.BUFFER_CODECS,v),_.tracks=A.tracks;let S=this.primaryMedia;this.bufferingAsset===_.assetItem&&S&&!_.media&&this.bufferAssetPlayer(_,S)}};f.on(m.BUFFER_CODECS,v);let E=()=>{var x;let A=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;let _=this.schedule.findEventIndex(e.identifier),S=(x=this.schedule.items)==null?void 0:x[_];this.isInterstitial(S)&&this.advanceAssetBuffering(S,t)};f.on(m.BUFFERED_TO_END,E);let T=x=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;let _=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,_,x)};return f.once(m.MEDIA_ENDED,T(s)),f.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),f.on(m.ERROR,(x,A)=>{if(!this.schedule)return;let _=this.getAssetPlayer(h);if(A.details===R.BUFFER_STALLED_ERROR){if(_!=null&&_.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${A.error} ${e}`)}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;let A=new Error(`Asset player destroyed unexpectedly ${h}`),_={fatal:!0,type:V.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(_,e,this.schedule.findEventIndex(e.identifier),s,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${xt(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){let s=this.getAssetPlayerQueueIndex(e);if(s!==-1){let i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Be(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,n){let{interstitial:a,assetItem:o,assetId:c}=e,l=a.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!d||d.identifier!==c)&&(d&&(this.clearAssetPlayer(d.identifier,s[i]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${xt(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;let{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=a;let l=this.getBufferingPlayer();if(l===e)return;let d=n.appendInPlace;if(d&&l?.interstitial.appendInPlace===!1)return;let h=l?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(d&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(h&&!Ca(h,e.tracks)){let u=new Error(`Asset ${xt(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),g={fatal:!0,type:V.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},f=n.findAssetIndex(a);this.handleAssetItemError(g,n,o,f,u.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,s=this.primaryMedia;if(!t||!s)return;let i=s.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let c=o.currentTime||i-a.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){let d=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,d,n)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,n){if(e.details===R.BUFFER_STALLED_ERROR)return;let a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&xt(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,d=this.schedule.items,h=ie({},e,{fatal:!1,errorAction:It(!0),asset:a,assetListIndex:i,event:t,schedule:d,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;let u=this.playingAsset,g=this.bufferingAsset,f=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=f),!t.assetList.some(p=>!p.error))t.error=f;else for(let p=i;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):u&&u.identifier===o?this.advanceAfterAssetEnded(t,s,i):g&&g.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){let t=e.timelineStart,s=this.effectivePlayingItem,i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Be(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);let a=this.updateItem(s,i);this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;let n=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(n)}onAssetListLoaded(e,t){var s,i;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;let c=n.timelineStart,l=n.duration,d=0;o.forEach((p,y)=>{let v=parseFloat(p.DURATION);this.createAsset(n,y,d,c+d,v,p.URI),d+=v}),n.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${n}`);let h=this.waitingItem,u=h?.event.identifier===a;this.updateSchedule();let g=(i=this.bufferingItem)==null?void 0:i.event;if(u){var f;let p=this.schedule.findEventIndex(a),y=(f=this.schedule.items)==null?void 0:f[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){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(y)}this.setSchedulePosition(p)}else if(g?.identifier===a){let p=n.assetList[0];if(p){let y=this.getAssetPlayer(p.identifier);if(g.appendInPlace){let v=this.primaryMedia;y&&v&&this.bufferAssetPlayer(y,v)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{let s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case R.BUFFER_STALLED_ERROR:{let s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},xa=500,Rn=class extends Yt{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",B.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(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=P.IDLE,this.setInterval(xa),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:s,success:i}=t;if(this.fragContextChanged(s)||(de(s)&&(this.fragPrevious=s),this.state=P.IDLE),!i)return;let n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a,o=s.start;for(let l=0;l<n.length;l++)if(o>=n[l].start&&o<=n[l].end){a=n[l];break}let c=s.start+s.duration;a?a.end=c:(a={start:o,end:c},n.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){let n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(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(s,n,B.SUBTITLE)}}onError(e,t){let s=t.frag;s?.type===B.SUBTITLE&&(t.details===R.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Do(this.levels,t)){this.levels=t.map(s=>new gt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{let i=new gt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,B.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}let i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==P.STOPPED&&this.setInterval(xa)}onSubtitleTrackLoaded(e,t){var s;let{currentTrackId:i,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let c=n[o];if(o>=n.length||!c)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 l=0;if(a.live||(s=c.details)!=null&&s.live){if(a.deltaUpdateFailed)return;let h=this.mainDetails;if(!h){this.startFragRequested=!1;return}let u=h.fragments[0];if(!c.details)a.hasProgramDateTime&&h.hasProgramDateTime?(ws(a,h),l=a.fragmentStart):u&&(l=u.start,Yi(a,l));else{var d;l=this.alignPlaylists(a,c.details,(d=this.levelLastLoaded)==null?void 0:d.details),l===0&&u&&(l=u.start,Yi(a,l))}h&&!this.startFragRequested&&this.setStartPosition(h,l)}c.details=a,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===P.IDLE&&(pt(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:s}=e,i=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&bt(i.method)){let a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,Zn(i.method)).catch(o=>{throw n.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{let c=performance.now();n.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=P.IDLE})}}doTick(){if(!this.media){this.state=P.IDLE;return}if(this.state===P.IDLE){let{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;let{config:i}=this,n=this.getLoadPosition(),a=q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),{end:o,len:c}=a,l=s.details,d=this.hls.maxBufferLength+l.levelTargetDuration;if(c>d)return;let h=l.fragments,u=h.length,g=l.edge,f=null,p=this.fragPrevious;if(o<g){let E=i.maxFragLookUpTolerance,T=o>g-E?0:E;f=pt(p,h,Math.max(h[0].start,o),T),!f&&p&&p.start<h[0].start&&(f=h[0])}else f=h[u-1];if(f=this.filterReplacedPrimary(f,s.details),!f)return;let y=f.sn-l.startSN,v=h[y-1];if(v&&v.cc===f.cc&&this.fragmentTracker.getState(v)===fe.NOT_LOADED&&(f=v),this.fragmentTracker.getState(f)===fe.NOT_LOADED){let E=this.mapToInitFragWhenRequired(f);E&&this.loadFragment(E,s,o)}}}loadFragment(e,t,s){de(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new _n(this.tracksBuffered[this.currentTrackId]||[])}},_n=class{constructor(e){this.buffered=void 0;let t=(s,i,n)=>{if(i=i>>>0,i>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${n})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}},Qh={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},Yo=r=>String.fromCharCode(Qh[r]||r),$e=15,ze=100,Zh={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Jh={17:2,18:4,21:6,22:8,23:10,19:13,20:15},eu={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},tu={25:2,26:4,29:6,30:8,31:10,27:13,28:15},su=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Pn=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let s=typeof t=="function"?t():t;se.log(`${this.time} [${e}] ${s}`)}}},ct=function(e){let t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},Ks=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){let t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){let i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Dn=class{constructor(){this.uchar=" ",this.penState=new Ks}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},kn=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Ks,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ze;t++)this.chars.push(new Dn);this.logger=e}equals(e){for(let t=0;t<ze;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<ze;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<ze;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}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)}moveCursor(e){let t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].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=Yo(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 s=0;s<ze;s++){let i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},$t=class{constructor(e){this.rows=[],this.currRow=$e-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<$e;t++)this.rows.push(new kn(e));this.logger=e}reset(){for(let e=0;e<$e;e++)this.rows[e].clear();this.currRow=$e-1}equals(e){let t=!0;for(let s=0;s<$e;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<$e;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<$e;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 = "+re(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<$e;o++)this.rows[o].clear();let n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[n].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(a.rows[n+l])}}this.currRow=t;let s=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}let i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+re(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=[],s="",i=-1;for(let n=0;n<$e;n++){let a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
30
+ `)),s}getTextAndFormat(){return this.rows}},Vs=class{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new $t(s),this.nonDisplayedMemory=new $t(s),this.lastOutputScreen=new $t(s),this.currRollUpRow=this.displayedMemory.rows[$e-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[$e-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);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 s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+re(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))}},Hs=class{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=nu(),this.logger=void 0;let i=this.logger=new Pn;this.channels=[null,new Vs(e,t,i),new Vs(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){let i=t[s]&127,n=t[s+1]&127,a=!1,o=null;if(i===0&&n===0)continue;this.logger.log(3,()=>"["+ct([t[s],t[s+1]])+"] -> ("+ct([i,n])+")");let c=this.cmdHistory;if(i>=16&&i<=31){if(iu(i,n,c)){ds(null,null,c),this.logger.log(3,()=>"Repeated command ("+ct([i,n])+") is dropped");continue}ds(i,n,this.cmdHistory),a=this.parseCmd(i,n),a||(a=this.parseMidrow(i,n)),a||(a=this.parsePAC(i,n)),a||(a=this.parseBackgroundAttributes(i,n))}else ds(null,null,c);if(!a&&(o=this.parseChars(i,n),o)){let d=this.currentChannel;d&&d>0?this.channels[d].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+ct([i,n])+" orig: "+ct([t[s],t[s+1]]))}}parseCmd(e,t){let s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;let n=e===20||e===21||e===23?1:2,a=this.channels[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 s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+ct([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s,i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(i||n))return!1;let a=e<=23?1:2;t>=64&&t<=95?s=a===1?Zh[e]:eu[e]:s=a===1?Jh[e]:tu[e];let o=this.channels[a];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let s,i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,n=null;if(e>=25?(s=2,n=e-8):(s=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 '"+Yo(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+ct(i).join(",")),i}parseBackgroundAttributes(e,t){let s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=su[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.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}ds(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let s=this.channels[t];s&&s.cueSplitAtTime(e)}}};function ds(r,e,t){t.a=r,t.b=e}function iu(r,e,t){return t.a===r&&t.b===e}function nu(){return{a:null,b:null}}var lr=(function(){if(Cs!=null&&Cs.VTTCue)return self.VTTCue;let r=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;let l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(r,o)}function i(o){return t(e,o)}function n(o,...c){let l=1;for(;l<arguments.length;l++){let d=arguments[l];for(let h in d)o[h]=d[h]}return o}function a(o,c,l){let d=this,h={enumerable:!0};d.hasBeenReset=!1;let u="",g=!1,f=o,p=c,y=l,v=null,E="",T=!0,x="auto",A="start",_=50,S="middle",I=50,b="middle";Object.defineProperty(d,"id",n({},h,{get:function(){return u},set:function(L){u=""+L}})),Object.defineProperty(d,"pauseOnExit",n({},h,{get:function(){return g},set:function(L){g=!!L}})),Object.defineProperty(d,"startTime",n({},h,{get:function(){return f},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");f=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",n({},h,{get:function(){return p},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");p=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",n({},h,{get:function(){return y},set:function(L){y=""+L,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",n({},h,{get:function(){return v},set:function(L){v=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",n({},h,{get:function(){return E},set:function(L){let D=s(L);if(D===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",n({},h,{get:function(){return T},set:function(L){T=!!L,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",n({},h,{get:function(){return x},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");x=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",n({},h,{get:function(){return A},set:function(L){let D=i(L);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");A=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",n({},h,{get:function(){return _},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");_=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",n({},h,{get:function(){return S},set:function(L){let D=i(L);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");S=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",n({},h,{get:function(){return I},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");I=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",n({},h,{get:function(){return b},set:function(L){let D=i(L);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");b=D,this.hasBeenReset=!0}})),d.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})(),Cn=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Wo(r){function e(s,i,n,a){return(s|0)*3600+(i|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 wn=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){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 s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}};function qo(r,e,t,s){let i=s?r.split(s):[r];for(let n in i){if(typeof i[n]!="string")continue;let a=i[n].split(t);if(a.length!==2)continue;let o=a[0],c=a[1];e(o,c)}}var Mn=new lr(0,0,""),hs=Mn.align==="middle"?"middle":"center";function ru(r,e,t){let s=r;function i(){let o=Wo(r);if(o===null)throw new Error("Malformed timestamp: "+s);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,c){let l=new wn;qo(o,function(u,g){let f;switch(u){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===g){l.set(u,t[p].region);break}break;case"vertical":l.alt(u,g,["rl","lr"]);break;case"line":f=g.split(","),l.integer(u,f[0]),l.percent(u,f[0])&&l.set("snapToLines",!1),l.alt(u,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",hs,"end"]);break;case"position":f=g.split(","),l.percent(u,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",hs,"end","line-left","line-right","auto"]);break;case"size":l.percent(u,g);break;case"align":l.alt(u,g,["start",hs,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let d=l.get("line","auto");d==="auto"&&Mn.line===-1&&(d=-1),c.line=d,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",hs);let h=l.get("position","auto");h==="auto"&&Mn.position===50&&(h=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=h}function a(){r=r.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);r=r.slice(3),a(),e.endTime=i(),a(),n(r,e)}function jo(r){return r.replace(/<br(?: \/)?>/gi,`
31
+ `)}var On=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Cn,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 s(){let n=t.buffer,a=0;for(n=jo(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
32
+ `;)++a;let o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
33
+ `&&++a,t.buffer=n.slice(a),o}function i(n){qo(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=s();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=s(),t.state){case"HEADER":/:/.test(n)?i(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 lr(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{ru(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
+ `),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
+
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}},au=/\r\n|\n\r|\n|\r/g,Ei=function(e,t,s=0){return e.slice(s,s+t.length)===t},ou=function(e){let t=parseInt(e.slice(-3)),s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!F(t)||!F(s)||!F(i)||!F(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*n,t};function cr(r,e,t){return Bt(r.toString())+Bt(e.toString())+Bt(t)}var lu=function(e,t,s){let i=e[t],n=e[i.prevCC];if(!n||!n.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=i.start-n.start,i.new=!1,i=n,n=e[i.prevCC]}e.presentationOffset=s};function cu(r,e,t,s,i,n,a){let o=new On,c=ke(new Uint8Array(r)).trim().replace(au,`
37
37
  `).split(`
38
- `),l=[],h=e?wh(e.baseTime,e.timescale):0,d="00:00.000",u=0,f=0,g,p=!0;o.oncue=function(y){let v=t[s],E=t.ccOffset,T=(u-h)/9e4;if(v!=null&&v.new&&(f!==void 0?E=t.ccOffset=v.start:tu(t,s,T)),T){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}E=T-t.presentationOffset}let S=y.endTime-y.startTime,x=_e((y.startTime+E-f)*9e4,i*9e4)/9e4;y.startTime=Math.max(x,0),y.endTime=Math.max(x+S,0);let _=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(_)),y.id||(y.id=ln(y.startTime,y.endTime,_)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){g=y},o.onflush=function(){if(g){a(g);return}r(l)},c.forEach(y=>{if(p)if(vi(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(v=>{vi(v,"LOCAL:")?d=v.slice(6):vi(v,"MPEGTS:")&&(u=parseInt(v.slice(7)))});try{f=eu(d)/1e3}catch(v){g=v}return}else y===""&&(p=!1);o.parse(y+`
39
- `)}),o.flush()}var Ei="stpp.ttml.im1t",Wo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,qo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,iu={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ta(n,e,t,s){let i=X(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}let r=i.map(o=>Pe(o)),a=Ch(e.baseTime,1,e.timescale);try{r.forEach(o=>t(ru(o,a)))}catch(o){s(o)}}function ru(n,e){let i=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(r).reduce((d,u)=>(d[u]=i.getAttribute(`ttp:${u}`)||r[u],d),{}),o=i.getAttribute("xml:space")!=="preserve",c=Sa(Ti(i,"styling","style")),l=Sa(Ti(i,"layout","region")),h=Ti(i,"body","[begin]");return[].map.call(h,d=>{let u=jo(d,o);if(!u||!d.hasAttribute("begin"))return null;let f=xi(d.getAttribute("begin"),a),g=xi(d.getAttribute("dur"),a),p=xi(d.getAttribute("end"),a);if(f===null)throw xa(d);if(p===null){if(g===null)throw xa(d);p=f+g}let y=new on(f-e,p-e,u);y.id=ln(y.startTime,y.endTime,y.text);let v=l[d.getAttribute("region")],E=c[d.getAttribute("style")],T=nu(v,E,c),{textAlign:S}=T;if(S){let x=iu[S];x&&(y.lineAlign=x),y.align=S}return ie(y,T),y}).filter(d=>d!==null)}function Ti(n,e,t){let s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Sa(n){return n.reduce((e,t)=>{let s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function jo(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
40
- `:(r=s.childNodes)!=null&&r.length?jo(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function nu(n,e,t){let s="http://www.w3.org/ns/ttml#styling",i=null,r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),r.reduce((o,c)=>{let l=Si(e,s,c)||Si(n,s,c)||Si(i,s,c);return l&&(o[c]=l),o},{})}function Si(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function xa(n){return new Error(`Could not parse ttml timestamp ${n}`)}function xi(n,e){if(!n)return null;let t=Vo(n);return t===null&&(Wo.test(n)?t=au(n,e):qo.test(n)&&(t=ou(n,e))),t}function au(n,e){let t=Wo.exec(n),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function ou(n,e){let t=qo.exec(n),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}var At=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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Mr=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=La(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new At(this,"textTrack1"),t=new At(this,"textTrack2"),s=new At(this,"textTrack3"),i=new At(this,"textTrack4");this.cea608Parser1=new Vs(1,e,t),this.cea608Parser2=new Vs(3,s,i)}addCues(e,t,s,i,r){let a=!1;for(let o=r.length;o--;){let c=r[o],l=lu(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),a=!0,l/(s-t)>.5))return}if(a||r.push([t,s]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{let o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:a}){let{unparsedVttFrags:o}=this;s===N.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,c):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){let r=s.textTracks[i];if(Aa(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:a}=t[e],o=this.getExistingTrack(r,a);if(o)s[e]=o,xt(s[e]),Uo(s[e],i);else{let c=this.createTextTrack("captions",r,a);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){let i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let s=!!t.transferMedia;if(this.media=null,s)return;let{captionsTracks:i}=this;Object.keys(i).forEach(r=>{xt(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=La(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let s=0;s<t.length;s++)xt(t[s])}onSubtitleTracksUpdated(e,t){let s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Ei);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Ro(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){let a=this.media,o=a?vs(a.textTracks):null;if(this.tracks.forEach((c,l)=>{let h;if(o){let d=null;for(let u=0;u<o.length;u++)if(o[u]&&Aa(o[u],c)){d=o[u],o[u]=null;break}d&&(h=d)}if(h)xt(h);else{let d=zo(c);h=this.createTextTrack(d,c.name,c.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){let c=o.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{let i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;let r=`textTrack${i[1]}`,a=this.captionsProperties[r];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===N.MAIN){var s,i;let{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&a&&(l!==o+1||l===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){let{frag:s,payload:i}=t;if(s.type===N.SUBTITLE)if(i.byteLength){let r=s.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){let o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Ei?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let s=this.hls;Ta(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;let{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[s.cc]&&o===-1){a.push(e);return}let c=this.hls,l=(t=s.initSegment)!=null&&t.data?we(s.initSegment.data,new Uint8Array(i)).buffer:i;su(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{let d=h.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${h}`),!(d&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){let s=this.tracks[e.level];s.textCodec||Ta(t,this.initPTS[e.cc],()=>{s.textCodec=Ei,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){let s=this.hls;if(this.config.renderTextTracksNatively){let i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>$o(i,r))}else{let i=this.tracks[t];if(!i)return;let r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){let{frag:s}=t;s.type===N.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:s,samples:i}=t;if(!(s.type===N.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){let a=i[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){let{media:a}=this;if(!(!a||a.currentTime<s)){if(!r||r==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(c=>vr(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(c=>vr(o[c],t,i))}}}extractCea608Data(e){let t=[[],[]],s=e[0]&31,i=2;for(let r=0;r<s;r++){let a=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&a)!==0){let h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(c))}}return t}};function zo(n){return n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function Aa(n,e){return!!n&&n.kind===zo(e)&&ar(e,n)}function lu(n,e,t,s){return Math.min(e,s)-Math.max(n,t)}function La(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var cu=/\s/,hu={newCue(n,e,t,s){let i=[],r,a,o,c,l,h=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(r=s.rows[u],o=!0,c=0,l="",!r.isEmpty()){var d;for(let p=0;p<r.chars.length;p++)cu.test(r.chars[p].uchar)&&o?c++:(l+=r.chars[p].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;let f=Yo(l.trim()),g=ln(e,t,f);n!=null&&(d=n.cues)!=null&&d.getCueById(g)||(a=new h(e,t,f),a.id=g,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),i.forEach(u=>$o(n,u))),i}};function du(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var uu=/(\d+)-(\d+)\/(\d+)/,Hs=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||pu,this.controller=new self.AbortController,this.stats=new Ut}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){let i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();let r=fu(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&O(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(jt(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var u;this.response=this.loader=d;let f=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(f-i.loading.start)),!d.ok){let{status:p,statusText:y}=d;throw new Or(y||"fetch, bad network response",p,d)}i.loading.first=f,i.total=mu(d.headers)||i.total;let g=(u=this.callbacks)==null?void 0:u.onProgress;return g&&O(t.highWaterMark)?this.loadProgressively(d,i,e,t.highWaterMark,g):a?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var u,f;let g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);let p=d[o];p&&(i.loaded=i.total=p);let y={url:g.url,data:d,code:g.status},v=(u=this.callbacks)==null?void 0:u.onProgress;v&&!O(t.highWaterMark)&&v(i,e,d,g),(f=this.callbacks)==null||f.onSuccess(y,i,e,g)}).catch(d=>{var u;if(self.clearTimeout(this.requestTimeout),i.aborted)return;let f=d&&d.code||0,g=d?d.message:null;(u=this.callbacks)==null||u.onError({code:f,text:g},e,d?d.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,s,i=0,r){let a=new ws,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return a.dataLength&&r(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let h=l.value,d=h.length;return t.loaded+=d,d<i||a.dataLength?(a.push(h),a.dataLength>=i&&r(t,s,a.flush().buffer,e)):r(t,s,h.buffer,e),c()}).catch(()=>Promise.reject());return c()}};function fu(n,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ie({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function gu(n){let e=uu.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function mu(n){let e=n.get("Content-Range");if(e){let s=gu(e);if(O(s))return s}let t=n.get("Content-Length");if(t)return parseInt(t)}function pu(n,e){return new self.Request(n.url,e)}var Or=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},yu=/^age:\s*[\d.]+\s*$/im,Ys=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ut,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;let r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);let i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(let o in i)e.setRequestHeader(o,i[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),s.timeout=r&&O(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:s}=this;if(!e||!t)return;let i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){let g=h??t.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);let p=t.responseType==="arraybuffer"?g.byteLength:g.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);let y=(a=this.callbacks)==null?void 0:a.onProgress;y&&y(s,e,g,t);let v={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}let d=r.loadPolicy.errorRetry,u=s.retry,f={url:e.url,data:void 0,code:l};if(Rs(d,u,!1,f))this.retry(d);else{var c;se.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Rs(e,t,!0))this.retry(e);else{var s;se.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);let i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:s}=this;this.retryDelay=zr(e,s.retry),s.retry++,se.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&yu.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}},vu={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Eu=te(te({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Ys,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Ci,bufferController:hr,capLevelController:dr,errorController:Mi,fpsController:yr,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Za,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:vu},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},Tu()),{},{subtitleStreamController:Ir,subtitleTrackController:Er,timelineController:Mr,audioStreamController:nr,audioTrackController:or,emeController:Us,cmcdController:mr,contentSteeringController:pr,interstitialsController:Lr});function Tu(){return{cueHandler:hu,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 Su(n,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"');let s=Fr(n),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,c=e[o]===void 0,l=[];r.forEach(h=>{let d=`${a}Loading${h}`,u=e[d];if(u!==void 0&&c){l.push(d);let f=s[o].default;switch(e[o]={default:f},h){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}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ne(e[o])}`)}),te(te({},s),e)}function Fr(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(Fr):Object.keys(n).reduce((e,t)=>(e[t]=Fr(n[t]),e),{}):n}function xu(n,e){let t=n.loader;t!==Hs&&t!==Ys?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):du()&&(n.loader=Hs,n.progressive=!0,n.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Es=2,Au=.1,Lu=.05,Iu=100,Nr=class extends _s{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.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(Iu),this.mediaSource=t.mediaSource;let s=this.media=t.media;xe(s,"playing",this.onMediaPlaying),xe(s,"waiting",this.onMediaWaiting),xe(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:s}=this;s&&(Le(s,"playing",this.onMediaPlaying),Le(s,"waiting",this.onMediaWaiting),Le(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;let r=(s=this.hls)==null?void 0:s.config;if(!r)return;let a=this.media;if(!a)return;let{seeking:o}=a,c=this.seeking&&!o,l=!this.seeking&&o,h=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!q.getBuffered(a).length){this.nudgeRetry=0;return}let d=q.bufferInfo(a,e,0),u=d.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){let _=Ia(this.hls.inFlightFragments,e),A=d.len>Es,R=!u||_||u-e>Es&&!f.getPartialFragment(e);if(A||R)return;this.moved=!1}let g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(d.len>0)&&!u)return;let A=Math.max(u,d.start||0)-e,b=!!(g!=null&&g.live)?g.targetduration*2:Es,L=ds(e,f);if(A>0&&(A<=b||L)){a.paused||this._trySkipBufferHole(L);return}}let p=r.detectStallWithCurrentTimeMs,y=self.performance.now(),v=this.waiting,E=this.stalled;if(E===null)if(v>0&&y-v<p)E=this.stalled=v;else{this.stalled=y;return}let T=y-E;if(!o&&(T>=p||v)&&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(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}let x=q.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(x,T,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;let i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){let r=q.bufferedInfo(q.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){let a=q.timeRangesToArray(i),o=q.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let c=q.bufferedInfo(a,e,0).bufferedIndex,l=a[o].end,h=a[o+1].start;if((c===-1||c>o)&&h-l<1&&e-l<2){let d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${h} buffered index: ${c}`);this.warn(d.message),this.media.currentTime+=1e-6;let u=ds(e,this.fragmentTracker);u&&"fragment"in u?u=u.fragment:u||(u=void 0);let f=q.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:u,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var i,r;let{fragmentTracker:a,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!a||!c)return;let l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=ds(s,a);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;let d=e.buffered,u=this.adjacentTraversal(e,s);(d&&d.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||u))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let s=this.fragmentTracker,i=e.nextStart;if(s&&i){let r=s.getFragAtPos(t,N.MAIN),a=s.getFragAtPos(i,N.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(e){let{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ne(e)})`);this.warn(a.message),t.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;let{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;let a=i.currentTime,o=q.bufferInfo(i,a,0),c=a<o.start?o.start:o.nextStart;if(c&&this.hls){let h=o.len<=r.maxBufferHole,d=o.len>0&&o.len<1&&i.readyState<3,u=c-a;if(u>0&&(h||d)){if(u>r.maxBufferHole){let g=!1;if(a===0){let p=s.getAppendedFrag(0,N.MAIN);p&&c<p.end&&(g=!0)}if(!g&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Ia(this.hls.inFlightFragments,c))return 0;let y=!1,v=e.end;for(;v<c;){let E=ds(v,s);if(E)v+=E.duration;else{y=!0;break}}if(y)return 0}}let f=Math.max(c+Lu,a+Au);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,i.currentTime=f,!(e!=null&&e.gap)){let g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:K.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:s,nudgeRetry:i}=this,r=t?.config;if(!s||!r)return 0;let a=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){let o=a+(i+1)*r.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Ia(n,e){let t=ba(n.main);if(t&&t.start<=e)return t;let s=ba(n.audio);return s&&s.start<=e?s:null}function ba(n){if(!n)return null;switch(n.state){case D.IDLE:case D.STOPPED:case D.ENDED:case D.ERROR:return null}return n.frag}function ds(n,e){return e.getAppendedFrag(n,N.MAIN)||e.getPartialFragment(n)}var bu=.25;function Br(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Ai(n,e,t,s,i){let r=new n(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new n(e,t,ne(i?te({type:i},s):s))}return r}var us=(()=>{let n=Br();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Ur=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(m.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(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}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.removeCues&&xt(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Uo(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;let{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=Br();if(a)for(let o=0;o<r.length;o++){let c=r[o].type;if(c===De.emsg&&!s||!i)continue;let l=po(r[o].data),h=r[o].pts,d=h+r[o].duration;d>us&&(d=us),d-h<=0&&(d=h+bu);for(let f=0;f<l.length;f++){let g=l[f];if(!yo(g)){this.updateId3CueEnds(h,c);let p=Ai(a,h,d,g,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;let i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){let a=i[r];a.type===t&&a.startTime<e&&a.endTime===us&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){let{id3Track:r,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=a;if(r&&(o||c)){let l;i==="audio"?l=h=>h.type===De.audioId3&&c:i==="video"?l=h=>h.type===De.emsg&&o:l=h=>h.type===De.audioId3&&c||h.type===De.emsg&&o,vr(r,t,s,l)}}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:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;let o=Br();if(s&&i&&!a){let{fragmentStart:p,fragmentEnd:y}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=y):o&&(v=this.assetCue=Ai(o,p,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:c}=this,{dateRanges:l}=e,h=Object.keys(l),d=this.dateRangeCuesAppended;if(c&&t){var u;if((u=c.cues)!=null&&u.length){let p=Object.keys(d).filter(y=>!h.includes(y));for(let y=p.length;y--;){var f;let v=p[y],E=(f=d[v])==null?void 0:f.cues;delete d[v],E&&Object.keys(E).forEach(T=>{let S=E[T];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(S)}catch{}}})}}else d=this.dateRangeCuesAppended={}}let g=e.fragments[e.fragments.length-1];if(!(h.length===0||!O(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<h.length;p++){let y=h[p],v=l[y],E=v.startTime,T=d[y],S=T?.cues||{},x=T?.durationKnown||!1,_=us,{duration:A,endDate:R}=v;if(R&&A!==null)_=E+A,x=!0;else if(v.endOnNext&&!x){let L=h.reduce((P,M)=>{if(M!==v.id){let B=l[M];if(B.class===v.class&&B.startDate>v.startDate&&(!P||v.startDate<P.startDate))return B}return P},null);L&&(_=L.startTime,x=!0)}let b=Object.keys(v.attr);for(let L=0;L<b.length;L++){let P=b[L];if(!kc(P))continue;let M=S[P];if(M)x&&!(T!=null&&T.durationKnown)?M.endTime=_:Math.abs(M.startTime-E)>.01&&(M.startTime=E,M.endTime=_);else if(o){let B=v.attr[P];Cc(P)&&(B=Pa(B));let U=Ai(o,E,_,{key:P,data:B},De.dateRange);U&&(U.id=y,this.id3Track.addCue(U),S[P]=U,a&&(P==="X-ASSET-LIST"||P==="X-ASSET-URL")&&U.addEventListener("enter",this.onEventCueEnter))}}d[y]={cues:S,dateRange:v,durationKnown:x}}}}},$r=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;let i=this.computeLatency();if(i===null)return;this._latency=i;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:a}=this.config;if(!r||a===1||!s.live)return;let o=this.targetLatency;if(o===null)return;let c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){let d=Math.min(2,Math.max(1,a)),u=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,f=Math.min(d,Math.max(1,u));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,c=this.hls.userConfig,l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:a*i);let h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let s=this.levelDetails;if(s===null)return null;let i=s.edge,r=e-t-this.edgeStalled,a=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,r),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.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 s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===I.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.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}},Gr=class extends zt{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let s=this.hls.config.preferManagedMediaSource,i=[],r={},a={},o=!1,c=!1,l=!1;t.levels.forEach(h=>{let d=h.attrs,{audioCodec:u,videoCodec:f}=h;u&&(h.audioCodec=u=xs(u,s)||void 0),f&&(f=h.videoCodec=tc(f));let{width:g,height:p,unknownCodecs:y}=h,v=y?.length||0;if(o||(o=!!(g&&p)),c||(c=!!f),l||(l=!!u),v||u&&!this.isAudioSupported(u)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}let{CODECS:E,"FRAME-RATE":T,"HDCP-LEVEL":S,"PATHWAY-ID":x,RESOLUTION:_,"VIDEO-RANGE":A}=d,b=`${`${x||"."}-`}${h.bitrate}-${_}-${T}-${E}-${A}-${S}`;if(r[b])if(r[b].uri!==h.url&&!h.attrs["PATHWAY-ID"]){let L=a[b]+=1;h.attrs["PATHWAY-ID"]=new Array(L+1).join(".");let P=this.createLevel(h);r[b]=P,i.push(P)}else r[b].addGroupId("audio",d.AUDIO),r[b].addGroupId("text",d.SUBTITLES);else{let L=this.createLevel(h);r[b]=L,a[b]=1,i.push(L)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){let t=new ft(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){let i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=Ga(i,[])}return t}isAudioSupported(e){return $t(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return $t(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var a;let o=[],c=[],l=e,h=((a=t.stats)==null?void 0:a.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:E,videoRange:T,width:S,height:x})=>(!!E||!!(S&&x))&&dc(T))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let E="no level with compatible codecs found in manifest",T=E;t.levels.length&&(T=`one or more CODECS in variant not supported: ${ne(t.levels.map(x=>x.attrs.CODECS).filter((x,_,A)=>A.indexOf(x)===_))}`,this.warn(T),E+=` (${T})`);let S=new Error(E);this.hls.trigger(m.ERROR,{type:K.MEDIA_ERROR,details:I.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:T})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(E=>!E.audioCodec||this.isAudioSupported(E.audioCodec)),Ra(o)),t.subtitles&&(c=t.subtitles,Ra(c));let d=l.slice(0);l.sort((E,T)=>{if(E.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(E.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&E.height!==T.height)return E.height-T.height;if(E.frameRate!==T.frameRate)return E.frameRate-T.frameRate;if(E.videoRange!==T.videoRange)return As.indexOf(E.videoRange)-As.indexOf(T.videoRange);if(E.videoCodec!==T.videoCodec){let S=An(E.videoCodec),x=An(T.videoCodec);if(S!==x)return x-S}if(E.uri===T.uri&&E.codecSet!==T.codecSet){let S=Ss(E.codecSet),x=Ss(T.codecSet);if(S!==x)return x-S}return E.averageBitrate!==T.averageBitrate?E.averageBitrate-T.averageBitrate:0});let u=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length)){for(let E=0;E<d.length;E++)if(d[E].pathwayId===l[0].pathwayId){u=d[E];break}}this._levels=l;for(let E=0;E<l.length;E++)if(l[E]===u){var f;this._firstLevel=E;let T=u.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){let x=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);x>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=x)}break}let g=r&&!i,p=this.hls.config,y=!!(p.audioStreamController&&p.audioTrackController),v={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:y&&!g&&o.some(E=>!!E.url)};h.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,v)}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 h=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(m.ERROR,{type:K.OTHER_ERROR,details:I.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:h,reason:h.message}),d)return;e=Math.min(e,t.length-1)}let s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&i&&r===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 ${s}${r?" with Pathway "+r:""}`);let c={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(m.LEVEL_SWITCHING,c);let l=a.details;if(!l||l.live){let h=this.switchParams(a.uri,i?.details,l);this.loadPlaylist(h)}}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(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===Q.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===N.MAIN){let s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;let i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;let{level:i,details:r}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,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){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let s=this._levels.filter((r,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));ao(s),this._levels=s,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 i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}};function Ra(n){let e={};n.forEach(t=>{let s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Xo(){return self.SourceBuffer||self.WebKitSourceBuffer}function Qo(){if(!st())return!1;let e=Xo();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Ru(){if(!Qo())return!1;let n=st();return typeof n?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(Gt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(Gt(e,"audio"))))}function _u(){var n;let e=Xo();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}var Du=100,Kr=class extends Ht{constructor(e,t,s){super(e,t,s,"stream-controller",N.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let i=this.media,r=i?i.currentTime:null;if(r===null||!O(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;let a=this.getFwdBufferInfoAtPos(i,r,N.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(Du),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=D.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=D.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case D.WAITING_LEVEL:{let{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=D.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=D.IDLE;break}break}case D.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===D.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:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;let a=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;let c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){let p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=D.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;let l=a.details;if(!l||this.state===D.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=D.WAITING_LEVEL,this.startFragRequested=!1;return}let h=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let u=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&ce(f)&&this.fragmentTracker.getState(f)!==de.OK){var g;let y=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,v=l.fragments[y-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,u)){if(!f.gap){let y=this.audioOnly&&!this.altAudio?re.AUDIO:re.VIDEO,v=(y===re.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,N.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,N.MAIN,d)}f&&(this.exceedsMaxBuffer(o,d,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,u)))}loadFragment(e,t,s){let i=this.fragmentTracker.getState(e);i===de.NOT_LOADED||i===de.PARTIAL?ce(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,N.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let s,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);let r=this.getLevelDetails();if(r!=null&&r.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;let a=this.getBufferedFrag(t.currentTime+s);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,h=Math.max(a.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case D.KEY_LOADING:case D.FRAG_LOADING:case D.FRAG_LOADING_WAITING_RETRY:case D.PARSING:case D.PARSED:this.state=D.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let s=t.media;xe(s,"playing",this.onMediaPlaying),xe(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:s}=this;s&&(Le(s,"playing",this.onMediaPlaying),Le(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){let a=t.levels[r].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!_u(),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:s}=this;if(!s||this.state!==D.IDLE)return;let i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=D.WAITING_LEVEL)}onLevelLoaded(e,t){var s;let{levels:i,startFragRequested:r}=this,a=t.level,o=t.details,c=o.totalduration;if(!i){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:${c}`);let l=t.levelInfo,h=this.fragCurrent;h&&(this.state===D.FRAG_LOADING||this.state===D.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(o.live||(s=l.details)!=null&&s.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,d),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:a}),this.state===D.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=D.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:s}=this;if(!s)return;let i=this.hls.liveSyncPosition,r=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,c=r>=a-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!c)){let h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;let d=q.bufferInfo(s,i,0);if(!((l=d.buffered)!=null&&l.length)){s.currentTime=i;return}if(d.start<=r){s.currentTime=i;return}let{nextStart:f}=q.bufferedInfo(d.buffered,r,0);f&&(s.currentTime=f)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:i,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}let c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}let l=o.videoCodec,h=c.PTSKnown||!c.live,d=(t=s.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Ns(this.hls,N.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,p=g!==-1,y=new Vt(s.level,s.sn,s.stats.chunkCount,r.byteLength,g,p),v=this.initPTS[s.cc];f.push(r,d,u,l,s,i,c.totalduration,h,y,v)}onAudioTrackSwitching(e,t){let s=this.hls,i=this.altAudio!==0;if(Is(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let 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(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let s=Is(t.url,this.hls);if(s){let i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){let s=t.tracks,i,r,a=!1;for(let o in s){let c=s[o];if(c.id==="main"){if(r=o,i=c,o==="video"){let l=s[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:s,part:i}=t,r=s.type===N.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===D.PARSED&&(this.state=D.IDLE);return}let o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),ce(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}let a=this.media;a&&(!this._hasEnoughToStart&&q.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=D.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(N.MAIN,t);break;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===D.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Q.LEVEL&&(this.state=D.IDLE);break;case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case I.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 I.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=D.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==re.AUDIO||!this.altAudio){let s=(t===re.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,N.MAIN),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,s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}let i=this.timelineOffset;i&&s&&(s+=i);let r=this.getLevelDetails(),a=q.getBuffered(e),o=a.length?a.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_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(s=>{let{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=D.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===D.STOPPED||this.state===D.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}let{frag:o,part:c,level:l}=a,{video:h,text:d,id3:u,initSegment:f}=i,{details:g}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=D.PARSING,f){let y=f.tracks;if(y){let S=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,y,S,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:y})}let v=f.initPTS,E=f.timescale,T=this.initPTS[o.cc];if(O(v)&&(!T||T.baseTime!==v||T.timescale!==E)){let S=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:E,trackId:S},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:E,trackId:S})}}if(h&&g){p&&h.type==="audiovideo"&&this.logMuxedErr(o);let y=g.fragments[o.sn-1-g.startSN],v=o.sn===g.startSN,E=!y||o.cc>y.cc;if(i.independent!==!1){let{startPTS:T,endPTS:S,startDTS:x,endDTS:_}=h;if(c)c.elementaryStreams[h.type]={startPTS:T,endPTS:S,startDTS:x,endDTS:_};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!E&&(this.couldBacktrack=!0),h.dropped&&h.independent){let A=this.getMainFwdBufferInfo(),R=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,b=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!v&&R<b-this.config.maxBufferHole&&!E){this.backtrack(o);return}else E&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,S,o.start,_,!0)}else v&&T-(g.appliedTimelineOffset||0)>Es&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,S,x,_),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,r,v||E)}else if(v||E)o.gap=!0;else{this.backtrack(o);return}}if(p){let{startPTS:y,endPTS:v,startDTS:E,endDTS:T}=p;c&&(c.elementaryStreams[re.AUDIO]={startPTS:y,endPTS:v,startDTS:E,endDTS:T}),o.setElementaryStreamInfo(re.AUDIO,y,v,E,T),this.bufferFragmentData(p,o,c,r)}if(g&&u!=null&&u.samples.length){let y={id:t,frag:o,details:g,samples:u.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(g&&d){let y={id:t,frag:o,details:g,samples:d.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${ce(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==D.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));let{audio:r,video:a,audiovideo:o}=t;if(r){let l=e.audioCodec,h=fs(r.codec,l);h==="mp4a"&&(h="mp4a.40.5");let d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");let u=r.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),l&&l!==h&&this.log(`Swapping manifest audio codec "${l}" for "${h}"`),r.levelCodec=h,r.id=N.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=N.MAIN;let l=a.codec;if(l?.length===4)switch(l){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||""}/${l}]${a.codec!==l?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let c=Object.keys(t);if(c.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{let d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:d,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,N.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.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=D.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let s=e.currentTime;if(q.isBuffered(e,s)?t=this.getAppendedFrag(s):q.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;let i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:r}))}}}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 O(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(O(t)){let s=this.getLevelDetails(),i=this.currentFrag||(s?gt(null,s.fragments,t):null);if(i){let r=i.programDateTime;if(r!==null){let a=r+(t-i.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}},Vr=class extends Ie{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let s in this.keyIdToKeyInfo){let i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=I.KEY_LOAD_ERROR,s,i,r){return new Be({type:K.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){let a=t[i];if(e.cc<=a.cc&&(!ce(e)||!ce(a)||e.sn<a.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let c=ms(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){let i=Mt(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);let r=e.decryptdata;if(!r){let l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,l))}let a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=Li(r),c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{let{keyInfo:d}=h;return r.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+ye(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){let s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){let a=Vl(t.initSegment.data);if(a.length){let o=a[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${ye(o)}`),Dt.setKeyIdForUri(e.decryptdata.uri,o)):(o=Dt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${ye(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!ce(t))return Promise.resolve(s);let r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){let s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{let c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,g,p)=>{let{frag:y,keyInfo:v}=g,E=Li(v.decryptdata);if(!y.decryptdata||v!==this.keyIdToKeyInfo[E])return o(this.createKeyLoadError(y,I.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=y.decryptdata.key=new Uint8Array(u.data),y.keyLoader=null,v.loader=null,a({frag:y,keyInfo:v})},onError:(u,f,g,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,I.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),g,te({url:c.url,data:void 0},u)))},onTimeout:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,I.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,I.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};r.load(c,h,d)})}resetLoader(e){let{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);let a=Li(s.decryptdata)||i;delete this.keyIdToKeyInfo[a],r&&r.destroy()}};function Li(n){if(n.keyFormat!==ve.FAIRPLAY){let e=n.keyId;if(e)return ye(e)}return n.uri}function _a(n){let{type:e}=n;switch(e){case Q.AUDIO_TRACK:return N.AUDIO;case Q.SUBTITLE_TRACK:return N.SUBTITLE;default:return N.MAIN}}function Ii(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Hr=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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,a=new r(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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Q.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:s,level:i,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Q.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){let{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let s=this.loaders[Q.LEVEL];if(s){let i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[Q.LEVEL])}}load(e){var t;let s=this.hls.config,i=this.getInternalLoader(e);if(i){let l=this.hls.logger,h=i.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===Q.MANIFEST?r=s.manifestLoadPolicy.default:r=ie({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),O((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Q.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Q.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Q.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){let h=l.partTarget,d=l.targetduration;if(h&&d){let u=Math.max(h*3,d*.8)*1e3;r=ie({},r,{maxTimeToFirstByteMs:Math.min(u,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,r.maxTimeToFirstByteMs)})}}}let a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(l,h,d,u)=>{let f=this.getInternalLoader(d);this.resetInternalLoader(d.type);let g=l.data;h.parsing.start=performance.now(),ht.isMediaPlaylist(g)||d.type!==Q.MANIFEST?this.handleTrackOrLevelPlaylist(l,h,d,u||null,f):this.handleMasterPlaylist(l,h,d,u)},onError:(l,h,d,u)=>{this.handleNetworkError(h,d,!1,l,u)},onTimeout:(l,h,d)=>{this.handleNetworkError(h,d,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){let r=this.hls,a=e.data,o=Ii(e,s),c=ht.parseMasterPlaylist(a,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}let{contentSteering:l,levels:h,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g}=c;this.variableList=g,h.forEach(E=>{let{unknownCodecs:T}=E;if(T){let{preferManagedMediaSource:S}=this.hls.config,{audioCodec:x,videoCodec:_}=E;for(let A=T.length;A--;){let R=T[A];$t(R,"audio",S)?(E.audioCodec=x=x?`${x},${R}`:R,_t.audio[x.substring(0,4)]=2,T.splice(A,1)):$t(R,"video",S)&&(E.videoCodec=_=_?`${_},${R}`:R,_t.video[_.substring(0,4)]=2,T.splice(A,1))}}});let{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=ht.parseMasterPlaylistMedia(a,o,c);p.length&&!p.some(T=>!T.url)&&h[0].audioCodec&&!h[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 ae({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:y,captions:v,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,r){let a=this.hls,{id:o,level:c,type:l}=s,h=Ii(e,s),d=O(c)?c:O(o)?o:0,u=_a(s),f=ht.parseLevelPlaylist(e.data,h,d,u,0,this.variableList);if(l===Q.MANIFEST){let g={attrs:new ae({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+io(f,0),a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:K.NETWORK_ERROR,details:I.MANIFEST_PARSING_ERROR,fatal:t.type===Q.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Q.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Q.AUDIO_TRACK||e.type===Q.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=I.UNKNOWN,l=!1,h=this.getInternalLoader(e);switch(e.type){case Q.MANIFEST:c=s?I.MANIFEST_LOAD_TIMEOUT:I.MANIFEST_LOAD_ERROR,l=!0;break;case Q.LEVEL:c=s?I.LEVEL_LOAD_TIMEOUT:I.LEVEL_LOAD_ERROR,l=!1;break;case Q.AUDIO_TRACK:c=s?I.AUDIO_TRACK_LOAD_TIMEOUT:I.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Q.SUBTITLE_TRACK:c=s?I.SUBTITLE_TRACK_LOAD_TIMEOUT:I.SUBTITLE_LOAD_ERROR,l=!1;break}h&&this.resetInternalLoader(e.type);let d={type:K.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){let u=t?.url||e.url;d.response=te({url:u,data:void 0},i)}this.hls.trigger(m.ERROR,d)}handlePlaylistLoaded(e,t,s,i,r,a){let o=this.hls,{type:c,level:l,levelOrTrack:h,id:d,groupId:u,deliveryDirectives:f}=i,g=Ii(t,i),p=_a(i),y=typeof i.level=="number"&&p===N.MAIN?l:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:K.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:v,reason:v.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){let E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:K.NETWORK_ERROR,details:I.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Q.MANIFEST:case Q.LEVEL:if(y){if(!h)y=0;else if(h!==o.levels[y]){let E=o.levels.indexOf(h);E>-1&&(y=E)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:y||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:c===Q.MANIFEST});break;case Q.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:f});break;case Q.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:f});break}}},We=class n{static get version(){return Yt}static isMSESupported(){return Qo()}static isSupported(){return Ru()}static getMediaSource(){return st()}static get Events(){return m}static get MetadataSchema(){return De}static get ErrorTypes(){return K}static get ErrorDetails(){return I}static get DefaultConfig(){return n.defaultConfig?n.defaultConfig:Eu}static set DefaultConfig(e){n.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new 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.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=Cl(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Su(n.DefaultConfig,e,t);this.userConfig=e,s.progressive&&xu(s,t);let{abrController:i,bufferController:r,capLevelController:a,errorController:o,fpsController:c}=s,l=new o(this),h=this.abrController=new i(this),d=new Oi(this),u=s.interstitialsController,f=u?this.interstitialsController=new u(this,n):null,g=this.bufferController=new r(this,d),p=this.capLevelController=new a(this),y=new c(this),v=new Hr(this),E=s.contentSteeringController,T=E?new E(this):null,S=this.levelController=new Gr(this,T),x=new Ur(this),_=new Vr(this.config,this.logger),A=this.streamController=new Kr(this,d,_),R=this.gapController=new Nr(this,d);p.setStreamController(A),y.setStreamController(A);let b=[v,S,A];f&&b.splice(1,0,f),T&&b.splice(1,0,T),this.networkControllers=b;let L=[h,g,R,p,y,x,d];this.audioTrackController=this.createController(s.audioTrackController,b);let P=s.audioStreamController;P&&b.push(this.audioStreamController=new P(this,d,_)),this.subtitleTrackController=this.createController(s.subtitleTrackController,b);let M=s.subtitleStreamController;M&&b.push(this.subtititleStreamController=new M(this,d,_)),this.createController(s.timelineController,L),_.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController($r,L),this.coreComponents=L,b.push(l);let B=l.onErrorOut;typeof B=="function"&&this.on(m.ERROR,B,l),this.on(m.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){let s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;let i=e===m.ERROR;this.trigger(m.ERROR,{type:K.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(m.ERROR,{type:K.OTHER_ERROR,details:I.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(m.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,s=this._url,i=this._url=Yr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.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 s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}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}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={[N.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[N.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[N.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Gd()),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=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){hc(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 s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this,i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){let a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((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 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(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){let s=Ha(t);return Ka(e,s,navigator.mediaCapabilities)}};We.defaultConfig=void 0;function Pu(n){return/\.m3u8($|\?)/i.test(n)}var zs=class{constructor(e,t,s,i={}){this.video=e;this.emitter=t;this.hlsConfig=s;this.callbacks=i;this.hls=null;this.currentSrc=""}load(e){if(this.detachHls(),this.currentSrc=e,Pu(e)){if(We.isSupported()){this.hls=new We(this.hlsConfig),this.hls.on(We.Events.ERROR,(t,s)=>{if(s.fatal)switch(s.type){case We.ErrorTypes.NETWORK_ERROR:this.emitter.emit("error",{type:"hls-network",detail:s});break;case We.ErrorTypes.MEDIA_ERROR:this.hls?.recoverMediaError();break;default:this.emitter.emit("error",{type:"hls-fatal",detail:s}),this.detachHls()}}),this.hls.on(We.Events.MANIFEST_PARSED,()=>{this.notifyTracks()}),this.hls.loadSource(e),this.hls.attachMedia(this.video);return}if(this.video.canPlayType("application/vnd.apple.mpegurl")){this.video.src=e;return}this.emitter.emit("error",{type:"hls-unsupported"});return}this.video.src=e}reload(){this.currentSrc&&this.load(this.currentSrc)}notifyTracks(){if(this.hls){if(this.hls.levels.length>1&&this.callbacks.onLevels){let e=this.hls.levels.map((t,s)=>({index:s,height:t.height,bitrate:t.bitrate,label:t.height?`${t.height}P`:`${Math.round(t.bitrate/1e3)}kbps`})).sort((t,s)=>s.height-t.height);this.callbacks.onLevels(e)}this.hls.audioTracks.length>1&&this.callbacks.onAudioTracks&&this.callbacks.onAudioTracks(this.hls.audioTracks.map((e,t)=>({index:t,label:e.name||e.lang||`Track ${t+1}`})))}}setLevel(e){this.hls&&(this.hls.currentLevel=e)}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}get bandwidthEstimate(){return this.hls?.bandwidthEstimate}get currentLevelInfo(){if(!this.hls||this.hls.currentLevel<0)return;let e=this.hls.levels[this.hls.currentLevel];if(e)return`${e.width}x${e.height}@${Math.round(e.bitrate/1e3)}kbps`}detachHls(){this.hls&&(this.hls.destroy(),this.hls=null)}destroy(){this.detachHls(),this.video.removeAttribute("src"),this.video.load()}};function ku(n){return n instanceof HTMLElement?n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.tagName==="SELECT"||n.isContentEditable:!1}var Xs=class{constructor(e,t,s){this.container=e;this.actions=t;this.options=s;this.holdDirection=0;this.holdStart=0;this.accumulated=0;this.tickTimer=null;this.hovering=!1;this.onKeyDown=e=>this.handleKeyDown(e);this.onKeyUp=e=>this.handleKeyUp(e);this.onEnter=()=>this.hovering=!0;this.onLeave=()=>this.hovering=!1;document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),e.addEventListener("mouseenter",this.onEnter),e.addEventListener("mouseleave",this.onLeave)}isScoped(e){return ku(e.target)?!1:this.hovering||this.container.contains(document.activeElement)}handleKeyDown(e){if(this.isScoped(e))switch(e.key){case" ":e.preventDefault(),e.repeat||this.actions.togglePlay();break;case"ArrowLeft":case"ArrowRight":{if(e.preventDefault(),e.repeat)return;this.startHold(e.key==="ArrowRight"?1:-1);break}case"ArrowUp":e.preventDefault(),this.actions.adjustVolume(5);break;case"ArrowDown":e.preventDefault(),this.actions.adjustVolume(-5);break;case"f":case"F":e.repeat||this.actions.toggleFullscreen();break;case"m":case"M":e.repeat||this.actions.toggleMute();break}}handleKeyUp(e){if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;let t=e.key==="ArrowRight"?1:-1;this.holdDirection===t&&this.endHold()}startHold(e){this.holdDirection!==0&&this.endHold(),this.holdDirection=e,this.holdStart=performance.now(),this.accumulated=0,this.tickTimer=setInterval(()=>{let t=performance.now()-this.holdStart;if(t<300)return;let{longSeekSteps:s,stepUpInterval:i}=this.options,r=Math.min(Math.floor((t-300)/i),s.length-1),a=s[r];this.accumulated+=a*(250/1e3)*this.holdDirection,this.actions.onLongSeekProgress(Math.round(this.accumulated))},250)}endHold(){this.tickTimer&&(clearInterval(this.tickTimer),this.tickTimer=null);let e=performance.now()-this.holdStart,t=this.holdDirection;this.holdDirection=0,e<300?this.actions.seekBy(this.options.seekStep*t):this.actions.onLongSeekCommit(Math.round(this.accumulated)),this.accumulated=0}destroy(){this.tickTimer&&clearInterval(this.tickTimer),document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("keyup",this.onKeyUp),this.container.removeEventListener("mouseenter",this.onEnter),this.container.removeEventListener("mouseleave",this.onLeave)}};var Qs=class{constructor(e,t,s,i){this.container=e;this.video=t;this.actions=s;this.seekStep=i;this.startX=0;this.startY=0;this.mode="none";this.pendingDelta=0;this.lastTapTime=0;this.lastTapX=0;this.singleTapTimer=null;this.onPointerDown=e=>this.handleDown(e);this.onPointerMove=e=>this.handleMove(e);this.onPointerUp=e=>this.handleUp(e);e.addEventListener("pointerdown",this.onPointerDown),e.addEventListener("pointermove",this.onPointerMove),e.addEventListener("pointerup",this.onPointerUp),e.addEventListener("pointercancel",this.onPointerUp)}isOnVideoSurface(e){return e.target===this.video||e.target===this.container}handleDown(e){e.pointerType!=="touch"||!this.isOnVideoSurface(e)||(this.startX=e.clientX,this.startY=e.clientY,this.mode="none",this.pendingDelta=0)}handleMove(e){if(e.pointerType!=="touch"||this.mode==="none"&&!this.isOnVideoSurface(e))return;let t=e.clientX-this.startX,s=e.clientY-this.startY,i=this.container.getBoundingClientRect();if(this.mode==="none"&&(Math.abs(t)>12&&Math.abs(t)>Math.abs(s)?this.mode="seek":Math.abs(s)>12&&Math.abs(s)>Math.abs(t)&&this.startX-i.left>i.width/2&&(this.mode="volume"),this.mode!=="none"&&this.container.setPointerCapture(e.pointerId)),this.mode==="seek")this.pendingDelta=Math.round(t/i.width*120),this.actions.onSeekPreview(this.pendingDelta);else if(this.mode==="volume"){let r=Math.round(-(e.clientY-this.startY)/i.height*100);r!==0&&(this.actions.adjustVolume(r),this.startY=e.clientY)}}handleUp(e){e.pointerType==="touch"&&(this.mode==="seek"?this.actions.onSeekCommit(this.pendingDelta):this.mode==="none"&&this.isOnVideoSurface(e)&&this.handleTap(e),this.mode="none",this.pendingDelta=0)}handleTap(e){let t=Date.now(),s=this.container.getBoundingClientRect();if(t-this.lastTapTime<280&&Math.abs(e.clientX-this.lastTapX)<60){this.singleTapTimer&&(clearTimeout(this.singleTapTimer),this.singleTapTimer=null),this.lastTapTime=0;let i=(e.clientX-s.left)/s.width;i<1/3?this.actions.seekBy(-this.seekStep):i>2/3?this.actions.seekBy(this.seekStep):this.actions.toggleFullscreen();return}this.lastTapTime=t,this.lastTapX=e.clientX,this.singleTapTimer=setTimeout(()=>{this.singleTapTimer=null,this.actions.toggleControls()},280)}destroy(){this.singleTapTimer&&clearTimeout(this.singleTapTimer),this.container.removeEventListener("pointerdown",this.onPointerDown),this.container.removeEventListener("pointermove",this.onPointerMove),this.container.removeEventListener("pointerup",this.onPointerUp),this.container.removeEventListener("pointercancel",this.onPointerUp)}};function Zs(n){let e=document;return(e.fullscreenElement??e.webkitFullscreenElement)===n}async function Zo(n){let e=document,t=n;Zs(n)?await(e.exitFullscreen?.()??e.webkitExitFullscreen?.()):await(t.requestFullscreen?.()??t.webkitRequestFullscreen?.())}function Jo(n,e){let t=()=>e(Zs(n));return document.addEventListener("fullscreenchange",t),document.addEventListener("webkitfullscreenchange",t),()=>{document.removeEventListener("fullscreenchange",t),document.removeEventListener("webkitfullscreenchange",t)}}function H(n,{className:e,text:t,html:s,attrs:i,parent:r}={}){let a=document.createElement(n);if(e&&(a.className=e),t&&(a.textContent=t),s&&(a.innerHTML=s),i)for(let[o,c]of Object.entries(i))a.setAttribute(o,c);return r&&r.appendChild(a),a}function be(n,e="0 0 24 24"){return`<svg viewBox="${e}" fill="currentColor" aria-hidden="true"><path d="${n}"/></svg>`}function Me(n){if(!Number.isFinite(n)||n<0)return"0:00";let e=Math.floor(n%60),t=Math.floor(n/60%60),s=Math.floor(n/3600),i=s>0?String(t).padStart(2,"0"):String(t),r=String(e).padStart(2,"0");return s>0?`${s}:${i}:${r}`:`${i}:${r}`}function Qe(n,e,t){return Math.min(t,Math.max(e,n))}var me={play:be("M8 5v14l11-7z"),pause:be("M6 19h4V5H6v14zm8-14v14h4V5h-4z"),prev:be("M6 6h2v12H6zm3.5 6l8.5 6V6z"),next:be("M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"),seekBack:be("M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"),seekForward:be("M12 5V1l5 5-5 5V7c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6h2c0 4.42-3.58 8-8 8s-8-3.58-8-8 3.58-8 8-8z"),volumeHigh:be("M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"),volumeLow:be("M5 9v6h4l5 5V4L9 9H5zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"),volumeMute:be("M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"),fullscreen:be("M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"),fullscreenExit:be("M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"),pip:be("M19 7h-8v6h8V7zm2-4H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.98h18v14.03z"),audio:be("M12 3a9 9 0 0 0-9 9v7c0 1.1.9 2 2 2h4v-8H5v-1c0-3.87 3.13-7 7-7s7 3.13 7 7v1h-4v8h4c1.1 0 2-.9 2-2v-7a9 9 0 0 0-9-9z")};function Qt(n){let e=H("div",{className:"sp-menu"}),t=H("button",{className:"sp-btn sp-menu-btn",html:n.buttonHtml,attrs:{type:"button",title:n.title,"aria-label":n.title},parent:e}),s=H("div",{className:"sp-menu-panel",parent:e}),i=[],r;function a(){if(s.innerHTML="",i.length===0){H("div",{className:"sp-menu-empty",text:n.emptyText??"-",parent:s});return}for(let c of i)H("button",{className:"sp-menu-item"+(c.value===r?" sp-active":""),text:c.label,attrs:{type:"button"},parent:s}).addEventListener("click",h=>{h.stopPropagation(),o(),n.onSelect(c)})}function o(){e.classList.remove("sp-open")}return t.addEventListener("click",c=>{c.stopPropagation();let l=!e.classList.contains("sp-open");e.closest(".sp-controls")?.querySelectorAll(".sp-menu.sp-open").forEach(h=>h.classList.remove("sp-open")),e.classList.toggle("sp-open",l)}),document.addEventListener("click",o),a(),{el:e,setItems(c){i=c,a()},setActive(c){r=c,a()},setButtonContent(c){t.innerHTML=c},close:o}}function el(n,e){let t=H("div",{className:"sp-progress"}),s=H("div",{className:"sp-progress-track",parent:t}),i=H("div",{className:"sp-progress-buffered",parent:s}),r=H("div",{className:"sp-progress-played",parent:s}),a=H("div",{className:"sp-progress-thumb",parent:s}),o=H("div",{className:"sp-progress-tooltip",text:"0:00",parent:t}),c=!1;function l(g){let p=t.getBoundingClientRect();return Qe((g.clientX-p.left)/p.width,0,1)}function h(g){let p=n.duration||0,y=g??(p?n.currentTime/p:0);r.style.width=`${y*100}%`,a.style.left=`${y*100}%`;let v=0;for(let E=0;E<n.buffered.length;E++)n.buffered.start(E)<=n.currentTime&&n.buffered.end(E)>v&&(v=n.buffered.end(E));i.style.width=p?`${v/p*100}%`:"0%"}function d(g){let p=l(g);o.style.left=`${p*100}%`,o.textContent=Me(p*(n.duration||0)),c&&h(p)}function u(g){c=!0,t.classList.add("sp-dragging"),t.setPointerCapture(g.pointerId),h(l(g))}function f(g){c&&(c=!1,t.classList.remove("sp-dragging"),e(l(g)*(n.duration||0)))}return t.addEventListener("pointermove",d),t.addEventListener("pointerdown",u),t.addEventListener("pointerup",f),t.addEventListener("pointercancel",()=>{c=!1,t.classList.remove("sp-dragging")}),{el:t,update(){c||h()},destroy(){t.remove()}}}function tl(n){let e=H("div",{className:"sp-volume"}),t=H("button",{className:"sp-btn",html:me.volumeHigh,attrs:{type:"button",title:n.muteTitle,"aria-label":n.muteTitle},parent:e}),s=H("div",{className:"sp-volume-slider",parent:e}),i=H("div",{className:"sp-volume-track",parent:s}),r=H("div",{className:"sp-volume-fill",parent:i}),a=H("div",{className:"sp-volume-thumb",parent:i});t.addEventListener("click",n.onToggleMute);let o=!1;function c(h){let d=i.getBoundingClientRect();return Math.round(Qe((h.clientX-d.left)/d.width,0,1)*100)}i.addEventListener("pointerdown",h=>{o=!0,e.classList.add("sp-dragging"),i.setPointerCapture(h.pointerId),n.onVolumeChange(c(h))}),i.addEventListener("pointermove",h=>{o&&n.onVolumeChange(c(h))});let l=()=>{o=!1,e.classList.remove("sp-dragging")};return i.addEventListener("pointerup",l),i.addEventListener("pointercancel",l),{el:e,update(h,d){let u=d?0:h;r.style.width=`${u}%`,a.style.left=`${u}%`,t.innerHTML=d||h===0?me.volumeMute:h<50?me.volumeLow:me.volumeHigh}}}function sl(n){let{video:e,actions:t,i18n:s}=n,i=H("div",{className:"sp-top"});H("div",{className:"sp-title",text:n.title,parent:i}).addEventListener("click",t.onTitleClick);let a=H("div",{className:"sp-bottom"}),o=el(e,E=>{e.currentTime=E});a.appendChild(o.el);let c=H("div",{className:"sp-controls",parent:a}),l=(E,T,S,x=!1)=>{let _=H("button",{className:"sp-btn",html:E,attrs:{type:"button",title:T,"aria-label":T},parent:c});return _.disabled=x,_.addEventListener("click",S),_};l(me.prev,s.t("prev"),()=>t.onPrev?.(),!t.onPrev),l(me.seekBack,s.t("seekBack",{n:n.seekStep}),()=>t.seekBy(-n.seekStep));let h=l(me.play,s.t("playPause"),t.togglePlay);l(me.seekForward,s.t("seekForward",{n:n.seekStep}),()=>t.seekBy(n.seekStep)),l(me.next,s.t("next"),()=>t.onNext?.(),!t.onNext);let d=H("span",{className:"sp-time",text:"0:00 / 0:00",parent:c});H("div",{className:"sp-controls-spacer",parent:c});let u=Qt({buttonHtml:"1x",title:s.t("speed"),emptyText:s.t("empty"),onSelect:E=>t.setRate(E.value)});u.setItems(n.playbackRates.map(E=>({label:`${E}x`,value:E}))),u.setActive(e.playbackRate),c.appendChild(u.el);let f=Qt({buttonHtml:s.t("quality"),title:s.t("quality"),emptyText:s.t("empty"),onSelect:E=>t.selectQuality(E.value)});c.appendChild(f.el);let g=Qt({buttonHtml:s.t("aspectRatio"),title:s.t("aspectRatio"),emptyText:s.t("empty"),onSelect:E=>t.setAspectRatio(E.value)});g.setItems(n.aspectRatios.map(E=>({label:E==="original"?s.t("ratioOriginal"):E,value:E}))),g.setActive("original"),c.appendChild(g.el);let p=Qt({buttonHtml:me.audio,title:s.t("audioTrack"),emptyText:s.t("empty"),onSelect:E=>t.selectAudioTrack(E.value)});c.appendChild(p.el);let y=tl({muteTitle:s.t("mute"),onVolumeChange:t.setVolume,onToggleMute:t.toggleMute});c.appendChild(y.el),document.pictureInPictureEnabled&&l(me.pip,s.t("pip"),t.togglePip);let v=l(me.fullscreen,s.t("fullscreen"),t.toggleFullscreen);return{topEl:i,bottomEl:a,progress:o,volume:y,qualityMenu:f,audioMenu:p,updatePlayState(E){h.innerHTML=E?me.pause:me.play},updateTime(){d.textContent=`${Me(e.currentTime)} / ${Me(e.duration)}`,o.update()},updateRate(E){u.setButtonContent(`${E}x`),u.setActive(E)},updateFullscreen(E){v.innerHTML=E?me.fullscreenExit:me.fullscreen},updateRatio(E){g.setActive(E)},destroy(){i.remove(),a.remove()}}}function il(){let n=H("div",{className:"sp-osd"}),e=null;function t(i){e&&(clearTimeout(e),e=null),n.textContent=i,n.classList.add("sp-visible")}function s(){n.classList.remove("sp-visible")}return{el:n,show:t,hide:s,flash(i){t(i),e=setTimeout(s,800)}}}function rl(n,e,t,s){let i=null,r=null;function a(){let h=e.getVideoPlaybackQuality?.(),d=[];for(let f=0;f<e.buffered.length;f++)d.push(`${Me(e.buffered.start(f))}-${Me(e.buffered.end(f))}`);let u=t.bandwidthEstimate;return[["Video Res",`${e.videoWidth}x${e.videoHeight}`],["Viewport",`${n.clientWidth}x${n.clientHeight}`],["Time",`${Me(e.currentTime)} / ${Me(e.duration)}`],["Buffered",d.join(", ")||"-"],["Dropped Frames",h?`${h.droppedVideoFrames} / ${h.totalVideoFrames}`:"N/A"],["Bandwidth",u?`${(u/1e3/1e3).toFixed(2)} Mbps`:"N/A"],["HLS Level",t.currentLevelInfo??"N/A"],["Speed",`${e.playbackRate}x`],["Volume",e.muted?"muted":`${Math.round(e.volume*100)}%`],["Ready State",String(e.readyState)],["Source",e.currentSrc||"-"]]}function o(){if(!i)return;let h=i.querySelector(".sp-stats-body");h.innerHTML="";for(let[d,u]of a()){let f=H("div",{className:"sp-stats-row",parent:h});H("dt",{text:d,parent:f}),H("dd",{text:u,parent:f})}}function c(){if(i)return;i=H("div",{className:"sp-stats",parent:n}),H("button",{className:"sp-stats-close",text:"\u2715",attrs:{type:"button","aria-label":s.t("closeStats")},parent:i}).addEventListener("click",l),H("dl",{className:"sp-stats-body",parent:i}),o(),r=setInterval(o,500)}function l(){r&&(clearInterval(r),r=null),i?.remove(),i=null}return{toggle(){i?l():c()},hide:l,destroy:l}}function nl(n){let e=H("div",{className:"sp-state"}),t=H("div",{className:"sp-spinner",parent:e});t.innerHTML='<div class="sp-spinner-ring"></div>';let s=null,i=null,r=null;function a(){r&&(clearInterval(r),r=null)}function o(){s?.remove(),s=null}function c(){a(),i?.remove(),i=null}return{el:e,showLoading(){e.classList.add("sp-loading")},hideLoading(){e.classList.remove("sp-loading")},showError(l){o(),c(),e.classList.remove("sp-loading"),s=H("div",{className:"sp-state-panel",parent:e}),H("div",{className:"sp-state-message",text:n.t("loadError"),parent:s}),H("button",{className:"sp-state-btn",text:n.t("retry"),attrs:{type:"button"},parent:s}).addEventListener("click",()=>{o(),l()})},hideError:o,showEnded({onReplay:l,onNext:h,autoNextSeconds:d}){c(),o(),e.classList.remove("sp-loading"),i=H("div",{className:"sp-state-panel",parent:e});let u=H("div",{className:"sp-state-actions",parent:i});if(H("button",{className:"sp-state-btn",text:n.t("replay"),attrs:{type:"button"},parent:u}).addEventListener("click",()=>{c(),l()}),h&&(H("button",{className:"sp-state-btn sp-state-btn-primary",text:n.t("playNext"),attrs:{type:"button"},parent:u}).addEventListener("click",()=>{c(),h()}),d&&d>0)){let p=d,y=H("div",{className:"sp-state-countdown",text:n.t("autoNextIn",{n:p}),parent:i});H("button",{className:"sp-state-cancel",text:n.t("cancel"),attrs:{type:"button"},parent:y}).addEventListener("click",()=>{a(),y.remove()}),r=setInterval(()=>{p-=1,p<=0?(c(),h()):y.firstChild.textContent=n.t("autoNextIn",{n:p})},1e3)}},hideEnded:c,destroy(){a(),e.remove()}}}var al={play:"\u64AD\u653E",pause:"\u6682\u505C",playPause:"\u64AD\u653E/\u6682\u505C (\u7A7A\u683C)",prev:"\u4E0A\u4E00\u4E2A",next:"\u4E0B\u4E00\u4E2A",seekBack:"\u5FEB\u9000 {n} \u79D2 (\u2190)",seekForward:"\u5FEB\u8FDB {n} \u79D2 (\u2192)",speed:"\u64AD\u653E\u500D\u901F",quality:"\u753B\u8D28",qualityAuto:"\u81EA\u52A8",aspectRatio:"\u753B\u9762\u6BD4\u4F8B",ratioOriginal:"\u539F\u59CB",audioTrack:"\u97F3\u8F68",mute:"\u9759\u97F3 (M)",fullscreen:"\u5168\u5C4F (F)",pip:"\u753B\u4E2D\u753B (P)",empty:"\u6682\u65E0\u53EF\u9009\u9879",closeStats:"\u5173\u95ED\u7EDF\u8BA1\u4FE1\u606F",seconds:"\u79D2",volume:"\u97F3\u91CF",muted:"\u9759\u97F3",replay:"\u91CD\u65B0\u64AD\u653E",playNext:"\u64AD\u653E\u4E0B\u4E00\u4E2A",autoNextIn:"{n} \u79D2\u540E\u64AD\u653E\u4E0B\u4E00\u4E2A",cancel:"\u53D6\u6D88",loadError:"\u89C6\u9891\u52A0\u8F7D\u5931\u8D25",retry:"\u91CD\u8BD5"},Cu={play:"Play",pause:"Pause",playPause:"Play/Pause (Space)",prev:"Previous",next:"Next",seekBack:"Rewind {n}s (\u2190)",seekForward:"Forward {n}s (\u2192)",speed:"Playback speed",quality:"Quality",qualityAuto:"Auto",aspectRatio:"Aspect ratio",ratioOriginal:"Original",audioTrack:"Audio track",mute:"Mute (M)",fullscreen:"Fullscreen (F)",pip:"Picture-in-Picture (P)",empty:"Nothing available",closeStats:"Close stats",seconds:"s",volume:"Volume",muted:"Muted",replay:"Replay",playNext:"Play next",autoNextIn:"Playing next in {n}s",cancel:"Cancel",loadError:"Failed to load video",retry:"Retry"},wu={"zh-CN":al,en:Cu},Js=class{constructor(e="zh-CN",t){this.strings={...wu[e]??al,...t}}t(e,t){let s=this.strings[e];if(t)for(let[i,r]of Object.entries(t))s=s.replace(`{${i}}`,String(r));return s}};var ol="sweet-player-style";function ll(n){if(typeof document>"u"||document.getElementById(ol))return;let e=document.createElement("style");e.id=ol,e.textContent=n,document.head.appendChild(e)}var cl="sweet-player:prefs",cn="sweet-player:progress:";function hl(n){try{return localStorage.getItem(n)}catch{return null}}function dl(n,e){try{localStorage.setItem(n,e)}catch{}}function hn(){let n=hl(cl);if(!n)return{};try{return JSON.parse(n)}catch{return{}}}function dn(n){dl(cl,JSON.stringify({...hn(),...n}))}function ul(n){let e=hl(cn+n),t=e===null?NaN:Number(e);return Number.isFinite(t)?t:null}function fl(n,e){dl(cn+n,String(Math.floor(e)))}function gl(n){try{localStorage.removeItem(cn+n)}catch{}}var ml=`.sweet-player {
38
+ `),l=[],d=e?Ud(e.baseTime,e.timescale):0,h="00:00.000",u=0,g=0,f,p=!0;o.oncue=function(y){let v=t[s],E=t.ccOffset,T=(u-d)/9e4;if(v!=null&&v.new&&(g!==void 0?E=t.ccOffset=v.start:lu(t,s,T)),T){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}E=T-t.presentationOffset}let x=y.endTime-y.startTime,A=Pe((y.startTime+E-g)*9e4,i*9e4)/9e4;y.startTime=Math.max(A,0),y.endTime=Math.max(A+x,0);let _=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(_)),y.id||(y.id=cr(y.startTime,y.endTime,_)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){f=y},o.onflush=function(){if(f){a(f);return}n(l)},c.forEach(y=>{if(p)if(Ei(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(v=>{Ei(v,"LOCAL:")?h=v.slice(6):Ei(v,"MPEGTS:")&&(u=parseInt(v.slice(7)))});try{g=ou(h)/1e3}catch(v){f=v}return}else y===""&&(p=!1);o.parse(y+`
39
+ `)}),o.flush()}var Ti="stpp.ttml.im1t",zo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Xo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,du={left:"start",center:"center",right:"end",start:"start",end:"end"};function Aa(r,e,t,s){let i=X(new Uint8Array(r),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}let n=i.map(o=>ke(o)),a=$d(e.baseTime,1,e.timescale);try{n.forEach(o=>t(hu(o,a)))}catch(o){s(o)}}function hu(r,e){let i=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((h,u)=>(h[u]=i.getAttribute(`ttp:${u}`)||n[u],h),{}),o=i.getAttribute("xml:space")!=="preserve",c=La(Si(i,"styling","style")),l=La(Si(i,"layout","region")),d=Si(i,"body","[begin]");return[].map.call(d,h=>{let u=Qo(h,o);if(!u||!h.hasAttribute("begin"))return null;let g=Ai(h.getAttribute("begin"),a),f=Ai(h.getAttribute("dur"),a),p=Ai(h.getAttribute("end"),a);if(g===null)throw Ia(h);if(p===null){if(f===null)throw Ia(h);p=g+f}let y=new lr(g-e,p-e,u);y.id=cr(y.startTime,y.endTime,y.text);let v=l[h.getAttribute("region")],E=c[h.getAttribute("style")],T=uu(v,E,c),{textAlign:x}=T;if(x){let A=du[x];A&&(y.lineAlign=A),y.align=x}return ie(y,T),y}).filter(h=>h!==null)}function Si(r,e,t){let s=r.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function La(r){return r.reduce((e,t)=>{let s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Qo(r,e){return[].slice.call(r.childNodes).reduce((t,s,i)=>{var n;return s.nodeName==="br"&&i?t+`
40
+ `:(n=s.childNodes)!=null&&n.length?Qo(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function uu(r,e,t){let s="http://www.w3.org/ns/ttml#styling",i=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),n.reduce((o,c)=>{let l=xi(e,s,c)||xi(r,s,c)||xi(i,s,c);return l&&(o[c]=l),o},{})}function xi(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Ia(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Ai(r,e){if(!r)return null;let t=Wo(r);return t===null&&(zo.test(r)?t=fu(r,e):Xo.test(r)&&(t=gu(r,e))),t}function fu(r,e){let t=zo.exec(r),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function gu(r,e){let t=Xo.exec(r),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}var Lt=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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Fn=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Ra(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new Lt(this,"textTrack1"),t=new Lt(this,"textTrack2"),s=new Lt(this,"textTrack3"),i=new Lt(this,"textTrack4");this.cea608Parser1=new Hs(1,e,t),this.cea608Parser2=new Hs(3,s,i)}addCues(e,t,s,i,n){let a=!1;for(let o=n.length;o--;){let c=n[o],l=pu(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),a=!0,l/(s-t)>.5))return}if(a||n.push([t,s]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{let o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:n,trackId:a}){let{unparsedVttFrags:o}=this;s===B.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,c):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){let n=s.textTracks[i];if(ba(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:s,media:i}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)s[e]=o,At(s[e]),Ko(s[e],i);else{let c=this.createTextTrack("captions",n,a);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){let i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let s=!!t.transferMedia;if(this.media=null,s)return;let{captionsTracks:i}=this;Object.keys(i).forEach(n=>{At(i[n]),delete i[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Ra(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let s=0;s<t.length;s++)At(t[s])}onSubtitleTracksUpdated(e,t){let s=t.subtitleTracks||[],i=s.some(n=>n.textCodec===Ti);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Do(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){let a=this.media,o=a?Es(a.textTracks):null;if(this.tracks.forEach((c,l)=>{let d;if(o){let h=null;for(let u=0;u<o.length;u++)if(o[u]&&ba(o[u],c)){h=o[u],o[u]=null;break}h&&(d=h)}if(d)At(d);else{let h=Zo(c);d=this.createTextTrack(h,c.name,c.lang),d&&(d.mode="disabled")}d&&this.textTracks.push(d)}),o!=null&&o.length){let c=o.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{let i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;let n=`textTrack${i[1]}`,a=this.captionsProperties[n];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===B.MAIN){var s,i;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:l}=t.frag,d=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;n&&a&&(l!==o+1||l===o&&d!==this.lastPartIndex+1||c!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=d}}onFragLoaded(e,t){let{frag:s,payload:i}=t;if(s.type===B.SUBTITLE)if(i.byteLength){let n=s.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Ti?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let s=this.hls;Aa(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;let{frag:s,payload:i}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&o===-1){a.push(e);return}let c=this.hls,l=(t=s.initSegment)!=null&&t.data?Oe(s.initSegment.data,new Uint8Array(i)).buffer:i;cu(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,d=>{this._appendCues(d,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},d=>{let h=d.message==="Missing initPTS for VTT MPEGTS";h?a.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${d}`),!(h&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:d})})}_fallbackToIMSC1(e,t){let s=this.tracks[e.level];s.textCodec||Aa(t,this.initPTS[e.cc],()=>{s.textCodec=Ti,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){let s=this.hls;if(this.config.renderTextTracksNatively){let i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(n=>Vo(i,n))}else{let i=this.tracks[t];if(!i)return;let n=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:s}=t;s.type===B.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:s,samples:i}=t;if(!(s.type===B.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let n=0;n<i.length;n++){let a=i[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(i[n].pts,o[0]),this.cea608Parser2.addData(i[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:n}){let{media:a}=this;if(!(!a||a.currentTime<s)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(c=>Tn(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(c=>Tn(o[c],t,i))}}}extractCea608Data(e){let t=[[],[]],s=e[0]&31,i=2;for(let n=0;n<s;n++){let a=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&a)!==0){let d=3&a;(d===0||d===1)&&(t[d].push(o),t[d].push(c))}}return t}};function Zo(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function ba(r,e){return!!r&&r.kind===Zo(e)&&ln(e,r)}function pu(r,e,t,s){return Math.min(e,s)-Math.max(r,t)}function Ra(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var mu=/\s/,yu={newCue(r,e,t,s){let i=[],n,a,o,c,l,d=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(n=s.rows[u],o=!0,c=0,l="",!n.isEmpty()){var h;for(let p=0;p<n.chars.length;p++)mu.test(n.chars[p].uchar)&&o?c++:(l+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;let g=jo(l.trim()),f=cr(e,t,g);r!=null&&(h=r.cues)!=null&&h.getCueById(f)||(a=new d(e,t,g),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(a))}return r&&i.length&&(i.sort((u,g)=>u.line==="auto"||g.line==="auto"?0:u.line>8&&g.line>8?g.line-u.line:u.line-g.line),i.forEach(u=>Vo(r,u))),i}};function vu(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Eu=/(\d+)-(\d+)\/(\d+)/,Ys=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Au,this.controller=new self.AbortController,this.stats=new Ut}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){let i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();let n=Tu(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&F(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(zt(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var u;this.response=this.loader=h;let g=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(g-i.loading.start)),!h.ok){let{status:p,statusText:y}=h;throw new Nn(y||"fetch, bad network response",p,h)}i.loading.first=g,i.total=xu(h.headers)||i.total;let f=(u=this.callbacks)==null?void 0:u.onProgress;return f&&F(t.highWaterMark)?this.loadProgressively(h,i,e,t.highWaterMark,f):a?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var u,g;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 p=h[o];p&&(i.loaded=i.total=p);let y={url:f.url,data:h,code:f.status},v=(u=this.callbacks)==null?void 0:u.onProgress;v&&!F(t.highWaterMark)&&v(i,e,h,f),(g=this.callbacks)==null||g.onSuccess(y,i,e,f)}).catch(h=>{var u;if(self.clearTimeout(this.requestTimeout),i.aborted)return;let g=h&&h.code||0,f=h?h.message:null;(u=this.callbacks)==null||u.onError({code:g,text:f},e,h?h.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,s,i=0,n){let a=new Ms,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let d=l.value,h=d.length;return t.loaded+=h,h<i||a.dataLength?(a.push(d),a.dataLength>=i&&n(t,s,a.flush().buffer,e)):n(t,s,d.buffer,e),c()}).catch(()=>Promise.reject());return c()}};function Tu(r,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ie({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Su(r){let e=Eu.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function xu(r){let e=r.get("Content-Range");if(e){let s=Su(e);if(F(s))return s}let t=r.get("Content-Length");if(t)return parseInt(t)}function Au(r,e){return new self.Request(r.url,e)}var Nn=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},Lu=/^age:\s*[\d.]+\s*$/im,Ws=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ut,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return n(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),n(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);let i=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(let o in i)e.setRequestHeader(o,i[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),s.timeout=n&&F(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:s}=this;if(!e||!t)return;let i=t.readyState,n=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let l=t.status,d=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){let f=d??t.response;if(f!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);let p=t.responseType==="arraybuffer"?f.byteLength:f.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);let y=(a=this.callbacks)==null?void 0:a.onProgress;y&&y(s,e,f,t);let v={url:t.responseURL,data:f,code:l};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}let h=n.loadPolicy.errorRetry,u=s.retry,g={url:e.url,data:void 0,code:l};if(_s(h,u,!1,g))this.retry(h);else{var c;se.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(_s(e,t,!0))this.retry(e);else{var s;se.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);let i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:s}=this;this.retryDelay=Qn(e,s.retry),s.retry++,se.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Lu.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}},Iu={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},bu=te(te({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Ws,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:wi,bufferController:un,capLevelController:fn,errorController:Oi,fpsController:En,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:to,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Iu},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},Ru()),{},{subtitleStreamController:Rn,subtitleTrackController:Sn,timelineController:Fn,audioStreamController:on,audioTrackController:cn,emeController:Us,cmcdController:yn,contentSteeringController:vn,interstitialsController:bn});function Ru(){return{cueHandler:yu,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 _u(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"');let s=Bn(r),i=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,c=e[o]===void 0,l=[];n.forEach(d=>{let h=`${a}Loading${d}`,u=e[h];if(u!==void 0&&c){l.push(h);let g=s[o].default;switch(e[o]={default:g},d){case"TimeOut":g.maxLoadTimeMs=u,g.maxTimeToFirstByteMs=u;break;case"MaxRetry":g.errorRetry.maxNumRetry=u,g.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":g.errorRetry.retryDelayMs=u,g.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=u,g.timeoutRetry.maxRetryDelayMs=u;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${re(e[o])}`)}),te(te({},s),e)}function Bn(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(Bn):Object.keys(r).reduce((e,t)=>(e[t]=Bn(r[t]),e),{}):r}function Pu(r,e){let t=r.loader;t!==Ys&&t!==Ws?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):vu()&&(r.loader=Ys,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Ts=2,Du=.1,ku=.05,Cu=100,$n=class extends Ps{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.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(Cu),this.mediaSource=t.mediaSource;let s=this.media=t.media;Le(s,"playing",this.onMediaPlaying),Le(s,"waiting",this.onMediaWaiting),Le(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:s}=this;s&&(be(s,"playing",this.onMediaPlaying),be(s,"waiting",this.onMediaWaiting),be(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;let n=(s=this.hls)==null?void 0:s.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,c=this.seeking&&!o,l=!this.seeking&&o,d=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(d){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!q.getBuffered(a).length){this.nudgeRetry=0;return}let h=q.bufferInfo(a,e,0),u=h.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){let _=_a(this.hls.inFlightFragments,e),S=h.len>Ts,I=!u||_||u-e>Ts&&!g.getPartialFragment(e);if(S||I)return;this.moved=!1}let f=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(h.len>0)&&!u)return;let S=Math.max(u,h.start||0)-e,b=!!(f!=null&&f.live)?f.targetduration*2:Ts,L=us(e,g);if(S>0&&(S<=b||L)){a.paused||this._trySkipBufferHole(L);return}}let p=n.detectStallWithCurrentTimeMs,y=self.performance.now(),v=this.waiting,E=this.stalled;if(E===null)if(v>0&&y-v<p)E=this.stalled=v;else{this.stalled=y;return}let T=y-E;if(!o&&(T>=p||v)&&this.hls){var x;if(((x=this.mediaSource)==null?void 0:x.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-(f?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}let A=q.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(A,T,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;let i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){let n=q.bufferedInfo(q.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=q.timeRangesToArray(i),o=q.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let c=q.bufferedInfo(a,e,0).bufferedIndex,l=a[o].end,d=a[o+1].start;if((c===-1||c>o)&&d-l<1&&e-l<2){let h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${d} buffered index: ${c}`);this.warn(h.message),this.media.currentTime+=1e-6;let u=us(e,this.fragmentTracker);u&&"fragment"in u?u=u.fragment:u||(u=void 0);let g=q.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:u,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,s){var i,n;let{fragmentTracker:a,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!a||!c)return;let l=(n=this.hls)==null?void 0:n.latestLevelDetails,d=us(s,a);if((d||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;let h=e.buffered,u=this.adjacentTraversal(e,s);(h&&h.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||u))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let s=this.fragmentTracker,i=e.nextStart;if(s&&i){let n=s.getFragAtPos(t,B.MAIN),a=s.getFragAtPos(i,B.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:s,stallReported:i,stalled:n}=this;if(!i&&n!==null&&s&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${re(e)})`);this.warn(a.message),t.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;let{fragmentTracker:s,media:i}=this,n=(t=this.hls)==null?void 0:t.config;if(!i||!s||!n)return 0;let a=i.currentTime,o=q.bufferInfo(i,a,0),c=a<o.start?o.start:o.nextStart;if(c&&this.hls){let d=o.len<=n.maxBufferHole,h=o.len>0&&o.len<1&&i.readyState<3,u=c-a;if(u>0&&(d||h)){if(u>n.maxBufferHole){let f=!1;if(a===0){let p=s.getAppendedFrag(0,B.MAIN);p&&c<p.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||_a(this.hls.inFlightFragments,c))return 0;let y=!1,v=e.end;for(;v<c;){let E=us(v,s);if(E)v+=E.duration;else{y=!0;break}}if(y)return 0}}let g=Math.max(c+ku,a+Du);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${g}`),this.moved=!0,i.currentTime=g,!(e!=null&&e.gap)){let f=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${g}`),p={type:V.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return g}}return 0}_tryNudgeBuffer(e){let{hls:t,media:s,nudgeRetry:i}=this,n=t?.config;if(!s||!n)return 0;let a=s.currentTime;if(this.nudgeRetry++,i<n.nudgeMaxRetry){let o=a+(i+1)*n.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:c,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(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function _a(r,e){let t=Pa(r.main);if(t&&t.start<=e)return t;let s=Pa(r.audio);return s&&s.start<=e?s:null}function Pa(r){if(!r)return null;switch(r.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return r.frag}function us(r,e){return e.getAppendedFrag(r,B.MAIN)||e.getPartialFragment(r)}var wu=.25;function Un(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Li(r,e,t,s,i){let n=new r(e,t,"");try{n.value=s,i&&(n.type=i)}catch{n=new r(e,t,re(i?te({type:i},s):s))}return n}var fs=(()=>{let r=Un();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Gn=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(m.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(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}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.removeCues&&At(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Ko(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=Un();if(a)for(let o=0;o<n.length;o++){let c=n[o].type;if(c===De.emsg&&!s||!i)continue;let l=Eo(n[o].data),d=n[o].pts,h=d+n[o].duration;h>fs&&(h=fs),h-d<=0&&(h=d+wu);for(let g=0;g<l.length;g++){let f=l[g];if(!To(f)){this.updateId3CueEnds(d,c);let p=Li(a,d,h,f,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;let i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let n=i.length;n--;){let a=i[n];a.type===t&&a.startTime<e&&a.endTime===fs&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=a;if(n&&(o||c)){let l;i==="audio"?l=d=>d.type===De.audioId3&&c:i==="video"?l=d=>d.type===De.emsg&&o:l=d=>d.type===De.audioId3&&c||d.type===De.emsg&&o,Tn(n,t,s,l)}}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:s,timelineOffset:i,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=Un();if(s&&i&&!a){let{fragmentStart:p,fragmentEnd:y}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=y):o&&(v=this.assetCue=Li(o,p,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:c}=this,{dateRanges:l}=e,d=Object.keys(l),h=this.dateRangeCuesAppended;if(c&&t){var u;if((u=c.cues)!=null&&u.length){let p=Object.keys(h).filter(y=>!d.includes(y));for(let y=p.length;y--;){var g;let v=p[y],E=(g=h[v])==null?void 0:g.cues;delete h[v],E&&Object.keys(E).forEach(T=>{let x=E[T];if(x){x.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(x)}catch{}}})}}else h=this.dateRangeCuesAppended={}}let f=e.fragments[e.fragments.length-1];if(!(d.length===0||!F(f?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<d.length;p++){let y=d[p],v=l[y],E=v.startTime,T=h[y],x=T?.cues||{},A=T?.durationKnown||!1,_=fs,{duration:S,endDate:I}=v;if(I&&S!==null)_=E+S,A=!0;else if(v.endOnNext&&!A){let L=d.reduce((D,C)=>{if(C!==v.id){let $=l[C];if($.class===v.class&&$.startDate>v.startDate&&(!D||v.startDate<D.startDate))return $}return D},null);L&&(_=L.startTime,A=!0)}let b=Object.keys(v.attr);for(let L=0;L<b.length;L++){let D=b[L];if(!Bc(D))continue;let C=x[D];if(C)A&&!(T!=null&&T.durationKnown)?C.endTime=_:Math.abs(C.startTime-E)>.01&&(C.startTime=E,C.endTime=_);else if(o){let $=v.attr[D];$c(D)&&($=wa($));let U=Li(o,E,_,{key:D,data:$},De.dateRange);U&&(U.id=y,this.id3Track.addCue(U),x[D]=U,a&&(D==="X-ASSET-LIST"||D==="X-ASSET-URL")&&U.addEventListener("enter",this.onEventCueEnter))}}h[y]={cues:x,dateRange:v,durationKnown:A}}}}},Kn=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;let i=this.computeLatency();if(i===null)return;this._latency=i;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!s.live)return;let o=this.targetLatency;if(o===null)return;let c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){let h=Math.min(2,Math.max(1,a)),u=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,g=Math.min(h,Math.max(1,u));this.changeMediaPlaybackRate(t,g)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,c=this.hls.userConfig,l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=n!==void 0?n:a*i);let d=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let s=this.levelDetails;if(s===null)return null;let i=s.edge,n=e-t-this.edgeStalled,a=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.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)return 0;let t=(this.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 s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.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}},Vn=class extends Xt{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let s=this.hls.config.preferManagedMediaSource,i=[],n={},a={},o=!1,c=!1,l=!1;t.levels.forEach(d=>{let h=d.attrs,{audioCodec:u,videoCodec:g}=d;u&&(d.audioCodec=u=As(u,s)||void 0),g&&(g=d.videoCodec=lc(g));let{width:f,height:p,unknownCodecs:y}=d,v=y?.length||0;if(o||(o=!!(f&&p)),c||(c=!!g),l||(l=!!u),v||u&&!this.isAudioSupported(u)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}let{CODECS:E,"FRAME-RATE":T,"HDCP-LEVEL":x,"PATHWAY-ID":A,RESOLUTION:_,"VIDEO-RANGE":S}=h,b=`${`${A||"."}-`}${d.bitrate}-${_}-${T}-${E}-${S}-${x}`;if(n[b])if(n[b].uri!==d.url&&!d.attrs["PATHWAY-ID"]){let L=a[b]+=1;d.attrs["PATHWAY-ID"]=new Array(L+1).join(".");let D=this.createLevel(d);n[b]=D,i.push(D)}else n[b].addGroupId("audio",h.AUDIO),n[b].addGroupId("text",h.SUBTITLES);else{let L=this.createLevel(d);n[b]=L,a[b]=1,i.push(L)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){let t=new gt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){let i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=Ha(i,[])}return t}isAudioSupported(e){return Gt(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Gt(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,n){var a;let o=[],c=[],l=e,d=((a=t.stats)==null?void 0:a.parsing)||{};if((s||i)&&n&&(l=l.filter(({videoCodec:E,videoRange:T,width:x,height:A})=>(!!E||!!(x&&A))&&vc(T))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let E="no level with compatible codecs found in manifest",T=E;t.levels.length&&(T=`one or more CODECS in variant not supported: ${re(t.levels.map(A=>A.attrs.CODECS).filter((A,_,S)=>S.indexOf(A)===_))}`,this.warn(T),E+=` (${T})`);let x=new Error(E);this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:x,reason:T})}}),d.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(E=>!E.audioCodec||this.isAudioSupported(E.audioCodec)),Da(o)),t.subtitles&&(c=t.subtitles,Da(c));let h=l.slice(0);l.sort((E,T)=>{if(E.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(E.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&E.height!==T.height)return E.height-T.height;if(E.frameRate!==T.frameRate)return E.frameRate-T.frameRate;if(E.videoRange!==T.videoRange)return Ls.indexOf(E.videoRange)-Ls.indexOf(T.videoRange);if(E.videoCodec!==T.videoCodec){let x=br(E.videoCodec),A=br(T.videoCodec);if(x!==A)return A-x}if(E.uri===T.uri&&E.codecSet!==T.codecSet){let x=xs(E.codecSet),A=xs(T.codecSet);if(x!==A)return A-x}return E.averageBitrate!==T.averageBitrate?E.averageBitrate-T.averageBitrate:0});let u=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length)){for(let E=0;E<h.length;E++)if(h[E].pathwayId===l[0].pathwayId){u=h[E];break}}this._levels=l;for(let E=0;E<l.length;E++)if(l[E]===u){var g;this._firstLevel=E;let T=u.bitrate,x=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){let A=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);A>x&&x===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}let f=n&&!i,p=this.hls.config,y=!!(p.audioStreamController&&p.audioTrackController),v={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:y&&!f&&o.some(E=>!!E.url)};d.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,v)}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 d=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:d,reason:d.message}),h)return;e=Math.min(e,t.length-1)}let s=this.currentLevelIndex,i=this.currentLevel,n=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&i&&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 ${s}${n?" with Pathway "+n:""}`);let c={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(m.LEVEL_SWITCHING,c);let l=a.details;if(!l||l.live){let d=this.switchParams(a.uri,i?.details,l);this.loadPlaylist(d)}}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(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===Q.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===B.MAIN){let s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[n]))return;let i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;let{level:i,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.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 s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${i}${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||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,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){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let s=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));co(s),this._levels=s,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 i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}};function Da(r){let e={};r.forEach(t=>{let s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Jo(){return self.SourceBuffer||self.WebKitSourceBuffer}function el(){if(!it())return!1;let e=Jo();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Mu(){if(!el())return!1;let r=it();return typeof r?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(Kt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(Kt(e,"audio"))))}function Ou(){var r;let e=Jo();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}var Fu=100,Hn=class extends Yt{constructor(e,t,s){super(e,t,s,"stream-controller",B.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let i=this.media,n=i?i.currentTime:null;if(n===null||!F(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(i,n,B.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(Fu),this.level=-1,!this.startFragRequested){let n=i.startLevel;n===-1&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{let{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.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:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[n]))return;let a=s[n],o=this.getMainFwdBufferInfo();if(o===null)return;let c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){let p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=P.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 l=a.details;if(!l||this.state===P.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}let d=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let u=this.backtrackFragment?this.backtrackFragment.start:o.end,g=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&g&&de(g)&&this.fragmentTracker.getState(g)!==fe.OK){var f;let y=((f=this.backtrackFragment)!=null?f:g).sn-l.startSN,v=l.fragments[y-1];v&&g.cc===v.cc&&(g=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,u)){if(!g.gap){let y=this.audioOnly&&!this.altAudio?ne.AUDIO:ne.VIDEO,v=(y===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,B.MAIN)}g=this.getNextFragmentLoopLoading(g,l,o,B.MAIN,h)}g&&(this.exceedsMaxBuffer(o,h,g)||(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,a,u)))}loadFragment(e,t,s){let i=this.fragmentTracker.getState(e);i===fe.NOT_LOADED||i===fe.PARTIAL?de(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,B.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let s,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;let a=this.getBufferedFrag(t.currentTime+s);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,d=Math.max(a.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let s=t.media;Le(s,"playing",this.onMediaPlaying),Le(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:s}=this;s&&(be(s,"playing",this.onMediaPlaying),be(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Ou(),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:s}=this;if(!s||this.state!==P.IDLE)return;let i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var s;let{levels:i,startFragRequested:n}=this,a=t.level,o=t.details,c=o.totalduration;if(!i){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:${c}`);let l=t.levelInfo,d=this.fragCurrent;d&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let h=0;if(o.live||(s=l.details)!=null&&s.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=o,this.levelLastLoaded=l,n||this.setStartPosition(o,h),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:a}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:s}=this;if(!s)return;let i=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,c=n>=a-t.maxFragLookUpTolerance&&n<=o;if(i!==null&&s.duration>i&&(n<i||!c)){let d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||n<o-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;let h=q.bufferInfo(s,i,0);if(!((l=h.buffered)!=null&&l.length)){s.currentTime=i;return}if(h.start<=n){s.currentTime=i;return}let{nextStart:g}=q.bufferedInfo(h.buffered,n,0);g&&(s.currentTime=g)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:i,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}let c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}let l=o.videoCodec,d=c.PTSKnown||!c.live,h=(t=s.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new Bs(this.hls,B.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,p=f!==-1,y=new Ht(s.level,s.sn,s.stats.chunkCount,n.byteLength,f,p),v=this.initPTS[s.cc];g.push(n,h,u,l,s,i,c.totalduration,d,y,v)}onAudioTrackSwitching(e,t){let s=this.hls,i=this.altAudio!==0;if(bs(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let 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(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let s=bs(t.url,this.hls);if(s){let i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){let s=t.tracks,i,n,a=!1;for(let o in s){let c=s[o];if(c.id==="main"){if(n=o,i=c,o==="video"){let l=s[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:s,part:i}=t,n=s.type===B.MAIN;if(n){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}let o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),de(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}let a=this.media;a&&(!this._hasEnoughToStart&&q.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Q.LEVEL&&(this.state=P.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case R.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 R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ne.AUDIO||!this.altAudio){let s=(t===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,B.MAIN),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,s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}let i=this.timelineOffset;i&&s&&(s+=i);let n=this.getLevelDetails(),a=q.getBuffered(e),o=a.length?a.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_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(s=>{let{hls:i}=this,n=s?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=P.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(),i.trigger(m.FRAG_LOADED,s),n.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:c,level:l}=a,{video:d,text:h,id3:u,initSegment:g}=i,{details:f}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,g){let y=g.tracks;if(y){let x=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(l,y,x,n),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:t,tracks:y})}let v=g.initPTS,E=g.timescale,T=this.initPTS[o.cc];if(F(v)&&(!T||T.baseTime!==v||T.timescale!==E)){let x=g.trackId;this.initPTS[o.cc]={baseTime:v,timescale:E,trackId:x},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:E,trackId:x})}}if(d&&f){p&&d.type==="audiovideo"&&this.logMuxedErr(o);let y=f.fragments[o.sn-1-f.startSN],v=o.sn===f.startSN,E=!y||o.cc>y.cc;if(i.independent!==!1){let{startPTS:T,endPTS:x,startDTS:A,endDTS:_}=d;if(c)c.elementaryStreams[d.type]={startPTS:T,endPTS:x,startDTS:A,endDTS:_};else if(d.firstKeyFrame&&d.independent&&n.id===1&&!E&&(this.couldBacktrack=!0),d.dropped&&d.independent){let S=this.getMainFwdBufferInfo(),I=(S?S.end:this.getLoadPosition())+this.config.maxBufferHole,b=d.firstKeyFramePTS?d.firstKeyFramePTS:T;if(!v&&I<b-this.config.maxBufferHole&&!E){this.backtrack(o);return}else E&&(o.gap=!0);o.setElementaryStreamInfo(d.type,o.start,x,o.start,_,!0)}else v&&T-(f.appliedTimelineOffset||0)>Ts&&(o.gap=!0);o.setElementaryStreamInfo(d.type,T,x,A,_),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,c,n,v||E)}else if(v||E)o.gap=!0;else{this.backtrack(o);return}}if(p){let{startPTS:y,endPTS:v,startDTS:E,endDTS:T}=p;c&&(c.elementaryStreams[ne.AUDIO]={startPTS:y,endPTS:v,startDTS:E,endDTS:T}),o.setElementaryStreamInfo(ne.AUDIO,y,v,E,T),this.bufferFragmentData(p,o,c,n)}if(f&&u!=null&&u.samples.length){let y={id:t,frag:o,details:f,samples:u.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(f&&h){let y={id:t,frag:o,details:f,samples:h.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${de(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));let{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec,d=gs(n.codec,l);d==="mp4a"&&(d="mp4a.40.5");let h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");let u=n.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),l&&l!==d&&this.log(`Swapping manifest audio codec "${l}" for "${d}"`),n.levelCodec=d,n.id=B.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${d||""}/${l||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=B.MAIN;let l=a.codec;if(l?.length===4)switch(l){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||""}/${l}]${a.codec!==l?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let c=Object.keys(t);if(c.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{let h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:h,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,B.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.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=P.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let s=e.currentTime;if(q.isBuffered(e,s)?t=this.getAppendedFrag(s):q.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;let i=this.fragPlaying,n=t.level;(!i||t.sn!==i.sn||i.level!==n)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.level!==n)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:n}))}}}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 F(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(F(t)){let s=this.getLevelDetails(),i=this.currentFrag||(s?pt(null,s.fragments,t):null);if(i){let n=i.programDateTime;if(n!==null){let a=n+(t-i.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}},Yn=class extends Re{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let s in this.keyIdToKeyInfo){let i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=R.KEY_LOAD_ERROR,s,i,n){return new Ue({type:V.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,n=t.length;i<n;i++){let a=t[i];if(e.cc<=a.cc&&(!de(e)||!de(a)||e.sn<a.sn)||!s&&i==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let c=ms(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){let i=Ot(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,l))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=Ii(n),c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return n.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(d=>{let{keyInfo:h}=d;return n.key=h.decryptdata.key,{frag:e,keyInfo:h}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+ve(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){let a=Xl(t.initSegment.data);if(a.length){let o=a[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${ve(o)}`),Dt.setKeyIdForUri(e.decryptdata.uri,o)):(o=Dt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${ve(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!de(t))return Promise.resolve(s);let n=this.emeController.loadKey(s);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){let s=this.config,i=s.loader,n=new i(s);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,g,f,p)=>{let{frag:y,keyInfo:v}=f,E=Ii(v.decryptdata);if(!y.decryptdata||v!==this.keyIdToKeyInfo[E])return o(this.createKeyLoadError(y,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=y.decryptdata.key=new Uint8Array(u.data),y.keyLoader=null,v.loader=null,a({frag:y,keyInfo:v})},onError:(u,g,f,p)=>{this.resetLoader(g),o(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),f,te({url:c.url,data:void 0},u)))},onTimeout:(u,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(u,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};n.load(c,d,h)})}resetLoader(e){let{frag:t,keyInfo:s,url:i}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=null,s.loader=null);let a=Ii(s.decryptdata)||i;delete this.keyIdToKeyInfo[a],n&&n.destroy()}};function Ii(r){if(r.keyFormat!==Ee.FAIRPLAY){let e=r.keyId;if(e)return ve(e)}return r.uri}function ka(r){let{type:e}=r;switch(e){case Q.AUDIO_TRACK:return B.AUDIO;case Q.SUBTITLE_TRACK:return B.SUBTITLE;default:return B.MAIN}}function bi(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Wn=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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,s=t.pLoader,i=t.loader,n=s||i,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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Q.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:s,level:i,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:n,responseType:"text",type:Q.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){let{id:s,groupId:i,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:s,groupId:i,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let s=this.loaders[Q.LEVEL];if(s){let i=s.context;i&&!t.levels.some(n=>n===i.levelOrTrack)&&(s.abort(),delete this.loaders[Q.LEVEL])}}load(e){var t;let s=this.hls.config,i=this.getInternalLoader(e);if(i){let l=this.hls.logger,d=i.context;if(d&&d.levelOrTrack===e.levelOrTrack&&(d.url===e.url||d.deliveryDirectives&&!e.deliveryDirectives)){d.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${d.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let n;if(e.type===Q.MANIFEST?n=s.manifestLoadPolicy.default:n=ie({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),F((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Q.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Q.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Q.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){let d=l.partTarget,h=l.targetduration;if(d&&h){let u=Math.max(d*3,h*.8)*1e3;n=ie({},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},c={onSuccess:(l,d,h,u)=>{let g=this.getInternalLoader(h);this.resetInternalLoader(h.type);let f=l.data;d.parsing.start=performance.now(),ht.isMediaPlaylist(f)||h.type!==Q.MANIFEST?this.handleTrackOrLevelPlaylist(l,d,h,u||null,g):this.handleMasterPlaylist(l,d,h,u)},onError:(l,d,h,u)=>{this.handleNetworkError(d,h,!1,l,u)},onTimeout:(l,d,h)=>{this.handleNetworkError(d,h,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){let n=this.hls,a=e.data,o=bi(e,s),c=ht.parseMasterPlaylist(a,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}let{contentSteering:l,levels:d,sessionData:h,sessionKeys:u,startTimeOffset:g,variableList:f}=c;this.variableList=f,d.forEach(E=>{let{unknownCodecs:T}=E;if(T){let{preferManagedMediaSource:x}=this.hls.config,{audioCodec:A,videoCodec:_}=E;for(let S=T.length;S--;){let I=T[S];Gt(I,"audio",x)?(E.audioCodec=A=A?`${A},${I}`:I,Pt.audio[A.substring(0,4)]=2,T.splice(S,1)):Gt(I,"video",x)&&(E.videoCodec=_=_?`${_},${I}`:I,Pt.video[_.substring(0,4)]=2,T.splice(S,1))}}});let{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=ht.parseMasterPlaylistMedia(a,o,c);p.length&&!p.some(T=>!T.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ae({}),bitrate:0,url:""})),n.trigger(m.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:y,captions:v,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:h,sessionKeys:u,startTimeOffset:g,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,n){let a=this.hls,{id:o,level:c,type:l}=s,d=bi(e,s),h=F(c)?c:F(o)?o:0,u=ka(s),g=ht.parseLevelPlaylist(e.data,d,h,u,0,this.variableList);if(l===Q.MANIFEST){let f={attrs:new ae({}),bitrate:0,details:g,name:"",url:d};g.requestScheduled=t.loading.start+ao(g,0),a.trigger(m.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:d,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,i,n)}handleManifestParsingError(e,t,s,i,n){this.hls.trigger(m.ERROR,{type:V.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===Q.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:n})}handleNetworkError(e,t,s=!1,i,n){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Q.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Q.AUDIO_TRACK||e.type===Q.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=R.UNKNOWN,l=!1,d=this.getInternalLoader(e);switch(e.type){case Q.MANIFEST:c=s?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case Q.LEVEL:c=s?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case Q.AUDIO_TRACK:c=s?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Q.SUBTITLE_TRACK:c=s?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1;break}d&&this.resetInternalLoader(e.type);let h={type:V.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:d,context:e,error:o,networkDetails:t,stats:n};if(i){let u=t?.url||e.url;h.response=te({url:u,data:void 0},i)}this.hls.trigger(m.ERROR,h)}handlePlaylistLoaded(e,t,s,i,n,a){let o=this.hls,{type:c,level:l,levelOrTrack:d,id:h,groupId:u,deliveryDirectives:g}=i,f=bi(t,i),p=ka(i),y=typeof i.level=="number"&&p===B.MAIN?l:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:V.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:i,level:y,parent:p,networkDetails:n,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){let E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:V.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:y,parent:p,networkDetails:n,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Q.MANIFEST:case Q.LEVEL:if(y){if(!d)y=0;else if(d!==o.levels[y]){let E=o.levels.indexOf(d);E>-1&&(y=E)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:d||o.levels[0],level:y||0,id:h||0,stats:s,networkDetails:n,deliveryDirectives:g,withoutMultiVariant:c===Q.MANIFEST});break;case Q.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:u||"",stats:s,networkDetails:n,deliveryDirectives:g});break;case Q.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:u||"",stats:s,networkDetails:n,deliveryDirectives:g});break}}},Ce=class r{static get version(){return Wt}static isMSESupported(){return el()}static isSupported(){return Mu()}static getMediaSource(){return it()}static get Events(){return m}static get MetadataSchema(){return De}static get ErrorTypes(){return V}static get ErrorDetails(){return R}static get DefaultConfig(){return r.defaultConfig?r.defaultConfig:bu}static set DefaultConfig(e){r.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new er,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=$l(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=_u(r.DefaultConfig,e,t);this.userConfig=e,s.progressive&&Pu(s,t);let{abrController:i,bufferController:n,capLevelController:a,errorController:o,fpsController:c}=s,l=new o(this),d=this.abrController=new i(this),h=new Fi(this),u=s.interstitialsController,g=u?this.interstitialsController=new u(this,r):null,f=this.bufferController=new n(this,h),p=this.capLevelController=new a(this),y=new c(this),v=new Wn(this),E=s.contentSteeringController,T=E?new E(this):null,x=this.levelController=new Vn(this,T),A=new Gn(this),_=new Yn(this.config,this.logger),S=this.streamController=new Hn(this,h,_),I=this.gapController=new $n(this,h);p.setStreamController(S),y.setStreamController(S);let b=[v,x,S];g&&b.splice(1,0,g),T&&b.splice(1,0,T),this.networkControllers=b;let L=[d,f,I,p,y,A,h];this.audioTrackController=this.createController(s.audioTrackController,b);let D=s.audioStreamController;D&&b.push(this.audioStreamController=new D(this,h,_)),this.subtitleTrackController=this.createController(s.subtitleTrackController,b);let C=s.subtitleStreamController;C&&b.push(this.subtititleStreamController=new C(this,h,_)),this.createController(s.timelineController,L),_.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController(Kn,L),this.coreComponents=L,b.push(l);let $=l.onErrorOut;typeof $=="function"&&this.on(m.ERROR,$,l),this.on(m.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){let s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;let i=e===m.ERROR;this.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let 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(m.ERROR,{type:V.OTHER_ERROR,details:R.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,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(m.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,s=this._url,i=this._url=qn.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.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 s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}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}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={[B.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[B.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[B.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=jh()),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=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){yc(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 s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this,i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let n=i;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((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 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(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){let s=qa(t);return Ya(e,s,navigator.mediaCapabilities)}};Ce.defaultConfig=void 0;var Xs=[];function dr(r){return r<10?`0${r}`:String(r)}function Nu(r){return`${r.getFullYear()}/${r.getMonth()+1}/${r.getDate()} ${dr(r.getHours())}:${dr(r.getMinutes())}:${dr(r.getSeconds())}`}function ce(r,e){Xs.length>=2e3&&Xs.shift(),Xs.push({time:new Date,category:r,message:e})}function tl(){return Xs.map(r=>`[${Nu(r.time)}] [${r.category}]\uFF1A${r.message}`).join(`
41
+ `)}function Bu(r){return/\.m3u8($|\?)/i.test(r)}var Qs=class{constructor(e,t,s,i={}){this.video=e;this.emitter=t;this.hlsConfig=s;this.callbacks=i;this.hls=null;this.currentSrc=""}load(e){if(this.detachHls(),this.currentSrc=e,ce("\u64AD\u653E\u5668",`\u52A0\u8F7D\u6E90: ${e}`),Bu(e)){if(Ce.isSupported()){this.hls=new Ce(this.hlsConfig),this.hls.on(Ce.Events.MEDIA_ATTACHED,()=>{ce("hls\u4E8B\u4EF6","\u5A92\u4F53\u6210\u529F\u9644\u52A0\u5230\u64AD\u653E\u5668")}),this.hls.on(Ce.Events.ERROR,(t,s)=>{if(ce("hls\u4E8B\u4EF6",`${s.fatal?"\u81F4\u547D":""}\u9519\u8BEF: ${s.type} - ${s.details}`),s.fatal)switch(s.type){case Ce.ErrorTypes.NETWORK_ERROR:this.emitter.emit("error",{type:"hls-network",detail:s});break;case Ce.ErrorTypes.MEDIA_ERROR:this.hls?.recoverMediaError();break;default:this.emitter.emit("error",{type:"hls-fatal",detail:s}),this.detachHls()}}),this.hls.on(Ce.Events.MANIFEST_PARSED,()=>{ce("hls\u4E8B\u4EF6","\u64AD\u653E\u6E05\u5355\u89E3\u6790\u5B8C\u6BD5"),this.notifyTracks()}),this.hls.on(Ce.Events.BUFFER_CREATED,()=>{ce("hls\u4E8B\u4EF6","\u7F13\u51B2\u533A\u521B\u5EFA")}),this.hls.on(Ce.Events.LEVEL_SWITCHED,(t,s)=>{let i=this.hls?.levels[s.level],n=i?.height?`${i.height}P`:`Level ${s.level}`;ce("hls\u4E8B\u4EF6",`\u753B\u8D28\u6863\u4F4D\u5207\u6362: ${n}`)}),this.hls.loadSource(e),this.hls.attachMedia(this.video);return}if(this.video.canPlayType("application/vnd.apple.mpegurl")){this.video.src=e;return}this.emitter.emit("error",{type:"hls-unsupported"});return}this.video.src=e}reload(){this.currentSrc&&this.load(this.currentSrc)}notifyTracks(){if(this.hls){if(this.hls.levels.length>1&&this.callbacks.onLevels){let e=this.hls.levels.map((t,s)=>({index:s,height:t.height,bitrate:t.bitrate,label:t.height?`${t.height}P`:`${Math.round(t.bitrate/1e3)}kbps`})).sort((t,s)=>s.height-t.height);this.callbacks.onLevels(e)}this.hls.audioTracks.length>1&&this.callbacks.onAudioTracks&&this.callbacks.onAudioTracks(this.hls.audioTracks.map((e,t)=>({index:t,label:e.name||e.lang||`Track ${t+1}`})))}}setLevel(e){this.hls&&(this.hls.currentLevel=e)}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}get bandwidthEstimate(){return this.hls?.bandwidthEstimate}get currentLevelInfo(){if(!this.hls||this.hls.currentLevel<0)return;let e=this.hls.levels[this.hls.currentLevel];if(e)return`${e.width}x${e.height}@${Math.round(e.bitrate/1e3)}kbps`}detachHls(){this.hls&&(this.hls.destroy(),this.hls=null)}destroy(){this.detachHls(),this.video.removeAttribute("src"),this.video.load()}};function $u(r){return r instanceof HTMLElement?r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.tagName==="SELECT"||r.isContentEditable:!1}var Zs=class{constructor(e,t,s){this.container=e;this.actions=t;this.options=s;this.holdDirection=0;this.holdStart=0;this.accumulated=0;this.tickTimer=null;this.hovering=!1;this.onKeyDown=e=>this.handleKeyDown(e);this.onKeyUp=e=>this.handleKeyUp(e);this.onEnter=()=>this.hovering=!0;this.onLeave=()=>this.hovering=!1;document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),e.addEventListener("mouseenter",this.onEnter),e.addEventListener("mouseleave",this.onLeave)}isScoped(e){return $u(e.target)?!1:this.hovering||this.container.contains(document.activeElement)}handleKeyDown(e){if(this.isScoped(e))switch(e.key){case" ":e.preventDefault(),e.repeat||this.actions.togglePlay();break;case"ArrowLeft":case"ArrowRight":{if(e.preventDefault(),e.repeat)return;this.startHold(e.key==="ArrowRight"?1:-1);break}case"ArrowUp":e.preventDefault(),this.actions.adjustVolume(5);break;case"ArrowDown":e.preventDefault(),this.actions.adjustVolume(-5);break;case"f":case"F":e.repeat||this.actions.toggleFullscreen();break;case"m":case"M":e.repeat||this.actions.toggleMute();break}}handleKeyUp(e){if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;let t=e.key==="ArrowRight"?1:-1;this.holdDirection===t&&this.endHold()}startHold(e){this.holdDirection!==0&&this.endHold(),this.holdDirection=e,this.holdStart=performance.now(),this.accumulated=0,this.tickTimer=setInterval(()=>{let t=performance.now()-this.holdStart;if(t<300)return;let{longSeekSteps:s,stepUpInterval:i}=this.options,n=Math.min(Math.floor((t-300)/i),s.length-1),a=s[n];this.accumulated+=a*(250/1e3)*this.holdDirection,this.actions.onLongSeekProgress(Math.round(this.accumulated))},250)}endHold(){this.tickTimer&&(clearInterval(this.tickTimer),this.tickTimer=null);let e=performance.now()-this.holdStart,t=this.holdDirection;this.holdDirection=0,e<300?this.actions.seekBy(this.options.seekStep*t):this.actions.onLongSeekCommit(Math.round(this.accumulated)),this.accumulated=0}destroy(){this.tickTimer&&clearInterval(this.tickTimer),document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("keyup",this.onKeyUp),this.container.removeEventListener("mouseenter",this.onEnter),this.container.removeEventListener("mouseleave",this.onLeave)}};var Js=class{constructor(e,t,s,i){this.container=e;this.video=t;this.actions=s;this.seekStep=i;this.startX=0;this.startY=0;this.mode="none";this.pendingDelta=0;this.lastTapTime=0;this.lastTapX=0;this.singleTapTimer=null;this.onPointerDown=e=>this.handleDown(e);this.onPointerMove=e=>this.handleMove(e);this.onPointerUp=e=>this.handleUp(e);e.addEventListener("pointerdown",this.onPointerDown),e.addEventListener("pointermove",this.onPointerMove),e.addEventListener("pointerup",this.onPointerUp),e.addEventListener("pointercancel",this.onPointerUp)}isOnVideoSurface(e){return e.target===this.video||e.target===this.container}handleDown(e){e.pointerType!=="touch"||!this.isOnVideoSurface(e)||(this.startX=e.clientX,this.startY=e.clientY,this.mode="none",this.pendingDelta=0)}handleMove(e){if(e.pointerType!=="touch"||this.mode==="none"&&!this.isOnVideoSurface(e))return;let t=e.clientX-this.startX,s=e.clientY-this.startY,i=this.container.getBoundingClientRect();if(this.mode==="none"&&(Math.abs(t)>12&&Math.abs(t)>Math.abs(s)?this.mode="seek":Math.abs(s)>12&&Math.abs(s)>Math.abs(t)&&this.startX-i.left>i.width/2&&(this.mode="volume"),this.mode!=="none"&&this.container.setPointerCapture(e.pointerId)),this.mode==="seek")this.pendingDelta=Math.round(t/i.width*120),this.actions.onSeekPreview(this.pendingDelta);else if(this.mode==="volume"){let n=Math.round(-(e.clientY-this.startY)/i.height*100);n!==0&&(this.actions.adjustVolume(n),this.startY=e.clientY)}}handleUp(e){e.pointerType==="touch"&&(this.mode==="seek"?this.actions.onSeekCommit(this.pendingDelta):this.mode==="none"&&this.isOnVideoSurface(e)&&this.handleTap(e),this.mode="none",this.pendingDelta=0)}handleTap(e){let t=Date.now(),s=this.container.getBoundingClientRect();if(t-this.lastTapTime<280&&Math.abs(e.clientX-this.lastTapX)<60){this.singleTapTimer&&(clearTimeout(this.singleTapTimer),this.singleTapTimer=null),this.lastTapTime=0;let i=(e.clientX-s.left)/s.width;i<1/3?this.actions.seekBy(-this.seekStep):i>2/3?this.actions.seekBy(this.seekStep):this.actions.toggleFullscreen();return}this.lastTapTime=t,this.lastTapX=e.clientX,this.singleTapTimer=setTimeout(()=>{this.singleTapTimer=null,this.actions.toggleControls()},280)}destroy(){this.singleTapTimer&&clearTimeout(this.singleTapTimer),this.container.removeEventListener("pointerdown",this.onPointerDown),this.container.removeEventListener("pointermove",this.onPointerMove),this.container.removeEventListener("pointerup",this.onPointerUp),this.container.removeEventListener("pointercancel",this.onPointerUp)}};function ei(r){let e=document;return(e.fullscreenElement??e.webkitFullscreenElement)===r}async function sl(r){let e=document,t=r;ei(r)?await(e.exitFullscreen?.()??e.webkitExitFullscreen?.()):await(t.requestFullscreen?.()??t.webkitRequestFullscreen?.())}function il(r,e){let t=()=>e(ei(r));return document.addEventListener("fullscreenchange",t),document.addEventListener("webkitfullscreenchange",t),()=>{document.removeEventListener("fullscreenchange",t),document.removeEventListener("webkitfullscreenchange",t)}}function O(r,{className:e,text:t,html:s,attrs:i,parent:n}={}){let a=document.createElement(r);if(e&&(a.className=e),t&&(a.textContent=t),s&&(a.innerHTML=s),i)for(let[o,c]of Object.entries(i))a.setAttribute(o,c);return n&&n.appendChild(a),a}function Te(r,e="0 0 24 24"){return`<svg viewBox="${e}" fill="currentColor" aria-hidden="true"><path d="${r}"/></svg>`}function Fe(r){if(!Number.isFinite(r)||r<0)return"0:00";let e=Math.floor(r%60),t=Math.floor(r/60%60),s=Math.floor(r/3600),i=s>0?String(t).padStart(2,"0"):String(t),n=String(e).padStart(2,"0");return s>0?`${s}:${i}:${n}`:`${i}:${n}`}function Ze(r,e,t){return Math.min(t,Math.max(e,r))}var he={play:Te("M8 5v14l11-7z"),pause:Te("M6 19h4V5H6v14zm8-14v14h4V5h-4z"),prev:Te("M6 6h2v12H6zm3.5 6l8.5 6V6z"),next:Te("M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"),seekBack:Te("M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"),seekForward:Te("M12 5V1l5 5-5 5V7c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6h2c0 4.42-3.58 8-8 8s-8-3.58-8-8 3.58-8 8-8z"),volumeHigh:Te("M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"),volumeLow:Te("M5 9v6h4l5 5V4L9 9H5zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"),volumeMute:Te("M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"),fullscreen:Te("M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"),fullscreenExit:Te("M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"),pip:Te("M19 7h-8v6h8V7zm2-4H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.98h18v14.03z"),audio:Te("M12 3a9 9 0 0 0-9 9v7c0 1.1.9 2 2 2h4v-8H5v-1c0-3.87 3.13-7 7-7s7 3.13 7 7v1h-4v8h4c1.1 0 2-.9 2-2v-7a9 9 0 0 0-9-9z"),settings:Te("M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65a.5.5 0 0 0 .12-.64l-2-3.46a.5.5 0 0 0-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65A.49.49 0 0 0 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1a.49.49 0 0 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65a.5.5 0 0 0-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46a.5.5 0 0 0-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"),chevronRight:Te("M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"),chevronLeft:Te("M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z")};function nl(r,e){let t=O("div",{className:"sp-progress"}),s=O("div",{className:"sp-progress-track",parent:t}),i=O("div",{className:"sp-progress-buffered",parent:s}),n=O("div",{className:"sp-progress-played",parent:s}),a=O("div",{className:"sp-progress-thumb",parent:s}),o=O("div",{className:"sp-progress-tooltip",text:"0:00",parent:t}),c=!1;function l(f){let p=t.getBoundingClientRect();return Ze((f.clientX-p.left)/p.width,0,1)}function d(f){let p=r.duration||0,y=f??(p?r.currentTime/p:0);n.style.width=`${y*100}%`,a.style.left=`${y*100}%`;let v=0;for(let E=0;E<r.buffered.length;E++)r.buffered.start(E)<=r.currentTime&&r.buffered.end(E)>v&&(v=r.buffered.end(E));i.style.width=p?`${v/p*100}%`:"0%"}function h(f){let p=l(f);o.style.left=`${p*100}%`,o.textContent=Fe(p*(r.duration||0)),c&&d(p)}function u(f){c=!0,t.classList.add("sp-dragging"),t.setPointerCapture(f.pointerId),d(l(f))}function g(f){c&&(c=!1,t.classList.remove("sp-dragging"),e(l(f)*(r.duration||0)))}return t.addEventListener("pointermove",h),t.addEventListener("pointerdown",u),t.addEventListener("pointerup",g),t.addEventListener("pointercancel",()=>{c=!1,t.classList.remove("sp-dragging")}),{el:t,update(){c||d()},destroy(){t.remove()}}}function rl(r){let e=O("div",{className:"sp-volume"}),t=O("button",{className:"sp-btn",html:he.volumeHigh,attrs:{type:"button",title:r.muteTitle,"aria-label":r.muteTitle},parent:e}),s=O("div",{className:"sp-volume-slider",parent:e}),i=O("div",{className:"sp-volume-track",parent:s}),n=O("div",{className:"sp-volume-fill",parent:i}),a=O("div",{className:"sp-volume-thumb",parent:i});t.addEventListener("click",r.onToggleMute);let o=!1;function c(d){let h=i.getBoundingClientRect();return Math.round(Ze((d.clientX-h.left)/h.width,0,1)*100)}i.addEventListener("pointerdown",d=>{o=!0,e.classList.add("sp-dragging"),i.setPointerCapture(d.pointerId),r.onVolumeChange(c(d))}),i.addEventListener("pointermove",d=>{o&&r.onVolumeChange(c(d))});let l=()=>{o=!1,e.classList.remove("sp-dragging")};return i.addEventListener("pointerup",l),i.addEventListener("pointercancel",l),{el:e,update(d,h){let u=h?0:d;n.style.width=`${u}%`,a.style.left=`${u}%`,t.innerHTML=h||d===0?he.volumeMute:d<50?he.volumeLow:he.volumeHigh}}}function al(r){let e=O("div",{className:"sp-menu sp-settings"}),t=O("button",{className:"sp-btn",html:he.settings,attrs:{type:"button",title:r.buttonTitle,"aria-label":r.buttonTitle},parent:e}),s=O("div",{className:"sp-settings-panel",parent:e}),i=O("div",{className:"sp-settings-main",parent:s}),n=O("div",{className:"sp-settings-sub",parent:s}),a=r.sections,o=null;function c(){i.innerHTML="";for(let f of a){if(f.toggle){let v=O("div",{className:"sp-settings-row sp-settings-toggle-row",attrs:{"data-key":f.key},parent:i});O("span",{className:"sp-settings-label",text:f.label,parent:v});let E=O("div",{className:"sp-toggle"+(f.toggle.checked?" sp-on":""),attrs:{role:"switch","aria-checked":String(f.toggle.checked),tabindex:"0"},parent:v});O("span",{className:"sp-toggle-thumb",parent:E});let T=x=>{x.stopPropagation(),f.toggle.onToggle()};v.addEventListener("click",T),E.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),T(x))});continue}if(f.items.length===0)continue;let p=O("button",{className:"sp-settings-row",attrs:{type:"button","data-key":f.key},parent:i});O("span",{className:"sp-settings-label",text:f.label,parent:p}),O("span",{className:"sp-settings-value",text:f.currentValue,parent:p});let y=O("span",{className:"sp-settings-arrow",parent:p});y.innerHTML=he.chevronRight,p.addEventListener("click",v=>{v.stopPropagation(),d(f.key)})}}function l(f){n.innerHTML="";let p=a.find(E=>E.key===f);if(!p)return;let y=O("button",{className:"sp-settings-back",attrs:{type:"button"},parent:n}),v=O("span",{className:"sp-settings-back-arrow",parent:y});v.innerHTML=he.chevronLeft,O("span",{text:p.label,parent:y}),y.addEventListener("click",E=>{E.stopPropagation(),h()});for(let E of p.items)O("button",{className:"sp-menu-item"+(E.value===p.activeValue?" sp-active":""),text:E.label,attrs:{type:"button"},parent:n}).addEventListener("click",x=>{x.stopPropagation(),u(),p.onSelect(E)})}function d(f){o=f,l(f),i.style.display="none",n.style.display=""}function h(){o=null,i.style.display="",n.style.display="none"}function u(){e.classList.remove("sp-open"),h()}t.addEventListener("click",f=>{f.stopPropagation();let p=!e.classList.contains("sp-open");e.closest(".sp-controls")?.querySelectorAll(".sp-menu.sp-open").forEach(y=>y.classList.remove("sp-open")),p&&(c(),h()),e.classList.toggle("sp-open",p)});let g=()=>u();return document.addEventListener("click",g),s.addEventListener("click",f=>f.stopPropagation()),c(),h(),{el:e,updateSection(f,p){let y=a.find(v=>v.key===f);if(y){if(p.items!==void 0&&(y.items=p.items),p.currentValue!==void 0&&(y.currentValue=p.currentValue),p.activeValue!==void 0&&(y.activeValue=p.activeValue),p.toggle&&(y.toggle?(y.toggle.checked=p.toggle.checked,p.toggle.onToggle&&(y.toggle.onToggle=p.toggle.onToggle)):y.toggle={checked:p.toggle.checked,onToggle:p.toggle.onToggle??(()=>{})}),y.toggle){o||c();return}o===f&&l(f),o||c()}},close:u,destroy(){document.removeEventListener("click",g),e.remove()}}}function ol(r){let{video:e,actions:t,i18n:s,hidden:i}=r,n=S=>!i.has(S),a=O("div",{className:"sp-top"});n("title")&&O("div",{className:"sp-title",text:r.title,parent:a});let o=O("div",{className:"sp-bottom"}),c=nl(e,S=>{e.currentTime=S});n("progress")&&o.appendChild(c.el);let l=O("div",{className:"sp-controls",parent:o}),d=(S,I,b,L=!1,D=!0)=>{let C=O("button",{className:"sp-btn",html:S,attrs:{type:"button",title:I,"aria-label":I},parent:D?l:void 0});return C.disabled=L,C.addEventListener("click",b),C};d(he.prev,s.t("prev"),()=>t.onPrev?.(),!t.onPrev,n("prev")),d(he.seekBack,s.t("seekBack",{n:r.seekStep}),()=>t.seekBy(-r.seekStep),!1,n("seekBack"));let h=d(he.play,s.t("playPause"),t.togglePlay,!1,n("play"));d(he.seekForward,s.t("seekForward",{n:r.seekStep}),()=>t.seekBy(r.seekStep),!1,n("seekForward")),d(he.next,s.t("next"),()=>t.onNext?.(),!t.onNext,n("next"));let u=O("span",{className:"sp-time",text:"0:00 / 0:00",parent:n("time")?l:void 0});O("div",{className:"sp-controls-spacer",parent:l});let g=rl({muteTitle:s.t("mute"),onVolumeChange:t.setVolume,onToggleMute:t.toggleMute});n("volume")&&l.appendChild(g.el);let f=e.playbackRate,p=[],y,v=[],E,T=al({buttonTitle:s.t("settings"),sections:[...n("rate")?[{key:"rate",label:s.t("speed"),currentValue:`${f}x`,items:r.playbackRates.map(S=>({label:`${S}x`,value:S})),activeValue:f,onSelect:S=>t.setRate(S.value)}]:[],...n("quality")?[{key:"quality",label:s.t("quality"),currentValue:s.t("qualityAuto"),items:p,activeValue:y,onSelect:S=>t.selectQuality(S.value)}]:[],...n("ratio")?[{key:"ratio",label:s.t("aspectRatio"),currentValue:s.t("ratioOriginal"),items:r.aspectRatios.map(S=>({label:S==="original"?s.t("ratioOriginal"):S,value:S})),activeValue:"original",onSelect:S=>t.setAspectRatio(S.value)}]:[],...n("audioTrack")?[{key:"audioTrack",label:s.t("audioTrack"),currentValue:"-",items:v,activeValue:E,onSelect:S=>t.selectAudioTrack(S.value)}]:[],...n("pip")&&document.pictureInPictureEnabled?[{key:"pip",label:s.t("pip"),currentValue:"",items:[],activeValue:void 0,onSelect:()=>{},toggle:{checked:!1,onToggle:()=>t.togglePip()}}]:[]]});n("settings")&&l.appendChild(T.el);let x=d(he.fullscreen,s.t("fullscreen"),t.toggleFullscreen,!1,n("fullscreen")),A={el:document.createElement("div"),setItems(S){p=S;let I=y?S.find(b=>b.value===y)?.label:s.t("qualityAuto");T.updateSection("quality",{items:S,currentValue:I??s.t("qualityAuto")})},setActive(S){y=S;let I=p.find(b=>b.value===S)?.label??s.t("qualityAuto");T.updateSection("quality",{activeValue:S,currentValue:I})},setButtonContent(){},close(){}},_={el:document.createElement("div"),setItems(S){v=S;let I=E?S.find(b=>b.value===E)?.label:"-";T.updateSection("audioTrack",{items:S,currentValue:I??"-"})},setActive(S){E=S;let I=v.find(b=>b.value===S)?.label??"-";T.updateSection("audioTrack",{activeValue:S,currentValue:I})},setButtonContent(){},close(){}};return{topEl:a,bottomEl:o,progress:c,volume:g,qualityMenu:A,audioMenu:_,settingsPanel:T,updatePlayState(S){h.innerHTML=S?he.pause:he.play},updateTime(){u.textContent=`${Fe(e.currentTime)} / ${Fe(e.duration)}`,c.update()},updateRate(S){f=S,T.updateSection("rate",{activeValue:S,currentValue:`${S}x`})},updateFullscreen(S){x.innerHTML=S?he.fullscreenExit:he.fullscreen},updatePip(S){T.updateSection("pip",{toggle:{checked:S}})},updateRatio(S){let I=S==="original"?s.t("ratioOriginal"):S;T.updateSection("ratio",{activeValue:S,currentValue:I})},destroy(){T.destroy(),a.remove(),o.remove()}}}function ll(){let r=O("div",{className:"sp-osd"}),e=null;function t(i){e&&(clearTimeout(e),e=null),r.textContent=i,r.classList.add("sp-visible")}function s(){r.classList.remove("sp-visible")}return{el:r,show:t,hide:s,flash(i){t(i),e=setTimeout(s,800)}}}function cl(r,e){let t=O("div",{className:"sp-context-menu",parent:r});for(let o of e)O("button",{className:"sp-context-item",text:o.label,attrs:{type:"button"},parent:t}).addEventListener("click",()=>{i(),o.onClick()});function s(o,c){t.classList.add("sp-visible");let l=r.getBoundingClientRect(),d=Math.max(4,Math.min(o-l.left,l.width-t.offsetWidth-4)),h=Math.max(4,Math.min(c-l.top,l.height-t.offsetHeight-4));t.style.left=`${d}px`,t.style.top=`${h}px`}function i(){t.classList.remove("sp-visible")}let n=o=>{o.preventDefault(),s(o.clientX,o.clientY)},a=o=>{t.contains(o.target)||i()};return r.addEventListener("contextmenu",n),document.addEventListener("pointerdown",a,!0),{hide:i,destroy(){r.removeEventListener("contextmenu",n),document.removeEventListener("pointerdown",a,!0),t.remove()}}}function dl(r,e,t){let s=null;function i(){if(s)return;s=O("div",{className:"sp-shortcuts",parent:r}),O("button",{className:"sp-shortcuts-close",text:"\u2715",attrs:{type:"button","aria-label":e.t("close")},parent:s}).addEventListener("click",n),O("div",{className:"sp-shortcuts-title",text:e.t("shortcuts"),parent:s});let o=O("dl",{className:"sp-shortcuts-body",parent:s}),c=[[e.t("scKeySpace"),e.t("scPlayPause")],["\u2190 / \u2192",e.t("scSeek",{n:t})],[e.t("scKeyHold"),e.t("scLongSeek")],["\u2191 / \u2193",e.t("scVolume")],["F",e.t("scFullscreen")],["M",e.t("scMute")]];for(let[l,d]of c){let h=O("div",{className:"sp-shortcuts-row",parent:o}),u=O("dt",{parent:h});O("span",{className:"sp-kbd",text:l,parent:u}),O("dd",{text:d,parent:h})}}function n(){s?.remove(),s=null}return{toggle(){s?n():i()},hide:n,destroy:n}}function hl(r,e,t,s){let i=null,n=null;function a(){let d=e.getVideoPlaybackQuality?.(),h=[];for(let g=0;g<e.buffered.length;g++)h.push(`${Fe(e.buffered.start(g))}-${Fe(e.buffered.end(g))}`);let u=t.bandwidthEstimate;return[["Video Res",`${e.videoWidth}x${e.videoHeight}`],["Viewport",`${r.clientWidth}x${r.clientHeight}`],["Time",`${Fe(e.currentTime)} / ${Fe(e.duration)}`],["Buffered",h.join(", ")||"-"],["Dropped Frames",d?`${d.droppedVideoFrames} / ${d.totalVideoFrames}`:"N/A"],["Bandwidth",u?`${(u/1e3/1e3).toFixed(2)} Mbps`:"N/A"],["HLS Level",t.currentLevelInfo??"N/A"],["Speed",`${e.playbackRate}x`],["Volume",e.muted?"muted":`${Math.round(e.volume*100)}%`],["Ready State",String(e.readyState)],["Source",e.currentSrc||"-"]]}function o(){if(!i)return;let d=i.querySelector(".sp-stats-body");d.innerHTML="";for(let[h,u]of a()){let g=O("div",{className:"sp-stats-row",parent:d});O("dt",{text:h,parent:g}),O("dd",{text:u,parent:g})}}function c(){if(i)return;i=O("div",{className:"sp-stats",parent:r});let d=O("div",{className:"sp-stats-header",parent:i}),h=O("button",{className:"sp-stats-copy",text:s.t("copyLog"),attrs:{type:"button"},parent:d});h.addEventListener("click",()=>{let g=tl();navigator.clipboard.writeText(g||"(empty)").then(()=>{h.textContent=s.t("logCopied"),setTimeout(()=>{h.textContent=s.t("copyLog")},1500)},()=>{})}),O("button",{className:"sp-stats-close",text:"\u2715",attrs:{type:"button","aria-label":s.t("closeStats")},parent:d}).addEventListener("click",l),O("dl",{className:"sp-stats-body",parent:i}),o(),n=setInterval(o,500)}function l(){n&&(clearInterval(n),n=null),i?.remove(),i=null}return{toggle(){i?l():c()},hide:l,destroy:l}}function ul(r){let e=O("div",{className:"sp-state"}),t=O("div",{className:"sp-spinner",parent:e});t.innerHTML='<div class="sp-spinner-ring"></div>';let s=null,i=null,n=null;function a(){n&&(clearInterval(n),n=null)}function o(){s?.remove(),s=null}function c(){a(),i?.remove(),i=null}return{el:e,showLoading(){e.classList.add("sp-loading")},hideLoading(){e.classList.remove("sp-loading")},showError(l){o(),c(),e.classList.remove("sp-loading"),s=O("div",{className:"sp-state-panel",parent:e}),O("div",{className:"sp-state-message",text:r.t("loadError"),parent:s}),O("button",{className:"sp-state-btn",text:r.t("retry"),attrs:{type:"button"},parent:s}).addEventListener("click",()=>{o(),l()})},hideError:o,showEnded({onReplay:l,onNext:d,autoNextSeconds:h}){c(),o(),e.classList.remove("sp-loading"),i=O("div",{className:"sp-state-panel",parent:e});let u=O("div",{className:"sp-state-actions",parent:i});if(O("button",{className:"sp-state-btn",text:r.t("replay"),attrs:{type:"button"},parent:u}).addEventListener("click",()=>{c(),l()}),d&&(O("button",{className:"sp-state-btn sp-state-btn-primary",text:r.t("playNext"),attrs:{type:"button"},parent:u}).addEventListener("click",()=>{c(),d()}),h&&h>0)){let p=h,y=O("div",{className:"sp-state-countdown",text:r.t("autoNextIn",{n:p}),parent:i});O("button",{className:"sp-state-cancel",text:r.t("cancel"),attrs:{type:"button"},parent:y}).addEventListener("click",()=>{a(),y.remove()}),n=setInterval(()=>{p-=1,p<=0?(c(),d()):y.firstChild.textContent=r.t("autoNextIn",{n:p})},1e3)}},hideEnded:c,destroy(){a(),e.remove()}}}var fl={play:"\u64AD\u653E",pause:"\u6682\u505C",playPause:"\u64AD\u653E/\u6682\u505C (\u7A7A\u683C)",prev:"\u4E0A\u4E00\u4E2A",next:"\u4E0B\u4E00\u4E2A",seekBack:"\u5FEB\u9000 {n} \u79D2 (\u2190)",seekForward:"\u5FEB\u8FDB {n} \u79D2 (\u2192)",speed:"\u64AD\u653E\u500D\u901F",quality:"\u753B\u8D28",qualityAuto:"\u81EA\u52A8",aspectRatio:"\u753B\u9762\u6BD4\u4F8B",ratioOriginal:"\u539F\u59CB",audioTrack:"\u97F3\u8F68",mute:"\u9759\u97F3 (M)",fullscreen:"\u5168\u5C4F (F)",pip:"\u753B\u4E2D\u753B (P)",empty:"\u6682\u65E0\u53EF\u9009\u9879",closeStats:"\u5173\u95ED\u7EDF\u8BA1\u4FE1\u606F",seconds:"\u79D2",volume:"\u97F3\u91CF",muted:"\u9759\u97F3",replay:"\u91CD\u65B0\u64AD\u653E",playNext:"\u64AD\u653E\u4E0B\u4E00\u4E2A",autoNextIn:"{n} \u79D2\u540E\u64AD\u653E\u4E0B\u4E00\u4E2A",cancel:"\u53D6\u6D88",loadError:"\u89C6\u9891\u52A0\u8F7D\u5931\u8D25",retry:"\u91CD\u8BD5",changelog:"\u66F4\u65B0\u8BB0\u5F55",videoInfo:"\u89C6\u9891\u4FE1\u606F",shortcuts:"\u5FEB\u6377\u952E",close:"\u5173\u95ED",scKeySpace:"\u7A7A\u683C",scKeyHold:"\u2190 / \u2192 \u957F\u6309",scPlayPause:"\u64AD\u653E / \u6682\u505C",scSeek:"\u5FEB\u9000 / \u5FEB\u8FDB {n} \u79D2",scLongSeek:"\u9636\u68AF\u7D2F\u8BA1\u5FEB\u8FDB\u5FEB\u9000\uFF0C\u677E\u5F00\u6267\u884C",scVolume:"\u97F3\u91CF \xB15",scFullscreen:"\u5168\u5C4F\u5207\u6362",scMute:"\u9759\u97F3\u5207\u6362",settings:"\u8BBE\u7F6E",copyLog:"\u590D\u5236\u65E5\u5FD7",logCopied:"\u5DF2\u590D\u5236"},Uu={play:"Play",pause:"Pause",playPause:"Play/Pause (Space)",prev:"Previous",next:"Next",seekBack:"Rewind {n}s (\u2190)",seekForward:"Forward {n}s (\u2192)",speed:"Playback speed",quality:"Quality",qualityAuto:"Auto",aspectRatio:"Aspect ratio",ratioOriginal:"Original",audioTrack:"Audio track",mute:"Mute (M)",fullscreen:"Fullscreen (F)",pip:"Picture-in-Picture (P)",empty:"Nothing available",closeStats:"Close stats",seconds:"s",volume:"Volume",muted:"Muted",replay:"Replay",playNext:"Play next",autoNextIn:"Playing next in {n}s",cancel:"Cancel",loadError:"Failed to load video",retry:"Retry",changelog:"Changelog",videoInfo:"Video info",shortcuts:"Shortcuts",close:"Close",scKeySpace:"Space",scKeyHold:"Hold \u2190 / \u2192",scPlayPause:"Play / Pause",scSeek:"Rewind / forward {n}s",scLongSeek:"Accelerating seek, release to apply",scVolume:"Volume \xB15",scFullscreen:"Toggle fullscreen",scMute:"Toggle mute",settings:"Settings",copyLog:"Copy log",logCopied:"Copied"},Gu={"zh-CN":fl,en:Uu},ti=class{constructor(e="zh-CN",t){this.strings={...Gu[e]??fl,...t}}t(e,t){let s=this.strings[e];if(t)for(let[i,n]of Object.entries(t))s=s.replace(`{${i}}`,String(n));return s}};var gl="sweet-player-style";function pl(r){if(typeof document>"u"||document.getElementById(gl))return;let e=document.createElement("style");e.id=gl,e.textContent=r,document.head.appendChild(e)}var ml="sweet-player:prefs",hr="sweet-player:progress:";function yl(r){try{return localStorage.getItem(r)}catch{return null}}function vl(r,e){try{localStorage.setItem(r,e)}catch{}}function ur(){let r=yl(ml);if(!r)return{};try{return JSON.parse(r)}catch{return{}}}function fr(r){vl(ml,JSON.stringify({...ur(),...r}))}function El(r){let e=yl(hr+r),t=e===null?NaN:Number(e);return Number.isFinite(t)?t:null}function Tl(r,e){vl(hr+r,String(Math.floor(e)))}function Sl(r){try{localStorage.removeItem(hr+r)}catch{}}var gr="0.4.0";var xl=`.sweet-player {
41
42
  --sp-accent: #ff4d6d;
42
43
  --sp-bg: #000;
43
44
  --sp-text: #fff;
@@ -127,10 +128,33 @@ Schedule: ${c.map(p=>Fe(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
127
128
  pointer-events: auto;
128
129
  }
129
130
 
131
+ .sp-stats-header {
132
+ display: flex;
133
+ justify-content: flex-end;
134
+ align-items: center;
135
+ gap: 4px;
136
+ margin: -4px -6px 4px 0;
137
+ }
138
+
139
+ .sp-stats-copy {
140
+ border: none;
141
+ background: transparent;
142
+ color: var(--sp-text);
143
+ cursor: pointer;
144
+ opacity: 0.7;
145
+ font-size: 12px;
146
+ line-height: 22px;
147
+ padding: 0 6px;
148
+ border-radius: 3px;
149
+ white-space: nowrap;
150
+ }
151
+
152
+ .sp-stats-copy:hover {
153
+ opacity: 1;
154
+ background: rgba(255, 255, 255, 0.1);
155
+ }
156
+
130
157
  .sp-stats-close {
131
- position: absolute;
132
- top: 6px;
133
- right: 6px;
134
158
  width: 22px;
135
159
  height: 22px;
136
160
  border: none;
@@ -140,6 +164,7 @@ Schedule: ${c.map(p=>Fe(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
140
164
  opacity: 0.7;
141
165
  font-size: 16px;
142
166
  line-height: 1;
167
+ flex-shrink: 0;
143
168
  }
144
169
 
145
170
  .sp-stats-close:hover {
@@ -162,6 +187,113 @@ Schedule: ${c.map(p=>Fe(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
162
187
  word-break: break-all;
163
188
  }
164
189
 
190
+ /* ---------- \u5FEB\u6377\u952E\u9762\u677F ---------- */
191
+ .sp-shortcuts {
192
+ position: absolute;
193
+ top: 50%;
194
+ left: 50%;
195
+ transform: translate(-50%, -50%);
196
+ z-index: 30;
197
+ min-width: 280px;
198
+ max-width: calc(100% - 24px);
199
+ max-height: calc(100% - 24px);
200
+ overflow-y: auto;
201
+ padding: 14px 20px 14px;
202
+ background: rgba(0, 0, 0, 0.8);
203
+ border-radius: 8px;
204
+ font-size: 13px;
205
+ line-height: 2.1;
206
+ pointer-events: auto;
207
+ }
208
+
209
+ .sp-shortcuts-title {
210
+ font-size: 14px;
211
+ font-weight: 600;
212
+ margin-bottom: 6px;
213
+ }
214
+
215
+ .sp-shortcuts-body {
216
+ margin: 0;
217
+ }
218
+
219
+ .sp-shortcuts-row {
220
+ display: flex;
221
+ align-items: center;
222
+ gap: 16px;
223
+ }
224
+
225
+ .sp-shortcuts-row dt {
226
+ flex: 0 0 100px;
227
+ margin: 0;
228
+ }
229
+
230
+ .sp-shortcuts-row dd {
231
+ margin: 0;
232
+ opacity: 0.85;
233
+ }
234
+
235
+ .sp-kbd {
236
+ display: inline-block;
237
+ padding: 0 7px;
238
+ background: rgba(255, 255, 255, 0.15);
239
+ border-radius: 4px;
240
+ font-family: 'SFMono-Regular', Consolas, monospace;
241
+ font-size: 12px;
242
+ line-height: 20px;
243
+ white-space: nowrap;
244
+ }
245
+
246
+ .sp-shortcuts-close {
247
+ position: absolute;
248
+ top: 8px;
249
+ right: 8px;
250
+ width: 22px;
251
+ height: 22px;
252
+ border: none;
253
+ background: transparent;
254
+ color: var(--sp-text);
255
+ cursor: pointer;
256
+ opacity: 0.7;
257
+ font-size: 16px;
258
+ line-height: 1;
259
+ }
260
+
261
+ .sp-shortcuts-close:hover {
262
+ opacity: 1;
263
+ }
264
+
265
+ /* ---------- \u53F3\u952E\u83DC\u5355 ---------- */
266
+ .sp-context-menu {
267
+ position: absolute;
268
+ z-index: 40;
269
+ min-width: 150px;
270
+ padding: 4px 0;
271
+ background: rgba(28, 28, 28, 0.95);
272
+ border-radius: 6px;
273
+ display: none;
274
+ }
275
+
276
+ .sp-context-menu.sp-visible {
277
+ display: block;
278
+ }
279
+
280
+ .sp-context-item {
281
+ display: block;
282
+ width: 100%;
283
+ padding: 8px 16px;
284
+ border: none;
285
+ background: transparent;
286
+ color: var(--sp-text);
287
+ text-align: left;
288
+ cursor: pointer;
289
+ font-size: 13px;
290
+ white-space: nowrap;
291
+ }
292
+
293
+ .sp-context-item:hover {
294
+ background: rgba(255, 255, 255, 0.12);
295
+ }
296
+
165
297
  /* ---------- \u4E2D\u592E OSD \u53CD\u9988 ---------- */
166
298
  .sp-osd {
167
299
  position: absolute;
@@ -489,6 +621,137 @@ Schedule: ${c.map(p=>Fe(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
489
621
  padding: 2px 6px;
490
622
  }
491
623
 
624
+ /* ---------- \u8BBE\u7F6E\u9762\u677F ---------- */
625
+ .sp-settings-panel {
626
+ position: absolute;
627
+ bottom: calc(100% + 8px);
628
+ right: 0;
629
+ width: 180px;
630
+ background: rgba(28, 28, 28, 0.95);
631
+ border-radius: 6px;
632
+ padding: 4px 0;
633
+ display: none;
634
+ z-index: 25;
635
+ }
636
+
637
+ .sp-settings.sp-open .sp-settings-panel {
638
+ display: block;
639
+ }
640
+
641
+ .sp-settings-row {
642
+ display: flex;
643
+ align-items: center;
644
+ width: 100%;
645
+ padding: 7px 12px;
646
+ border: none;
647
+ background: transparent;
648
+ color: var(--sp-text);
649
+ cursor: pointer;
650
+ font-size: 13px;
651
+ white-space: nowrap;
652
+ gap: 4px;
653
+ }
654
+
655
+ .sp-settings-row:hover {
656
+ background: rgba(255, 255, 255, 0.12);
657
+ }
658
+
659
+ .sp-settings-label {
660
+ flex: 1;
661
+ text-align: left;
662
+ }
663
+
664
+ .sp-settings-value {
665
+ opacity: 0.6;
666
+ font-size: 12px;
667
+ }
668
+
669
+ .sp-settings-arrow {
670
+ display: inline-flex;
671
+ align-items: center;
672
+ opacity: 0.5;
673
+ }
674
+
675
+ .sp-settings-arrow svg {
676
+ width: 16px;
677
+ height: 16px;
678
+ }
679
+
680
+ .sp-settings-back {
681
+ display: flex;
682
+ align-items: center;
683
+ width: 100%;
684
+ padding: 7px 12px;
685
+ border: none;
686
+ border-bottom: 1px solid rgba(255, 255, 255, 0.1);
687
+ background: transparent;
688
+ color: var(--sp-text);
689
+ cursor: pointer;
690
+ font-size: 13px;
691
+ font-weight: 500;
692
+ gap: 2px;
693
+ margin-bottom: 2px;
694
+ }
695
+
696
+ .sp-settings-back:hover {
697
+ background: rgba(255, 255, 255, 0.08);
698
+ }
699
+
700
+ .sp-settings-back-arrow {
701
+ display: inline-flex;
702
+ align-items: center;
703
+ opacity: 0.7;
704
+ }
705
+
706
+ .sp-settings-back-arrow svg {
707
+ width: 18px;
708
+ height: 18px;
709
+ }
710
+
711
+ .sp-settings-sub .sp-menu-item {
712
+ text-align: left;
713
+ padding: 7px 16px;
714
+ }
715
+
716
+ /* ---------- \u884C\u5185\u5F00\u5173 ---------- */
717
+ .sp-settings-toggle-row {
718
+ cursor: pointer;
719
+ }
720
+
721
+ .sp-toggle {
722
+ position: relative;
723
+ width: 30px;
724
+ height: 17px;
725
+ background: rgba(255, 255, 255, 0.25);
726
+ border-radius: 9px;
727
+ flex-shrink: 0;
728
+ transition: background 0.15s ease;
729
+ outline: none;
730
+ }
731
+
732
+ .sp-toggle:focus-visible {
733
+ box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.4);
734
+ }
735
+
736
+ .sp-toggle.sp-on {
737
+ background: var(--sp-accent);
738
+ }
739
+
740
+ .sp-toggle-thumb {
741
+ position: absolute;
742
+ top: 2px;
743
+ left: 2px;
744
+ width: 13px;
745
+ height: 13px;
746
+ background: #fff;
747
+ border-radius: 50%;
748
+ transition: transform 0.15s ease;
749
+ }
750
+
751
+ .sp-toggle.sp-on .sp-toggle-thumb {
752
+ transform: translateX(13px);
753
+ }
754
+
492
755
  /* ---------- \u97F3\u91CF ---------- */
493
756
  .sp-volume {
494
757
  display: flex;
@@ -537,4 +800,4 @@ Schedule: ${c.map(p=>Fe(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
537
800
  transform: translate(-50%, -50%);
538
801
  pointer-events: none;
539
802
  }
540
- `;var Ou=[.5,1,1.5,2],Fu=["original","21:9","16:9","4:3"],Nu=[10,30,60],Bu=2e3,Uu=5,$u=3e3,Gu=10,Ku=1500,Vu=250,Hu=5e3,pl=10,ei=class{constructor(e){this.emitter=new Jt;this.hideTimer=null;this.clickTimer=null;this.progressTimer=null;this.titleClicks=0;this.lastTitleClick=0;this.currentRatio="original";this.hlsManagedQuality=!1;this.hlsManagedAudio=!1;this.disposers=[];this.pluginCleanups=[];this.destroyed=!1;this.options=e,this.i18n=new Js(e.locale,e.localeStrings);let t=typeof e.container=="string"?document.querySelector(e.container):e.container;if(!t)throw new Error(`[sweet-player] container not found: ${e.container}`);ll(ml),this.container=H("div",{className:"sweet-player",attrs:{tabindex:"0","data-ratio":"original"},parent:t}),this.video=H("video",{className:"sp-video",attrs:{playsinline:""},parent:this.container});let s=e.persist!==!1,i=s?hn():{};this.video.volume=Qe(i.volume??e.volume??100,0,100)/100,this.video.muted=i.muted??e.muted??!1,e.autoplay&&(this.video.autoplay=!0);let r=e.autoQuality!==!1;this.media=new zs(this.video,this.emitter,e.hlsConfig,{onLevels:r&&!e.qualities?.length?o=>this.applyHlsLevels(o):void 0,onAudioTracks:r&&!e.audioTracks?.length?o=>this.applyHlsAudioTracks(o):void 0}),this.osd=il(),this.stats=rl(this.container,this.video,this.media,this.i18n),this.state=nl(this.i18n),this.controls=sl({video:this.video,title:e.title??"",i18n:this.i18n,playbackRates:e.playbackRates??Ou,aspectRatios:e.aspectRatios??Fu,seekStep:e.seekStep??10,actions:{togglePlay:()=>this.toggle(),seekBy:o=>this.seekBy(o),setRate:o=>this.setRate(o),setVolume:o=>this.setVolume(o),toggleMute:()=>this.setMuted(!this.video.muted),setAspectRatio:o=>this.setAspectRatio(o),toggleFullscreen:()=>this.toggleFullscreen(),togglePip:()=>this.togglePip(),selectQuality:o=>this.handleQualitySelect(o),selectAudioTrack:o=>this.handleAudioTrackSelect(o),onPrev:e.onPrev,onNext:e.onNext,onTitleClick:()=>this.handleTitleClick()}}),this.container.appendChild(this.controls.topEl),this.container.appendChild(this.controls.bottomEl),this.container.appendChild(this.state.el),this.container.appendChild(this.osd.el),e.qualities?.length&&this.setQualities(e.qualities),e.audioTracks?.length&&this.setAudioTracks(e.audioTracks);let a=e.seekStep??10;this.keyboard=new Xs(this.container,{togglePlay:()=>this.toggle(),seekBy:o=>this.seekBy(o),onLongSeekProgress:o=>this.osd.show(`${o>0?"+":""}${o} ${this.i18n.t("seconds")}`),onLongSeekCommit:o=>{this.osd.hide(),o!==0&&this.seekBy(o,!1)},adjustVolume:o=>this.setVolume(Math.round(this.video.volume*100)+o),toggleFullscreen:()=>this.toggleFullscreen(),toggleMute:()=>this.setMuted(!this.video.muted)},{seekStep:a,longSeekSteps:e.longSeek?.steps??Nu,stepUpInterval:e.longSeek?.stepUpInterval??Bu}),this.gestures=new Qs(this.container,this.video,{seekBy:o=>this.seekBy(o),onSeekPreview:o=>this.osd.show(`${o>0?"+":""}${o} ${this.i18n.t("seconds")} (${Me(Qe(this.video.currentTime+o,0,this.video.duration||0))})`),onSeekCommit:o=>{this.osd.hide(),o!==0&&this.seekBy(o,!1)},adjustVolume:o=>this.setVolume(Math.round(this.video.volume*100)+o),toggleControls:()=>{this.container.classList.contains("sp-controls-hidden")?this.scheduleHide():this.hideControlsNow()},toggleFullscreen:()=>this.toggleFullscreen()},a),this.bindMediaEvents(),this.bindActivityTracking(),this.disposers.push(Jo(this.container,o=>{this.controls.updateFullscreen(o),this.emitter.emit("fullscreenchange",o)})),s&&i.rate&&(this.video.defaultPlaybackRate=i.rate,this.video.playbackRate=i.rate),this.media.load(e.src),this.controls.volume.update(Math.round(this.video.volume*100),this.video.muted),this.controls.updateRate(this.video.playbackRate),s&&this.bindPersistence(),e.id&&this.bindProgressMemory(e.id),e.plugins?.forEach(o=>this.use(o))}play(){return this.video.play()}pause(){this.video.pause()}toggle(){this.video.paused?this.play().catch(()=>{}):this.pause()}seek(e){this.video.currentTime=Qe(e,0,this.video.duration||0)}seekBy(e,t=!0){this.seek(this.video.currentTime+e),t&&this.osd.flash(`${e>0?"+":""}${e} ${this.i18n.t("seconds")}`)}setRate(e){this.video.playbackRate=e}setVolume(e){let t=Qe(e,0,100);this.video.volume=t/100,t>0&&(this.video.muted=!1),this.osd.flash(`${this.i18n.t("volume")} ${t}%`)}setMuted(e){this.video.muted=e,this.osd.flash(e?this.i18n.t("muted"):`${this.i18n.t("volume")} ${Math.round(this.video.volume*100)}%`)}setAspectRatio(e){this.currentRatio=e,this.container.setAttribute("data-ratio",e),e!=="original"&&this.container.style.setProperty("--sp-forced-ratio",e.replace(":"," / ")),this.controls.updateRatio(e),this.emitter.emit("aspectratiochange",e)}get aspectRatio(){return this.currentRatio}setQualities(e,t){this.hlsManagedQuality=!1,this.controls.qualityMenu.setItems(e.map(s=>({label:s.label,value:s}))),t&&this.controls.qualityMenu.setActive(t)}setAudioTracks(e,t){this.hlsManagedAudio=!1,this.controls.audioMenu.setItems(e.map(s=>({label:s.label,value:s}))),t&&this.controls.audioMenu.setActive(t)}async toggleFullscreen(){await Zo(this.container).catch(()=>{})}get fullscreen(){return Zs(this.container)}async togglePip(){try{document.pictureInPictureElement===this.video?await document.exitPictureInPicture():await this.video.requestPictureInPicture()}catch{}}load(e){this.state.hideEnded(),this.state.hideError(),this.media.load(e)}setTitle(e){let t=this.controls.topEl.querySelector(".sp-title");t&&(t.textContent=e)}use(e){let t=e.apply(this),s=typeof t=="function"?t:()=>{};return this.pluginCleanups.push(s),s}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}destroy(){this.destroyed||(this.destroyed=!0,this.saveProgressNow(),this.emitter.emit("destroy",void 0),this.pluginCleanups.forEach(e=>e()),this.keyboard.destroy(),this.gestures.destroy(),this.stats.destroy(),this.state.destroy(),this.controls.destroy(),this.disposers.forEach(e=>e()),this.hideTimer&&clearTimeout(this.hideTimer),this.clickTimer&&clearTimeout(this.clickTimer),this.progressTimer&&clearInterval(this.progressTimer),this.media.destroy(),this.emitter.removeAll(),this.container.remove())}applyHlsLevels(e){let t={label:this.i18n.t("qualityAuto"),value:-1},s=[t,...e.map(i=>({label:i.label,value:i.index}))];this.setQualities(s,t),this.hlsManagedQuality=!0}applyHlsAudioTracks(e){let t=e.map(s=>({label:s.label,value:s.index}));this.setAudioTracks(t,t[0]),this.hlsManagedAudio=!0}handleQualitySelect(e){if(this.controls.qualityMenu.setActive(e),this.hlsManagedQuality&&typeof e.value=="number")this.media.setLevel(e.value);else if(e.src){let t=this.video.currentTime;this.media.load(e.src),this.video.currentTime=t}this.options.onQualityChange?.(e),this.emitter.emit("qualitychange",e)}handleAudioTrackSelect(e){this.controls.audioMenu.setActive(e),this.hlsManagedAudio&&typeof e.value=="number"&&this.media.setAudioTrack(e.value),this.options.onAudioTrackChange?.(e),this.emitter.emit("audiotrackchange",e)}bindPersistence(){let e=()=>dn({volume:Math.round(this.video.volume*100),muted:this.video.muted}),t=()=>dn({rate:this.video.playbackRate});this.video.addEventListener("volumechange",e),this.video.addEventListener("ratechange",t),this.disposers.push(()=>{this.video.removeEventListener("volumechange",e),this.video.removeEventListener("ratechange",t)})}bindProgressMemory(e){let t=()=>{let s=ul(e);s!==null&&s>3&&s<this.video.duration-pl&&(this.video.currentTime=s)};this.video.addEventListener("loadedmetadata",t,{once:!0}),this.progressTimer=setInterval(()=>{this.video.paused||this.saveProgressNow()},Hu)}saveProgressNow(){let e=this.options.id;!e||!this.video.duration||(this.video.currentTime>=this.video.duration-pl?gl(e):this.video.currentTime>3&&fl(e,this.video.currentTime))}handleTitleClick(){let e=Date.now();this.titleClicks=e-this.lastTitleClick<=Ku?this.titleClicks+1:1,this.lastTitleClick=e,this.titleClicks>=Gu&&(this.titleClicks=0,this.stats.toggle())}bindMediaEvents(){let e=this.video,t=(r,a)=>{e.addEventListener(r,a),this.disposers.push(()=>e.removeEventListener(r,a))};t("loadedmetadata",()=>{this.controls.updateTime(),this.emitter.emit("ready",void 0)}),t("play",()=>{this.state.hideEnded(),this.controls.updatePlayState(!0),this.scheduleHide(),this.emitter.emit("play",void 0)}),t("pause",()=>{this.controls.updatePlayState(!1),this.showControls(),this.emitter.emit("pause",void 0)}),t("ended",()=>{this.saveProgressNow(),this.showControls();let r=this.options.onNext,a=this.options.autoNext;this.state.showEnded({onReplay:()=>{this.seek(0),this.play().catch(()=>{})},onNext:r,autoNextSeconds:r&&a?typeof a=="number"?a:Uu:void 0}),this.emitter.emit("ended",void 0)}),t("timeupdate",()=>{this.controls.updateTime(),this.emitter.emit("timeupdate",{currentTime:e.currentTime,duration:e.duration})}),t("progress",()=>this.controls.progress.update()),t("ratechange",()=>{this.controls.updateRate(e.playbackRate),this.emitter.emit("ratechange",e.playbackRate)}),t("volumechange",()=>{let r=Math.round(e.volume*100);this.controls.volume.update(r,e.muted),this.emitter.emit("volumechange",{volume:r,muted:e.muted})}),t("waiting",()=>this.state.showLoading()),t("stalled",()=>this.state.showLoading()),t("seeking",()=>this.state.showLoading()),t("canplay",()=>this.state.hideLoading()),t("playing",()=>{this.state.hideLoading(),this.state.hideError()}),t("seeked",()=>this.state.hideLoading()),t("error",()=>this.showErrorState({type:"media",detail:e.error})),this.disposers.push(this.emitter.on("error",r=>{r.type.startsWith("hls-")&&this.showErrorStateUi()})),t("enterpictureinpicture",()=>this.emitter.emit("pipchange",!0)),t("leavepictureinpicture",()=>this.emitter.emit("pipchange",!1));let s=r=>{r.target!==this.video||r.pointerType==="touch"||this.clickTimer||(this.clickTimer=setTimeout(()=>{this.clickTimer=null,this.toggle()},Vu))},i=r=>{r.target===this.video&&(this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null),this.toggleFullscreen())};this.container.addEventListener("click",s),this.container.addEventListener("dblclick",i),this.disposers.push(()=>{this.container.removeEventListener("click",s),this.container.removeEventListener("dblclick",i)})}showErrorState(e){this.emitter.emit("error",e),this.showErrorStateUi()}showErrorStateUi(){this.state.hideLoading(),this.state.showError(()=>{let e=this.video.currentTime;this.media.reload(),e>0&&(this.video.currentTime=e),this.play().catch(()=>{})})}showControls(){this.container.classList.remove("sp-controls-hidden"),this.hideTimer&&(clearTimeout(this.hideTimer),this.hideTimer=null)}hideControlsNow(){this.video.paused||this.container.classList.add("sp-controls-hidden")}scheduleHide(){this.showControls(),this.hideTimer=setTimeout(()=>this.hideControlsNow(),$u)}bindActivityTracking(){let e=t=>{t.pointerType!=="touch"&&(this.video.paused?this.showControls():this.scheduleHide())};this.container.addEventListener("pointermove",e),this.container.addEventListener("pointerdown",e),this.disposers.push(()=>{this.container.removeEventListener("pointermove",e),this.container.removeEventListener("pointerdown",e)})}};var Yu=ei;return Ll(Wu);})();
803
+ `;var Vu=[.5,1,1.5,2],Hu=["original","21:9","16:9","4:3"],Yu=[10,30,60],Wu=2e3,qu=5,ju=3e3,zu=250,Xu="https://www.npmjs.com/package/@sweet-player/core",Qu=5e3,Al=10,Zt=class{constructor(e){this.emitter=new es;this.contextMenu=null;this.hideTimer=null;this.clickTimer=null;this.progressTimer=null;this.currentRatio="original";this.hlsManagedQuality=!1;this.hlsManagedAudio=!1;this.disposers=[];this.pluginCleanups=[];this.destroyed=!1;this.options=e,this.i18n=new ti(e.locale,e.localeStrings);let t=typeof e.container=="string"?document.querySelector(e.container):e.container;if(!t)throw new Error(`[sweet-player] container not found: ${e.container}`);pl(xl),this.container=O("div",{className:"sweet-player",attrs:{tabindex:"0","data-ratio":"original"},parent:t}),this.video=O("video",{className:"sp-video",attrs:{playsinline:""},parent:this.container});let s=e.persist!==!1,i=s?ur():{};this.video.volume=Ze(i.volume??e.volume??100,0,100)/100,this.video.muted=i.muted??e.muted??!1,e.autoplay&&(this.video.autoplay=!0);let n=e.autoQuality!==!1;this.media=new Qs(this.video,this.emitter,e.hlsConfig,{onLevels:n&&!e.qualities?.length?c=>this.applyHlsLevels(c):void 0,onAudioTracks:n&&!e.audioTracks?.length?c=>this.applyHlsAudioTracks(c):void 0});let a=new Set(e.hiddenControls??[]);this.osd=ll(),this.stats=hl(this.container,this.video,this.media,this.i18n),this.shortcutsPanel=dl(this.container,this.i18n,e.seekStep??10),this.state=ul(this.i18n),a.has("contextMenu")||(this.contextMenu=cl(this.container,[{label:`${this.i18n.t("changelog")}: v${gr}`,onClick:()=>window.open(Xu,"_blank","noopener")},{label:this.i18n.t("videoInfo"),onClick:()=>this.stats.toggle()},{label:this.i18n.t("shortcuts"),onClick:()=>this.shortcutsPanel.toggle()}])),this.controls=ol({video:this.video,title:e.title??"",i18n:this.i18n,playbackRates:e.playbackRates??Vu,aspectRatios:e.aspectRatios??Hu,seekStep:e.seekStep??10,hidden:a,actions:{togglePlay:()=>this.toggle(),seekBy:c=>this.seekBy(c),setRate:c=>this.setRate(c),setVolume:c=>this.setVolume(c),toggleMute:()=>this.setMuted(!this.video.muted),setAspectRatio:c=>this.setAspectRatio(c),toggleFullscreen:()=>this.toggleFullscreen(),togglePip:()=>this.togglePip(),selectQuality:c=>this.handleQualitySelect(c),selectAudioTrack:c=>this.handleAudioTrackSelect(c),onPrev:e.onPrev,onNext:e.onNext}}),this.container.appendChild(this.controls.topEl),this.container.appendChild(this.controls.bottomEl),this.container.appendChild(this.state.el),this.container.appendChild(this.osd.el),e.qualities?.length&&this.setQualities(e.qualities),e.audioTracks?.length&&this.setAudioTracks(e.audioTracks);let o=e.seekStep??10;this.keyboard=new Zs(this.container,{togglePlay:()=>this.toggle(),seekBy:c=>this.seekBy(c),onLongSeekProgress:c=>this.osd.show(`${c>0?"+":""}${c} ${this.i18n.t("seconds")}`),onLongSeekCommit:c=>{this.osd.hide(),c!==0&&this.seekBy(c,!1)},adjustVolume:c=>this.setVolume(Math.round(this.video.volume*100)+c),toggleFullscreen:()=>this.toggleFullscreen(),toggleMute:()=>this.setMuted(!this.video.muted)},{seekStep:o,longSeekSteps:e.longSeek?.steps??Yu,stepUpInterval:e.longSeek?.stepUpInterval??Wu}),this.gestures=new Js(this.container,this.video,{seekBy:c=>this.seekBy(c),onSeekPreview:c=>this.osd.show(`${c>0?"+":""}${c} ${this.i18n.t("seconds")} (${Fe(Ze(this.video.currentTime+c,0,this.video.duration||0))})`),onSeekCommit:c=>{this.osd.hide(),c!==0&&this.seekBy(c,!1)},adjustVolume:c=>this.setVolume(Math.round(this.video.volume*100)+c),toggleControls:()=>{this.container.classList.contains("sp-controls-hidden")?this.scheduleHide():this.hideControlsNow()},toggleFullscreen:()=>this.toggleFullscreen()},o),this.bindMediaEvents(),this.bindActivityTracking(),this.disposers.push(il(this.container,c=>{ce("\u64AD\u653E\u5668",c?"\u8FDB\u5165\u5168\u5C4F":"\u9000\u51FA\u5168\u5C4F"),this.controls.updateFullscreen(c),this.emitter.emit("fullscreenchange",c)})),s&&i.rate&&(this.video.defaultPlaybackRate=i.rate,this.video.playbackRate=i.rate),this.media.load(e.src),this.controls.volume.update(Math.round(this.video.volume*100),this.video.muted),this.controls.updateRate(this.video.playbackRate),s&&this.bindPersistence(),e.id&&this.bindProgressMemory(e.id),e.plugins?.forEach(c=>this.use(c))}play(){return this.video.play()}pause(){this.video.pause()}toggle(){this.video.paused?this.play().catch(()=>{}):this.pause()}seek(e){this.video.currentTime=Ze(e,0,this.video.duration||0)}seekBy(e,t=!0){this.seek(this.video.currentTime+e),t&&this.osd.flash(`${e>0?"+":""}${e} ${this.i18n.t("seconds")}`)}setRate(e){ce("\u64AD\u653E\u5668",`\u500D\u901F\u5207\u6362: ${e}x`),this.video.playbackRate=e}setVolume(e){let t=Ze(e,0,100);this.video.volume=t/100,t>0&&(this.video.muted=!1),this.osd.flash(`${this.i18n.t("volume")} ${t}%`)}setMuted(e){this.video.muted=e,this.osd.flash(e?this.i18n.t("muted"):`${this.i18n.t("volume")} ${Math.round(this.video.volume*100)}%`)}setAspectRatio(e){this.currentRatio=e,this.container.setAttribute("data-ratio",e),e!=="original"&&this.container.style.setProperty("--sp-forced-ratio",e.replace(":"," / ")),this.controls.updateRatio(e),this.emitter.emit("aspectratiochange",e)}get aspectRatio(){return this.currentRatio}setQualities(e,t){this.hlsManagedQuality=!1,this.controls.qualityMenu.setItems(e.map(s=>({label:s.label,value:s}))),t&&this.controls.qualityMenu.setActive(t)}setAudioTracks(e,t){this.hlsManagedAudio=!1,this.controls.audioMenu.setItems(e.map(s=>({label:s.label,value:s}))),t&&this.controls.audioMenu.setActive(t)}async toggleFullscreen(){await sl(this.container).catch(()=>{})}get fullscreen(){return ei(this.container)}async togglePip(){try{document.pictureInPictureElement===this.video?await document.exitPictureInPicture():await this.video.requestPictureInPicture()}catch{}}load(e){this.state.hideEnded(),this.state.hideError(),this.media.load(e)}setTitle(e){let t=this.controls.topEl.querySelector(".sp-title");t&&(t.textContent=e)}use(e){let t=e.apply(this),s=typeof t=="function"?t:()=>{};return this.pluginCleanups.push(s),s}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}destroy(){this.destroyed||(this.destroyed=!0,this.saveProgressNow(),this.emitter.emit("destroy",void 0),this.pluginCleanups.forEach(e=>e()),this.keyboard.destroy(),this.gestures.destroy(),this.stats.destroy(),this.shortcutsPanel.destroy(),this.state.destroy(),this.contextMenu?.destroy(),this.controls.destroy(),this.disposers.forEach(e=>e()),this.hideTimer&&clearTimeout(this.hideTimer),this.clickTimer&&clearTimeout(this.clickTimer),this.progressTimer&&clearInterval(this.progressTimer),this.media.destroy(),this.emitter.removeAll(),this.container.remove())}applyHlsLevels(e){let t={label:this.i18n.t("qualityAuto"),value:-1},s=[t,...e.map(i=>({label:i.label,value:i.index}))];this.setQualities(s,t),this.hlsManagedQuality=!0}applyHlsAudioTracks(e){let t=e.map(s=>({label:s.label,value:s.index}));this.setAudioTracks(t,t[0]),this.hlsManagedAudio=!0}handleQualitySelect(e){if(ce("\u64AD\u653E\u5668",`\u5207\u6362\u753B\u8D28: ${e.label}`),this.controls.qualityMenu.setActive(e),this.hlsManagedQuality&&typeof e.value=="number")this.media.setLevel(e.value);else if(e.src){let t=this.video.currentTime;this.media.load(e.src),this.video.currentTime=t}this.options.onQualityChange?.(e),this.emitter.emit("qualitychange",e)}handleAudioTrackSelect(e){ce("\u64AD\u653E\u5668",`\u5207\u6362\u97F3\u8F68: ${e.label}`),this.controls.audioMenu.setActive(e),this.hlsManagedAudio&&typeof e.value=="number"&&this.media.setAudioTrack(e.value),this.options.onAudioTrackChange?.(e),this.emitter.emit("audiotrackchange",e)}bindPersistence(){let e=()=>fr({volume:Math.round(this.video.volume*100),muted:this.video.muted}),t=()=>fr({rate:this.video.playbackRate});this.video.addEventListener("volumechange",e),this.video.addEventListener("ratechange",t),this.disposers.push(()=>{this.video.removeEventListener("volumechange",e),this.video.removeEventListener("ratechange",t)})}bindProgressMemory(e){let t=()=>{let s=El(e);s!==null&&s>3&&s<this.video.duration-Al&&(this.video.currentTime=s)};this.video.addEventListener("loadedmetadata",t,{once:!0}),this.progressTimer=setInterval(()=>{this.video.paused||this.saveProgressNow()},Qu)}saveProgressNow(){let e=this.options.id;!e||!this.video.duration||(this.video.currentTime>=this.video.duration-Al?Sl(e):this.video.currentTime>3&&Tl(e,this.video.currentTime))}bindMediaEvents(){let e=this.video,t=(n,a)=>{e.addEventListener(n,a),this.disposers.push(()=>e.removeEventListener(n,a))};t("loadedmetadata",()=>{ce("\u539F\u751F\u4E8B\u4EF6",`\u83B7\u53D6\u5143\u6570\u636E (${e.videoWidth}x${e.videoHeight})`),this.controls.updateTime(),this.emitter.emit("ready",void 0)}),t("play",()=>{this.state.hideEnded(),this.controls.updatePlayState(!0),this.scheduleHide(),this.emitter.emit("play",void 0)}),t("pause",()=>{this.controls.updatePlayState(!1),this.showControls(),this.emitter.emit("pause",void 0)}),t("ended",()=>{ce("\u539F\u751F\u4E8B\u4EF6","\u64AD\u653E\u7ED3\u675F"),this.saveProgressNow(),this.showControls();let n=this.options.onNext,a=this.options.autoNext;this.state.showEnded({onReplay:()=>{this.seek(0),this.play().catch(()=>{})},onNext:n,autoNextSeconds:n&&a?typeof a=="number"?a:qu:void 0}),this.emitter.emit("ended",void 0)}),t("timeupdate",()=>{this.controls.updateTime(),this.emitter.emit("timeupdate",{currentTime:e.currentTime,duration:e.duration})}),t("progress",()=>this.controls.progress.update()),t("ratechange",()=>{this.controls.updateRate(e.playbackRate),this.emitter.emit("ratechange",e.playbackRate)}),t("volumechange",()=>{let n=Math.round(e.volume*100);this.controls.volume.update(n,e.muted),this.emitter.emit("volumechange",{volume:n,muted:e.muted})}),t("waiting",()=>{ce("\u539F\u751F\u4E8B\u4EF6","\u7B49\u5F85\u7F13\u51B2\u4E2D"),this.state.showLoading()}),t("stalled",()=>{ce("\u539F\u751F\u4E8B\u4EF6","\u6570\u636E\u52A0\u8F7D\u505C\u6EDE"),this.state.showLoading()}),t("seeking",()=>{ce("\u539F\u751F\u4E8B\u4EF6","\u5F00\u59CB\u8DF3\u8F6C"),this.state.showLoading()}),t("canplay",()=>{ce("\u539F\u751F\u4E8B\u4EF6","\u51C6\u5907\u597D\u5F00\u59CB\u64AD\u653E"),this.state.hideLoading()}),t("playing",()=>{this.state.hideLoading(),this.state.hideError()}),t("seeked",()=>{ce("\u539F\u751F\u4E8B\u4EF6","\u8DF3\u8F6C\u5B8C\u6210"),this.state.hideLoading()}),t("error",()=>{ce("\u539F\u751F\u4E8B\u4EF6",`\u64AD\u653E\u9519\u8BEF: ${e.error?.message??"\u672A\u77E5\u9519\u8BEF"}`),this.showErrorState({type:"media",detail:e.error})}),this.disposers.push(this.emitter.on("error",n=>{n.type.startsWith("hls-")&&this.showErrorStateUi()})),t("enterpictureinpicture",()=>{ce("\u64AD\u653E\u5668","\u8FDB\u5165\u753B\u4E2D\u753B"),this.controls.updatePip(!0),this.emitter.emit("pipchange",!0)}),t("leavepictureinpicture",()=>{ce("\u64AD\u653E\u5668","\u9000\u51FA\u753B\u4E2D\u753B"),this.controls.updatePip(!1),this.emitter.emit("pipchange",!1)});let s=n=>{n.target!==this.video||n.pointerType==="touch"||this.clickTimer||(this.clickTimer=setTimeout(()=>{this.clickTimer=null,this.toggle()},zu))},i=n=>{n.target===this.video&&(this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null),this.toggleFullscreen())};this.container.addEventListener("click",s),this.container.addEventListener("dblclick",i),this.disposers.push(()=>{this.container.removeEventListener("click",s),this.container.removeEventListener("dblclick",i)})}showErrorState(e){this.emitter.emit("error",e),this.showErrorStateUi()}showErrorStateUi(){this.state.hideLoading(),this.state.showError(()=>{let e=this.video.currentTime;this.media.reload(),e>0&&(this.video.currentTime=e),this.play().catch(()=>{})})}showControls(){this.container.classList.remove("sp-controls-hidden"),this.hideTimer&&(clearTimeout(this.hideTimer),this.hideTimer=null)}hideControlsNow(){this.video.paused||this.container.classList.add("sp-controls-hidden")}scheduleHide(){this.showControls(),this.hideTimer=setTimeout(()=>this.hideControlsNow(),ju)}bindActivityTracking(){let e=t=>{t.pointerType!=="touch"&&(this.video.paused?this.showControls():this.scheduleHide())};this.container.addEventListener("pointermove",e),this.container.addEventListener("pointerdown",e),this.disposers.push(()=>{this.container.removeEventListener("pointermove",e),this.container.removeEventListener("pointerdown",e)})}};Zt.version=gr;var Zu=Zt;return kl(Ju);})();