@scalemule/gallop 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +201 -0
- package/dist/EventEmitter-CiUv3YL_.d.cts +12 -0
- package/dist/EventEmitter-CkfpgRij.d.ts +12 -0
- package/dist/chunk-2JQGJ7NX.cjs +40 -0
- package/dist/chunk-PKRNWEEX.cjs +265 -0
- package/dist/chunk-QTV4W7FA.js +2886 -0
- package/dist/chunk-SQPWH6EI.js +38 -0
- package/dist/chunk-UFFGSURS.js +263 -0
- package/dist/chunk-VCNMR5AB.cjs +2893 -0
- package/dist/element.cjs +342 -0
- package/dist/element.d.cts +38 -0
- package/dist/element.d.ts +38 -0
- package/dist/element.js +340 -0
- package/dist/gallop.embed.global.js +568 -0
- package/dist/gallop.umd.global.js +568 -0
- package/dist/iframe.cjs +11 -0
- package/dist/iframe.d.cts +50 -0
- package/dist/iframe.d.ts +50 -0
- package/dist/iframe.js +2 -0
- package/dist/index.cjs +11 -0
- package/dist/index.d.cts +74 -0
- package/dist/index.d.ts +74 -0
- package/dist/index.js +2 -0
- package/dist/react.cjs +77 -0
- package/dist/react.d.cts +34 -0
- package/dist/react.d.ts +34 -0
- package/dist/react.js +74 -0
- package/dist/types-D9Oqcpr1.d.cts +235 -0
- package/dist/types-D9Oqcpr1.d.ts +235 -0
- package/package.json +93 -0
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
"use strict";var GallopEmbed=(()=>{var bs=Object.defineProperty;var wl=Object.getOwnPropertyDescriptor;var Ml=Object.getOwnPropertyNames;var Ol=Object.prototype.hasOwnProperty;var Fl=(r,e)=>{for(var t in e)bs(r,t,{get:e[t],enumerable:!0})},Nl=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ml(e))!Ol.call(r,s)&&s!==t&&bs(r,s,{get:()=>e[s],enumerable:!(i=wl(e,s))||i.enumerable});return r};var Bl=r=>Nl(bs({},"__esModule",{value:!0}),r);var sf={};Fl(sf,{PostMessageBridge:()=>yt,bootstrapEmbed:()=>Jt});var mt="0.0.1";var Ul=65536,$l=new Set(["play","pause","seek","setQualityLevel","setAutoQuality","toggleFullscreen","setVolume","setMuted","setPlaybackRate","query","getQualityLevels","getCurrentQuality","getDiagnostics"]),Gl=new Set(["currentTime","duration","volume","muted","playbackRate","status","isFullscreen","currentQuality","qualityLevels","diagnostics"]),yt=class{constructor(e){this.player=e;this.targetOrigin=null;this.isConnected=!1;this.version=1;this.stateInterval=null;window.addEventListener("message",t=>this.handleMessage(t)),this.sendMessage({type:"gallop:hello",version:this.version},"*")}handleMessage(e){let t=e.data;if(!(!t||typeof t.type!="string")&&e.source===window.parent){if(t.type==="gallop:ping"){this.handlePing(e);return}!this.isConnected||e.origin!==this.targetOrigin||t.type==="gallop:method"&&this.handleMethod(t)}}handlePing(e){let t=e.data;this.isConnected||(this.targetOrigin=e.origin,this.isConnected=!0,this.sendMessage({type:"gallop:pong",version:this.version,playerVersion:mt,capabilities:["fullscreen","quality","pip","state-snapshot"],sessionId:t.sessionId||"anonymous",diagnostics:this.player.getDiagnostics()}),this.setupEvents(),this.setupStateReporting())}async handleMethod(e){let t=e.method,i=Array.isArray(e.args)?e.args:[],s=e.callId;if(!(typeof s!="string"||!s)){if(!this.isAllowedMethod(t)){this.sendMethodResponse(s,null,{code:"UNKNOWN_METHOD",message:`Method ${t} not allowed`});return}try{let n=await this.invokeMethod(t,i);this.sendMethodResponse(s,n??null,null)}catch(n){this.sendMethodResponse(s,null,{code:"METHOD_ERROR",message:n instanceof Error?n.message:"Internal error"})}}}isAllowedMethod(e){return $l.has(e)}toFiniteNumber(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Error(`Invalid ${t}`);return e}async invokeMethod(e,t){switch(e){case"play":return this.player.play();case"pause":return this.player.pause();case"seek":return this.player.seek(this.toFiniteNumber(t[0],"seek time"));case"setQualityLevel":return this.player.setQualityLevel(Math.trunc(this.toFiniteNumber(t[0],"quality level")));case"setAutoQuality":return this.player.setAutoQuality();case"toggleFullscreen":return this.player.toggleFullscreen();case"setVolume":return this.player.volume=this.toFiniteNumber(t[0],"volume"),null;case"setMuted":{if(typeof t[0]!="boolean")throw new Error("Invalid muted value");return this.player.muted=t[0],null}case"setPlaybackRate":return this.player.playbackRate=this.toFiniteNumber(t[0],"playback rate"),null;case"query":{let i=t[0];if(typeof i!="string"||!Gl.has(i))throw new Error("Invalid query key");return this.player.query(i)}case"getQualityLevels":return this.player.getQualityLevels();case"getCurrentQuality":return this.player.getCurrentQuality();case"getDiagnostics":return this.player.getDiagnostics()}}sendMethodResponse(e,t,i){this.sendMessage({type:"gallop:response",callId:e,result:t,error:i,version:this.version})}setupEvents(){["ready","play","pause","ended","timeupdate","volumechange","qualitychange","qualitylevels","buffering","seeked","ratechange","fullscreenchange","statuschange","error","destroy"].forEach(t=>{this.player.on(t,i=>{this.sendMessage({type:"gallop:event",event:t,data:i??null,version:this.version})})})}setupStateReporting(){this.stateInterval=setInterval(()=>{this.isConnected&&this.sendMessage({type:"gallop:state",state:{currentTime:this.player.currentTime,duration:this.player.duration,paused:this.player.paused,volume:this.player.volume,muted:this.player.muted,playbackRate:this.player.playbackRate,status:this.player.status,isFullscreen:this.player.isFullscreen},version:this.version})},250)}sendMessage(e,t){let i=t||this.targetOrigin;if(i){try{if(JSON.stringify(e).length>Ul)return}catch{return}window.parent.postMessage(e,i)}}};var $r={colorPrimary:"#635bff",colorSecondary:"#8b5cf6",colorText:"#ffffff",colorBackground:"rgba(24, 24, 32, 0.92)",colorBuffered:"rgba(255, 255, 255, 0.22)",colorProgress:"#635bff",controlBarBackground:"rgba(0, 0, 0, 0.65)",controlBarHeight:"44px",borderRadius:"8px",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"13px",iconSize:"22px"},Xe={controls:!0,autoplay:!1,loop:!1,muted:!1,keyboard:!0,touch:!0,aspectRatio:"16:9",apiBaseUrl:"https://api.scalemule.com"},ti=[.25,.5,.75,1,1.25,1.5,1.75,2],As=5,vt=10,Ls=.05,Gr=3e3,Is=300,Kr={maxBufferLength:30,maxMaxBufferLength:60,startLevel:-1,capLevelToPlayerSize:!0,progressive:!0};var ii=class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}once(e,t){let i=((...s)=>{this.off(e,i),t(...s)});this.on(e,i)}emit(e,...t){let i=this.listeners.get(e);if(i)for(let s of i)try{s(...t)}catch(n){console.error(`[Gallop] Error in ${e} listener:`,n)}}removeAllListeners(){this.listeners.clear()}};var Kl={idle:["loading"],loading:["ready","error"],ready:["playing","paused","error"],playing:["paused","buffering","ended","error","loading"],paused:["playing","buffering","ended","error","loading"],buffering:["playing","paused","error","ended"],ended:["playing","loading","idle"],error:["loading","idle"]},si=class{constructor(e){this._status="idle";this.onChange=e}get status(){return this._status}transition(e){if(e===this._status||!Kl[this._status].includes(e))return!1;let i=this._status;return this._status=e,this.onChange?.(e,i),!0}reset(){let e=this._status;this._status="idle",e!=="idle"&&this.onChange?.("idle",e)}get isPlaying(){return this._status==="playing"}get isPaused(){return this._status==="paused"}get isBuffering(){return this._status==="buffering"}get isEnded(){return this._status==="ended"}};var O=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Vl=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=Hl},Hl=Number.MAX_SAFE_INTEGER||9007199254740991,K=(function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r})({}),L=(function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.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})({}),p=(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})({}),z={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},N={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},et=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},Qs=class{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new et(e),this.fast_=new et(t),this.defaultTTFB_=s,this.ttfb_=new et(e)}update(e,t){let{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new et(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new et(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new et(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let i=8*t,s=e/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(e){let t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function Yl(r,e,t){return(e=Wl(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 i in t)({}).hasOwnProperty.call(t,i)&&(r[i]=t[i])}return r},ie.apply(null,arguments)}function Vr(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(r);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,i)}return t}function ee(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Vr(Object(t),!0).forEach(function(i){Yl(r,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Vr(Object(t)).forEach(function(i){Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(t,i))})}return r}function ql(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var i=t.call(r,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Wl(r){var e=ql(r,"string");return typeof e=="symbol"?e:e+""}var Le=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=tt,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}},tt=function(){},jl={trace:tt,debug:tt,log:tt,warn:tt,info:tt,error:tt};function zs(){return ie({},jl)}function Ql(r,e){let t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):tt}function Hr(r,e,t){return e[r]?e[r].bind(e):Ql(r,t)}var Xs=zs();function zl(r,e,t){let i=zs();if(typeof console=="object"&&r===!0||typeof r=="object"){let s=["debug","log","info","warn","error"];s.forEach(n=>{i[n]=Hr(n,r,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return zs()}s.forEach(n=>{Xs[n]=Hr(n,r)})}else ie(Xs,i);return i}var te=Xs;function it(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Xl(r){return typeof self<"u"&&r===self.ManagedMediaSource}function to(r,e){let t=Object.keys(r),i=Object.keys(e),s=t.length,n=i.length;return!s||!n||s===n&&!t.some(a=>i.indexOf(a)===-1)}function Pe(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,i,s,n,a="",o=0;for(;o<t;){if(i=r[o++],i===0&&e)return a;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:s=r[o++],a+=String.fromCharCode((i&31)<<6|s&63);break;case 14:s=r[o++],n=r[o++],a+=String.fromCharCode((i&15)<<12|(s&63)<<6|(n&63)<<0);break}}return a}function pe(r){let e="";for(let t=0;t<r.length;t++){let i=r[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function io(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Zl(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Rs={exports:{}},Yr;function Jl(){return Yr||(Yr=1,(function(r,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\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 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=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var y={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(y.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)y.path=f.path,u.params||(y.params=f.params,u.query||(y.query=f.query));else{var m=f.path,v=m.substring(0,m.lastIndexOf("/")+1)+u.path;y.path=o.normalizePath(v)}return y.path===null&&(y.path=d.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(y)},parseURL:function(c){var l=i.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})()})(Rs)),Rs.exports}var pr=Jl(),Gt=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}}},se={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Li=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,ec(this,"stats")}setByteRange(e,t){let i=e.split("@",2),s;i.length===1?s=t?.byteRangeEndOffset||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[se.AUDIO]:null,[se.VIDEO]:null,[se.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 Gt),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=pr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[se.AUDIO]=null,e[se.VIDEO]=null,e[se.AUDIOVIDEO]=null}};function le(r){return r.sn!=="initSegment"}var Nt=class extends Li{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 i=Object.keys(t);if(i.length===1){let s=this._decryptdata=t[i[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=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 i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!O(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return le(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let s=t[e];s&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,n,a=!1){let{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:n,partial:a};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,i),c.startDTS=Math.min(c.startDTS,s),c.endDTS=Math.max(c.endDTS,n)}},Zs=class extends Li{constructor(e,t,i,s,n){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function so(r,e){let t=Object.getPrototypeOf(r);if(t){let i=Object.getOwnPropertyDescriptor(t,e);return i||so(t,e)}}function ec(r,e){let t=so(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}var qr=Math.pow(2,32)-1,tc=[].push,no={video:1,audio:2,id3:3,text:4};function ce(r){return String.fromCharCode.apply(null,r)}function ro(r,e){let t=r[e]<<8|r[e+1];return t<0?65536+t:t}function Y(r,e){let t=ao(r,e);return t<0?4294967296+t:t}function Wr(r,e){let t=Y(r,e);return t*=Math.pow(2,32),t+=Y(r,e+4),t}function ao(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function ic(r){let e=r.byteLength;for(let t=0;t<e;){let i=Y(r,t);if(i>8&&r[t+4]===109&&r[t+5]===111&&r[t+6]===111&&r[t+7]===102)return!0;t=i>1?t+i:e}return!1}function Q(r,e){let t=[];if(!e.length)return t;let i=r.byteLength;for(let s=0;s<i;){let n=Y(r,s),a=ce(r.subarray(s+4,s+8)),o=n>1?s+n:i;if(a===e[0])if(e.length===1)t.push(r.subarray(s+8,o));else{let c=Q(r.subarray(s+8,o),e.slice(1));c.length&&tc.apply(t,c)}s=o}return t}function sc(r){let e=[],t=r[0],i=8,s=Y(r,i);i+=4;let n=0,a=0;t===0?(n=Y(r,i),a=Y(r,i+4),i+=8):(n=Wr(r,i),a=Wr(r,i+8),i+=16),i+=2;let o=r.length+a,c=ro(r,i);i+=2;for(let l=0;l<c;l++){let d=i,h=Y(r,d);d+=4;let u=h&2147483647;if((h&2147483648)>>>31===1)return te.warn("SIDX has hierarchical references (not supported)"),null;let g=Y(r,d);d+=4,e.push({referenceSize:u,subsegmentDuration:g,info:{duration:g/s,start:o,end:o+u-1}}),o+=u,d+=4,i=d}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:c,references:e}}function oo(r){let e=[],t=Q(r,["moov","trak"]);for(let s=0;s<t.length;s++){let n=t[s],a=Q(n,["tkhd"])[0];if(a){let o=a[0],c=Y(a,o===0?12:20),l=Q(n,["mdia","mdhd"])[0];if(l){o=l[0];let d=Y(l,o===0?12:20),h=Q(n,["mdia","hdlr"])[0];if(h){let u=ce(h.subarray(8,12)),f={soun:se.AUDIO,vide:se.VIDEO}[u],g=Q(n,["mdia","minf","stbl","stsd"])[0],y=nc(g);f?(e[c]={timescale:d,type:f,stsd:y},e[f]=ee({timescale:d,id:c},y)):e[c]={timescale:d,type:u,stsd:y}}}}}return Q(r,["moov","mvex","trex"]).forEach(s=>{let n=Y(s,4),a=e[n];a&&(a.default={duration:Y(s,12),flags:Y(s,20)})}),e}function nc(r){let e=r.subarray(8),t=e.subarray(86),i=ce(e.subarray(4,8)),s=i,n,a=i==="enca"||i==="encv";if(a){let l=Q(e,[i])[0].subarray(i==="enca"?28:78);Q(l,["sinf"]).forEach(h=>{let u=Q(h,["schm"])[0];if(u){let f=ce(u.subarray(4,8));if(f==="cbcs"||f==="cenc"){let g=Q(h,["frma"])[0];g&&(s=ce(g))}}})}let o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{let c=Q(t,["avcC"])[0];c&&c.length>3&&(s+="."+ri(c[1])+ri(c[2])+ri(c[3]),n=ni(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let c=Q(e,[i])[0],l=Q(c.subarray(28),["esds"])[0];if(l&&l.length>7){let d=4;if(l[d++]!==3)break;d=_s(l,d),d+=2;let h=l[d++];if(h&128&&(d+=2),h&64&&(d+=l[d++]),l[d++]!==4)break;d=_s(l,d);let u=l[d++];if(u===64)s+="."+ri(u);else break;if(d+=12,l[d++]!==5)break;d=_s(l,d);let f=l[d++],g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[d]&224)>>5)),s+="."+g}break}case"hvc1":case"hev1":{let c=Q(t,["hvcC"])[0];if(c&&c.length>12){let l=c[1],d=["","A","B","C"][l>>6],h=l&31,u=Y(c,2),f=(l&32)>>5?"H":"L",g=c[12],y=c.subarray(6,12);s+="."+d+h,s+="."+rc(u).toString(16).toUpperCase(),s+="."+f+g;let m="";for(let v=y.length;v--;){let E=y[v];(E||m)&&(m="."+E.toString(16).toUpperCase()+m)}s+=m}n=ni(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=ni(s,t)||s;break}case"vp09":{let c=Q(t,["vpcC"])[0];if(c&&c.length>6){let l=c[4],d=c[5],h=c[6]>>4&15;s+="."+Ge(l)+"."+Ge(d)+"."+Ge(h)}break}case"av01":{let c=Q(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,f=(c[2]&32)>>5,g=l===2&&u?f?12:10:u?10:8,y=(c[2]&16)>>4,m=(c[2]&8)>>3,v=(c[2]&4)>>2,E=c[2]&3;s+="."+l+"."+Ge(d)+h+"."+Ge(g)+"."+y+"."+m+v+E+"."+Ge(1)+"."+Ge(1)+"."+Ge(1)+"."+0,n=ni("dav1",t)}break}}return{codec:s,encrypted:a,supplemental:n}}function ni(r,e){let t=Q(e,["dvvC"]),i=t.length?t[0]:Q(e,["dvcC"])[0];if(i){let s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return r+"."+Ge(s)+"."+Ge(n)}}function rc(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function _s(r,e){let t=e+5;for(;r[e++]&128&&e<t;);return e}function ri(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function Ge(r){return(r<10?"0":"")+r}function ac(r,e){if(!r||!e)return;let t=e.keyId;t&&e.isCommonEncryption&&lo(r,(i,s)=>{let n=i.subarray(8,24);n.some(a=>a!==0)||(te.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${pe(n)} -> ${pe(t)}`),i.set(t,8))})}function oc(r){let e=[];return lo(r,t=>e.push(t.subarray(8,24))),e}function lo(r,e){Q(r,["moov","trak"]).forEach(i=>{let s=Q(i,["mdia","minf","stbl","stsd"])[0];if(!s)return;let n=s.subarray(8),a=Q(n,["enca"]),o=a.length>0;o||(a=Q(n,["encv"])),a.forEach(c=>{let l=o?c.subarray(28):c.subarray(78);Q(l,["sinf"]).forEach(h=>{let u=co(h);u&&e(u,o)})})})}function co(r){let e=Q(r,["schm"])[0];if(e){let t=ce(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let i=Q(r,["schi","tenc"])[0];if(i)return i}}}function lc(r,e,t){let i={},s=Q(r,["moof","traf"]);for(let n=0;n<s.length;n++){let a=s[n],o=Q(a,["tfhd"])[0],c=Y(o,4),l=e[c];if(!l)continue;i[c]||(i[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});let d=i[c],h=Q(a,["tfdt"])[0];if(h){let T=h[0],S=Y(h,4);T===1&&(S===qr?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=qr+1,S+=Y(h,8))),O(S)&&(!O(d.start)||S<d.start)&&(d.start=S)}let u=l.default,f=Y(o,0)|u?.flags,g=u?.duration||0;f&8&&(f&2?g=Y(o,12):g=Y(o,8));let y=Q(a,["trun"]),m=d.start||0,v=0,E=g;for(let T=0;T<y.length;T++){let S=y[T],x=Y(S,4),_=d.sampleCount;d.sampleCount+=x;let b=S[3]&1,R=S[3]&4,I=S[2]&1,A=S[2]&2,P=S[2]&4,M=S[2]&8,B=8,V=x;for(b&&(B+=4),R&&x&&(!(S[B+1]&1)&&d.keyFrameIndex===void 0&&(d.keyFrameIndex=_),B+=4,I?(E=Y(S,B),B+=4):E=g,A&&(B+=4),M&&(B+=4),m+=E,v+=E,V--);V--;)I?(E=Y(S,B),B+=4):E=g,A&&(B+=4),P&&(S[B+1]&1||d.keyFrameIndex===void 0&&(d.keyFrameIndex=d.sampleCount-(V+1),d.keyFrameStart=m),B+=4),M&&(B+=4),m+=E,v+=E;!v&&g&&(v+=g*x)}d.duration+=v}if(!Object.keys(i).some(n=>i[n].duration)){let n=1/0,a=0,o=Q(r,["sidx"]);for(let c=0;c<o.length;c++){let l=sc(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&&O(a)&&Object.keys(i).forEach(c=>{i[c].duration||(i[c].duration=a*i[c].timescale-i[c].start)})}return i}function cc(r){let e={valid:null,remainder:null},t=Q(r,["moof"]);if(t.length<2)return e.remainder=r,e;let i=t[t.length-1];return e.valid=r.slice(0,i.byteOffset-8),e.remainder=r.slice(i.byteOffset-8),e}function we(r,e){let t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function jr(r,e){let t=[],i=e.samples,s=e.timescale,n=e.id,a=!1;return Q(i,["moof"]).map(c=>{let l=c.byteOffset-8;Q(c,["traf"]).map(h=>{let u=Q(h,["tfdt"]).map(f=>{let g=f[0],y=Y(f,4);return g===1&&(y*=Math.pow(2,32),y+=Y(f,8)),y/s})[0];return u!==void 0&&(r=u),Q(h,["tfhd"]).map(f=>{let g=Y(f,4),y=Y(f,0)&16777215,m=(y&1)!==0,v=(y&2)!==0,E=(y&8)!==0,T=0,S=(y&16)!==0,x=0,_=(y&32)!==0,b=8;g===n&&(m&&(b+=8),v&&(b+=4),E&&(T=Y(f,b),b+=4),S&&(x=Y(f,b),b+=4),_&&(b+=4),e.type==="video"&&(a=Xi(e.codec)),Q(h,["trun"]).map(R=>{let I=R[0],A=Y(R,0)&16777215,P=(A&1)!==0,M=0,B=(A&4)!==0,V=(A&256)!==0,U=0,C=(A&512)!==0,$=0,F=(A&1024)!==0,G=(A&2048)!==0,H=0,k=Y(R,4),w=8;P&&(M=Y(R,w),w+=4),B&&(w+=4);let W=M+l;for(let J=0;J<k;J++){if(V?(U=Y(R,w),w+=4):U=T,C?($=Y(R,w),w+=4):$=x,F&&(w+=4),G&&(I===0?H=Y(R,w):H=ao(R,w),w+=4),e.type===se.VIDEO){let j=0;for(;j<$;){let X=Y(i,W);if(W+=4,dc(a,i[W])){let ye=i.subarray(W,W+X);mr(ye,a?2:1,r+H/s,t)}W+=X,j+=X+4}}r+=U/s}}))})})}),t}function Xi(r){if(!r)return!1;let e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function dc(r,e){if(r){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function mr(r,e,t,i){let s=ho(r),n=0;n+=e;let a=0,o=0,c=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;c=s[n++],a+=c}while(c===255);o=0;do{if(n>=s.length)break;c=s[n++],o+=c}while(c===255);let l=s.length-n,d=n;if(o<l)n+=o;else if(o>l){te.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(s[d++]===181){let u=ro(s,d);if(d+=2,u===49){let f=Y(s,d);if(d+=4,f===1195456820){let g=s[d++];if(g===3){let y=s[d++],m=31&y,v=64&y,E=v?2+m*3:0,T=new Uint8Array(E);if(v){T[0]=y;for(let S=1;S<E;S++)T[S]=s[d++]}i.push({type:g,payloadType:a,pts:t,bytes:T})}}}}}else if(a===5&&o>16){let h=[];for(let g=0;g<16;g++){let y=s[d++].toString(16);h.push(y.length==1?"0"+y:y),(g===3||g===5||g===7||g===9)&&h.push("-")}let u=o-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=s[d++];i.push({payloadType:a,pts:t,uuid:h.join(""),userData:Pe(f),userDataBytes:f})}}}function ho(r){let e=r.byteLength,t=[],i=1;for(;i<e-2;)r[i]===0&&r[i+1]===0&&r[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return r;let s=e-t.length,n=new Uint8Array(s),a=0;for(i=0;i<s;a++,i++)a===t[0]&&(a++,t.shift()),n[i]=r[a];return n}function hc(r){let e=r[0],t="",i="",s=0,n=0,a=0,o=0,c=0,l=0;if(e===0){for(;ce(r.subarray(l,l+1))!=="\0";)t+=ce(r.subarray(l,l+1)),l+=1;for(t+=ce(r.subarray(l,l+1)),l+=1;ce(r.subarray(l,l+1))!=="\0";)i+=ce(r.subarray(l,l+1)),l+=1;i+=ce(r.subarray(l,l+1)),l+=1,s=Y(r,12),n=Y(r,16),o=Y(r,20),c=Y(r,24),l=28}else if(e===1){l+=4,s=Y(r,l),l+=4;let h=Y(r,l);l+=4;let u=Y(r,l);for(l+=4,a=2**32*h+u,Vl(a)||(a=Number.MAX_SAFE_INTEGER,te.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Y(r,l),l+=4,c=Y(r,l),l+=4;ce(r.subarray(l,l+1))!=="\0";)t+=ce(r.subarray(l,l+1)),l+=1;for(t+=ce(r.subarray(l,l+1)),l+=1;ce(r.subarray(l,l+1))!=="\0";)i+=ce(r.subarray(l,l+1)),l+=1;i+=ce(r.subarray(l,l+1)),l+=1}let d=r.subarray(l,r.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:c,payload:d}}function uc(r,...e){let t=e.length,i=8,s=t;for(;s--;)i+=e[s].byteLength;let n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(r,4),s=0,i=8;s<t;s++)n.set(e[s],i),i+=e[s].byteLength;return n}function fc(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let i,s;i=0,s=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),uc([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,a,t)}function gc(r){let e=[];if(r instanceof ArrayBuffer){let t=r.byteLength,i=0;for(;i+32<t;){let s=new DataView(r,i),n=pc(s);e.push(n),i+=n.size}}return e}function pc(r){let e=r.getUint32(0),t=r.byteOffset,i=r.byteLength;if(i<e)return{offset:t,size:i};if(r.getUint32(4)!==1886614376)return{offset:t,size:e};let n=r.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=r.buffer,o=pe(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||i<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));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 uo=()=>/\(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 yr(r,e){let t=Pt[e];return!!t&&!!t[r.slice(0,4)]}function Kt(r,e,t=!0){return!r.split(",").some(i=>!vr(i,e,t))}function vr(r,e,t=!0){var i;let s=it(t);return(i=s?.isTypeSupported(Vt(r,e)))!=null?i:!1}function Vt(r,e){return`${e}/mp4;codecs=${r}`}function Qr(r){if(r){let e=r.substring(0,4);return Pt.video[e]}return 2}function Ii(r){let e=uo();return r.split(",").reduce((t,i)=>{let n=e&&Xi(i)?9:Pt.video[i];return n?(n*2+t)/(t?3:2):(Pt.audio[i]+t)/(t?2:1)},0)}var Ds={};function mc(r,e=!0){if(Ds[r])return Ds[r];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let s=0;s<t.length;s++){var i;if(vr(t[s],"audio",e))return Ds[r]=t[s],t[s];if(t[s]==="mp3"&&(i=it(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return r}var yc=/flac|opus|mp4a\.40\.34/i;function Ri(r,e=!0){return r.replace(yc,t=>mc(t.toLowerCase(),e))}function vc(r,e){let t=[];if(r){let i=r.split(",");for(let s=0;s<i.length;s++)yr(i[s],"video")||t.push(i[s])}return e&&t.push(e),t.join(",")}function vi(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(zr(r,"audio")||zr(r,"video")))return r;if(e){let t=e.split(",");if(t.length>1){if(r){for(let i=t.length;i--;)if(t[i].substring(0,4)===r.substring(0,4))return t[i]}return t[0]}}return e||r}function zr(r,e){return yr(r,e)&&vr(r,e)}function Ec(r){let e=r.split(",");for(let t=0;t<e.length;t++){let i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Tc(r){if(r.startsWith("av01.")){let e=r.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return r}function Xr(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 Js(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Sc={supported:!0,powerEfficient:!0,smooth:!0},xc={supported:!1,smooth:!1,powerEfficient:!1},fo={supported:!0,configurations:[],decodingInfoResults:[Sc]};function go(r,e){return{supported:!1,configurations:e,decodingInfoResults:[xc],error:r}}function bc(r,e,t,i,s,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,f)=>{if(f){let g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(y=>{u[y]=(u[y]||0)+g.channels[y]})}return u},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(u=>Xi(u))||r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(i,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(s,8e6))||!!h&&O(d)&&Object.keys(h).some(u=>parseInt(u)>d)}function po(r,e,t,i={}){let s=r.videoCodec;if(!s&&!r.audioCodec||!t)return Promise.resolve(fo);let n=[],a=Ac(r),o=a.length,c=Lc(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(s){let d=navigator.userAgent;if(s.split(",").some(h=>Xi(h))&&uo())return Promise.resolve(go(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),n))}return Promise.all(n.map(d=>{let h=Rc(d);return i[h]||(i[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 Ac(r){var e;let t=(e=r.videoCodec)==null?void 0:e.split(","),i=mo(r),s=r.width||640,n=r.height||480,a=r.frameRate||30,o=r.videoRange.toLowerCase();return t?t.map(c=>{let l={contentType:Vt(Tc(c),"video"),width:s,height:n,bitrate:i,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function Lc(r,e,t){var i;let s=(i=r.audioCodec)==null?void 0:i.split(","),n=mo(r);return s&&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||"");s.forEach(f=>{let g={contentType:Vt(f,"audio"),bitrate:t?Ic(f,n):n};u&&(g.channels=""+u),d.push(g)})}return d},a):a},[]):[]}function Ic(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 mo(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function Rc(r){let e="",{audio:t,video:i}=r;if(i){let s=Js(i.contentType);e+=`${s}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){let s=Js(t.contentType);e+=`${i?"_":""}${s}_c${t.channels}`}return e}var en=["NONE","TYPE-0","TYPE-1",null];function _c(r){return en.indexOf(r)>-1}var _i=["SDR","PQ","HLG"];function Dc(r){return!!r&&_i.indexOf(r)>-1}var Ei={No:"",Yes:"YES",v2:"v2"};function Zr(r){let{canSkipUntil:e,canSkipDateRanges:t,age:i}=r,s=i<e/2;return e&&s?t?Ei.v2:Ei.Yes:Ei.No}var Di=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&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(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}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 Jr(this._audioGroups,e)}hasSubtitleGroup(e){return Jr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Jr(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function Pc(){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 Cc(r,e){let t=!1,i=[];if(r&&(t=r!=="SDR",i=[r]),e){i=e.allowedVideoRanges||_i.slice(0);let s=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:s&&Pc(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}var kc=r=>{let e=new WeakSet;return(t,i)=>{if(r&&(i=r(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},ne=(r,e)=>JSON.stringify(r,kc(e));function wc(r,e,t,i,s){let n=Object.keys(r),a=i?.channels,o=i?.audioCodec,c=s?.videoCodec,l=a&&parseInt(a)===2,d=!1,h=!1,u=1/0,f=1/0,g=1/0,y=1/0,m=0,v=[],{preferHDR:E,allowedVideoRanges:T}=Cc(e,s);for(let R=n.length;R--;){let I=r[n[R]];d||(d=I.channels[2]>0),u=Math.min(u,I.minHeight),f=Math.min(f,I.minFramerate),g=Math.min(g,I.minBitrate),T.filter(P=>I.videoRanges[P]>0).length>0&&(h=!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),h||(e=void 0);let _=n.length>1;return{codecSet:n.reduce((R,I)=>{let A=r[I];if(I===R)return R;if(v=h?T.filter(P=>A.videoRanges[P]>0):[],_){if(A.minBitrate>t)return Ue(I,`min bitrate of ${A.minBitrate} > current estimate of ${t}`),R;if(!A.hasDefaultAudio)return Ue(I,"no renditions with default or auto-select sound found"),R;if(o&&I.indexOf(o.substring(0,4))%5!==0)return Ue(I,`audio codec preference "${o}" not found`),R;if(a&&!l){if(!A.channels[a])return Ue(I,`no renditions with ${a} channel sound found (channels options: ${Object.keys(A.channels)})`),R}else if((!o||l)&&d&&A.channels[2]===0)return Ue(I,"no renditions with stereo sound found"),R;if(A.minHeight>S)return Ue(I,`min resolution of ${A.minHeight} > maximum of ${S}`),R;if(A.minFramerate>x)return Ue(I,`min framerate of ${A.minFramerate} > maximum of ${x}`),R;if(!v.some(P=>A.videoRanges[P]>0))return Ue(I,`no variants with VIDEO-RANGE of ${ne(v)} found`),R;if(c&&I.indexOf(c.substring(0,4))%5!==0)return Ue(I,`video codec preference "${c}" not found`),R;if(A.maxScore<m)return Ue(I,`max score of ${A.maxScore} < selected max of ${m}`),R}return R&&(Ii(I)>=Ii(R)||A.fragmentError>r[R].fragmentError)?R:(y=A.minIndex,m=A.maxScore,I)},void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:y}}function Ue(r,e){te.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function yo(r){return r.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Mc(r,e,t,i){return r.slice(t,i+1).reduce((s,n,a)=>{if(!n.codecSet)return s;let o=n.audioGroups,c=s[n.codecSet];c||(s[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]}))}),s},{})}function ea(r){if(!r)return r;let{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}=r;return{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}}function Ve(r,e,t){if("attrs"in r){let i=e.indexOf(r);if(i!==-1)return i}for(let i=0;i<e.length;i++){let s=e[i];if(ht(r,s,t))return i}return-1}function ht(r,e,t){let{groupId:i,name:s,lang:n,assocLang:a,default:o}=r,c=r.forced;return(i===void 0||e.groupId===i)&&(s===void 0||e.name===s)&&(n===void 0||Oc(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in r)||Fc(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function Oc(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function Fc(r,e=""){let t=r.split(","),i=e.split(",");return t.length===i.length&&!t.some(s=>i.indexOf(s)===-1)}function ct(r,e){let{audioCodec:t,channels:i}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function Nc(r,e,t,i,s){let n=e[i],o=e.reduce((u,f,g)=>{let y=f.uri;return(u[y]||(u[y]=[])).push(g),u},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));let c=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),h=ta(e,i,u=>{if(u.videoRange!==c||u.frameRate!==l||u.codecSet.substring(0,4)!==d)return!1;let f=u.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return Ve(r,g,s)>-1});return h>-1?h:ta(e,i,u=>{let f=u.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return Ve(r,g,s)>-1})}function ta(r,e,t){for(let i=e;i>-1;i--)if(t(r[i]))return i;for(let i=e+1;i<r.length;i++)if(t(r[i]))return i;return-1}function Pi(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}var tn=class extends Le{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 i;let{fragCurrent:s,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:c}=a;if(!s||!c)return;let l=performance.now(),d=n?n.stats:s.stats,h=n?n.duration:s.duration,u=l-d.loading.start,f=a.minAutoLevel,g=s.level,y=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let m=y>-1&&y!==g,v=!!t||m;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*(h/(S*2))))return;let x=E?E.len/S:0,_=d.loading.first?d.loading.first-d.loading.start:-1,b=d.loaded&&_>-1,R=this.getBwEstimate(),I=a.levels,A=I[g],P=Math.max(d.loaded,Math.round(h*(s.bitrate||A.averageBitrate)/8)),M=b?u-_:u;M<1&&b&&(M=Math.min(u,d.loaded*8/R));let B=b?d.loaded*1e3/M:0,V=T/1e3,U=B?(P-d.loaded)/B:P*8/R+V;if(U<=x)return;let C=B?B*8:R,$=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,F=this.hls.config.abrBandWidthUpFactor,G=Number.POSITIVE_INFINITY,H;for(H=g-1;H>f;H--){let J=I[H].maxBitrate,j=!I[H].details||$;if(G=this.getTimeToLoadFrag(V,C,h*J,j),G<Math.min(x,h+V))break}if(G>=U||G>h*10)return;b?this.bwEstimator.sample(u-Math.min(T,_),d.loaded):this.bwEstimator.sampleTTFB(u);let k=I[H].maxBitrate;this.getBwEstimate()*F>k&&this.resetEstimator(k);let w=this.findBestLevel(k,f,H,0,x,1,1);w>-1&&(H=w),this.warn(`Fragment ${s.sn}${n?" part "+n.index:""} of level ${g} is loading too slowly;
|
|
2
|
+
Fragment duration: ${s.duration.toFixed(3)}
|
|
3
|
+
Time to underbuffer: ${x.toFixed(3)} s
|
|
4
|
+
Estimated load time for current fragment: ${U.toFixed(3)} s
|
|
5
|
+
Estimated load time for down switch fragment: ${G.toFixed(3)} s
|
|
6
|
+
TTFB estimate: ${_|0} ms
|
|
7
|
+
Current BW estimate: ${O(R)?R|0:"Unknown"} bps
|
|
8
|
+
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
9
|
+
Switching to level ${H} @ ${k|0} bps`),a.nextLoadLevel=a.nextAutoLevel=H,this.clearTimer();let W=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===H&&H>0){let J=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${H>0?"and switching down":""}
|
|
10
|
+
Fragment duration: ${s.duration.toFixed(3)} s
|
|
11
|
+
Time to underbuffer: ${J.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,H>f){let j=this.findBestLevel(this.hls.levels[f].bitrate,f,H,0,J,1,1);j===-1&&(j=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=j,this.resetEstimator(this.hls.levels[j].bitrate)}}};m||U>G*2?W():this.timer=self.setInterval(W,G*1e3),a.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,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 Qs(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case L.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:s,partCurrent:n}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){let a=performance.now(),o=n?n.stats:i.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,i,s){let n=e+i/t,a=s?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let i=this.hls.config,{loading:s}=t.stats,n=s.end-s.first;O(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){let s=i?i.stats:t.stats;if(t.type===N.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let n=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+s.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:s,frag:t,part:i,id:t.type};this.onFragBuffered(p.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:i,part:s}=t,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;let 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(),i.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,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,s,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,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:s,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay(),d=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(l){let m=this.findBestLevel(c,a,s,l,0,d,h);if(m>=0)return this.rebufferNotice=-1,m}let u=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){let m=this.bitrateTestDelay;m&&(u=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-m,this.info(`bitrate test took ${Math.round(1e3*m)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=h=1)}let f=this.findBestLevel(c,a,s,l,u,d,h);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=i.levels[a],y=i.loadLevelObj;return y&&g?.bitrate<y.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,n,a,o){var c;let l=s+n,d=this.lastLoadedFragLevel,h=d===-1?this.hls.firstLevel:d,{fragCurrent:u,partCurrent:f}=this,{levels:g,allAudioTracks:y,loadLevel:m,config:v}=this.hls;if(g.length===1)return 0;let E=g[h],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),S=m===-1||d===-1,x,_="SDR",b=E?.frameRate||0,{audioPreference:R,videoPreference:I}=v,A=this.audioTracksByGroup||(this.audioTracksByGroup=yo(y)),P=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;let C=this.codecTiers||(this.codecTiers=Mc(g,A,t,i)),$=wc(C,_,e,R,I),{codecSet:F,videoRanges:G,minFramerate:H,minBitrate:k,minIndex:w,preferHDR:W}=$;P=w,x=F,_=W?G[G.length-1]:G[0],b=H,e=Math.max(e,k),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 C=i;C>=t;C--){var U;let $=g[C],F=C>h;if(!$)continue;if(v.useMediaCapabilities&&!$.supportedResult&&!$.supportedPromise){let j=navigator.mediaCapabilities;typeof j?.decodingInfo=="function"&&bc($,A,_,b,e,R)?($.supportedPromise=po($,A,j,this.supportedCache),$.supportedPromise.then(X=>{if(!this.hls)return;$.supportedResult=X;let ye=this.hls.levels,ge=ye.indexOf($);X.error?this.warn(`MediaCapabilities decodingInfo error: "${X.error}" for level ${ge} ${ne(X)}`):X.supported?X.decodingInfoResults.some(Ce=>Ce.smooth===!1||Ce.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ge} not smooth or powerEfficient: ${ne(X)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ge} ${ne(X)}`),ge>-1&&ye.length>1&&(this.log(`Removing unsupported level ${ge}`),this.hls.removeLevel(ge),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(X=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${X}`)})):$.supportedResult=fo}if((x&&$.codecSet!==x||_&&$.videoRange!==_||F&&b>$.frameRate||!F&&b>0&&b<$.frameRate||(U=$.supportedResult)!=null&&(U=U.decodingInfoResults)!=null&&U.some(j=>j.smooth===!1))&&(!S||C!==P)){V.push(C);continue}let G=$.details,H=(f?G?.partTarget:G?.averagetargetduration)||M,k;F?k=o*e:k=a*e;let w=M&&s>=M*2&&n===0?$.averageBitrate:$.maxBitrate,W=this.getTimeToLoadFrag(B,k,w*H,G===void 0);if(k>=w&&(C===d||$.loadError===0&&$.fragmentError===0)&&(W<=B||!O(W)||T&&!this.bitrateTestDelay||W<l)){let j=this.forcedAutoLevel;return C!==m&&(j===-1||j!==m)&&(V.length&&this.trace(`Skipped level(s) ${V.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[V[0]].codecs}" ${g[V[0]].videoRange}; not compatible with "${x}" ${_}`),this.info(`switch candidate:${h}->${C} adjustedbw(${Math.round(k)})-bitrate=${Math.round(k-w)} ttfb:${B.toFixed(1)} avgDuration:${H.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${W.toFixed(1)} firstSelection:${S} codecSet:${$.codecSet} videoRange:${$.videoRange} hls.loadLevel:${m}`)),S&&(this.firstSelection=C),C}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},vo={search:function(r,e){let t=0,i=r.length-1,s=null,n=null;for(;t<=i;){s=(t+i)/2|0,n=r[s];let a=e(n);if(a>0)t=s+1;else if(a<0)i=s-1;else return n}return null}};function Bc(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!O(e))return null;let i=r[0].programDateTime;if(e<(i||0))return null;let s=r[r.length-1].endProgramDateTime;if(e>=(s||0))return null;for(let n=0;n<r.length;++n){let a=r[n];if($c(e,t,a))return a}return null}function gt(r,e,t=0,i=0,s=.005){let n=null;if(r){n=e[1+r.sn-e[0].sn]||null;let o=r.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&r.level!==n.level&&n.end<=r.end&&(n=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!r||r.level===n.level)&&ia(t,i,n)===0||Uc(n,r,Math.min(s,i))))return n;let a=vo.search(e,ia.bind(null,t,i));return a&&(a!==r||!n)?a:n}function Uc(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){let i=e.tagList.reduce((s,n)=>(n[0]==="INF"&&(s+=parseFloat(n[1])),s),t);return r.start<=i}return!1}function ia(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=r?1:t.start-i>r&&t.start?-1:0}function $c(r,e,t){let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function Eo(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){let i=r.fragments,{fragmentHint:s}=r;s&&(i=i.concat(s));let n;return vo.search(i,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Ci(r){switch(r.details){case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_TIMEOUT:case L.LEVEL_LOAD_TIMEOUT:case L.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function To(r){return r.details.startsWith("key")}function So(r){return To(r)&&!!r.frag&&!r.frag.decryptdata}function sa(r,e){let t=Ci(e);return r.default[`${t?"timeout":"error"}Retry`]}function Er(r,e){let t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function na(r){return ee(ee({},r),{errorRetry:null,timeoutRetry:null})}function ki(r,e,t,i){if(!r)return!1;let s=i?.code,n=e<r.maxNumRetry&&(Gc(s)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,i,n):n}function Gc(r){return sn(r)||!!r&&(r<400||r>499)}function sn(r){return r===0&&navigator.onLine===!1}var fe={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Re={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},nn=class extends Le{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(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.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,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;let s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(a=>s.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;let s=this.hls,n=t.context;switch(t.details){case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case L.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=It();return}case L.FRAG_GAP:case L.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=fe.SendAlternateToPenaltyBox;return}case L.LEVEL_EMPTY_ERROR:case L.LEVEL_PARSING_ERROR:{var a;let c=t.parent===N.MAIN?t.level:s.loadLevel;t.details===L.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_LOAD_ERROR:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let c=s.loadLevelObj;if(c&&(n.type===z.AUDIO_TRACK&&c.hasAudioGroup(n.groupId)||n.type===z.SUBTITLE_TRACK&&c.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=fe.SendAlternateToPenaltyBox,t.errorAction.flags=Re.MoveAllAlternatesMatchingHost;return}}return;case L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:fe.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingHDCP};return;case L.KEY_SYSTEM_SESSION_UPDATE_FAILED:case L.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case L.KEY_SYSTEM_NO_SESSION:t.errorAction={action:fe.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingKey};return;case L.BUFFER_ADD_CODEC_ERROR:case L.REMUX_ALLOC_ERROR:case L.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:s.loadLevel)}return;case L.INTERNAL_EXCEPTION:case L.BUFFER_APPENDING_ERROR:case L.BUFFER_FULL_ERROR:case L.LEVEL_SWITCH_ERROR:case L.BUFFER_STALLED_ERROR:case L.BUFFER_SEEK_OVER_HOLE:case L.BUFFER_NUDGE_ON_STALL:t.errorAction=It();return}t.type===K.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=It())}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,s=sa(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(ki(s,n,Ci(e),e.response))return{action:fe.RetryRequest,flags:Re.None,retryConfig:s,retryCount:n};let o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=sa(To(e)?a:n,e),c=t.levels.reduce((d,h)=>d+h.fragmentError,0);if(s&&(e.details!==L.FRAG_GAP&&s.fragmentError++,!So(e)&&ki(o,c,Ci(e),e.response)))return{action:fe.RetryRequest,flags:Re.None,retryConfig:o,retryCount:c};let l=this.getLevelSwitchAction(e,i);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){let i=this.hls;t==null&&(t=i.loadLevel);let s=this.hls.levels[t];if(s){var n,a;let l=e.details;s.loadError++,l===L.BUFFER_APPEND_ERROR&&s.fragmentError++;let d=-1,{levels:h,loadLevel:u,minAutoLevel:f,maxAutoLevel:g}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);let y=(n=e.frag)==null?void 0:n.type,v=(y===N.AUDIO&&l===L.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===L.BUFFER_ADD_CODEC_ERROR||l===L.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:_})=>s.audioCodec!==_),T=e.sourceBufferName==="video"&&(l===L.BUFFER_ADD_CODEC_ERROR||l===L.BUFFER_APPEND_ERROR)&&h.some(({codecSet:_,audioCodec:b})=>s.codecSet!==_&&s.audioCodec===b),{type:S,groupId:x}=(a=e.context)!=null?a:{};for(let _=h.length;_--;){let b=(_+u)%h.length;if(b!==u&&b>=f&&b<=g&&h[b].loadError===0){var o,c;let R=h[b];if(l===L.FRAG_GAP&&y===N.MAIN&&e.frag){let I=h[b].details;if(I){let A=gt(e.frag,I.fragments,e.frag.start);if(A!=null&&A.gap)continue}}else{if(S===z.AUDIO_TRACK&&R.hasAudioGroup(x)||S===z.SUBTITLE_TRACK&&R.hasSubtitleGroup(x))continue;if(y===N.AUDIO&&(o=s.audioGroups)!=null&&o.some(I=>R.hasAudioGroup(I))||y===N.SUBTITLE&&(c=s.subtitleGroups)!=null&&c.some(I=>R.hasSubtitleGroup(I))||v&&s.audioCodec===R.audioCodec||T&&s.codecSet===R.codecSet||!v&&s.codecSet!==R.codecSet)continue}d=b;break}}if(d>-1&&i.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:fe.SendAlternateToPenaltyBox,flags:Re.None,nextAutoLevel:d}}return{action:fe.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case fe.DoNothing:break;case fe.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==L.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 fe.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:s}=i,n=i.nextAutoLevel;switch(s){case Re.None:this.switchLevel(e,n);break;case Re.MoveAllAlternatesMatchingHDCP:{let c=this.getVariantLevelIndex(e.frag),l=t.levels[c],d=l?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=d,d==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(d){t.maxHdcpLevel=en[en.indexOf(d)-1],i.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,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) ${pe(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)i.resolved=!0;else if(h&&h.type!==N.MAIN){let u=h.decryptdata;u&&!c.matches(u)&&(i.resolved=!0)}}break}}i.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===L.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let i=Js(e.mimeType),s=this.hls.levels;for(let n=s.length;n--;)s[n][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(n))}}};function It(r){let e={action:fe.DoNothing,flags:Re.None};return r&&(e.resolved=!0),e}var de={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},rn=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e&&(e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let s=i.length;s--;){let n=i[s];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){let{fragments:s}=this,n=Object.keys(s);for(let a=n.length;a--;){let o=s[n[a]];if(o?.body.type===t&&(!i||o.buffered)){let c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,i,s,n){this.timeRanges&&(this.timeRanges[e]=t);let a=s?.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===i&&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 i=e.frag,s=Et(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;let a=!i.relurl;Object.keys(t).forEach(o=>{let c=i.elementaryStreams[o];if(!c)return;let l=t[o],d=a||c.partial===!0;n.range[o]=this.getBufferedTimes(i,e.part,d,l)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,i),ai(n)||this.removeParts(i.sn-1,i.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 i=this.activePartLists[t];i&&(this.activePartLists[t]=ra(i,s=>s.fragment.sn>=e))}fragBuffered(e,t){let i=Et(e),s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,e))}getBufferedTimes(e,t,i,s){let n={time:[],partial:i},a=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||a;for(let d=0;d<s.length;d++){let h=s.start(d)-this.bufferPadding,u=s.end(d)+this.bufferPadding;if(l>=h&&c<=u){n.time.push({startPTS:Math.max(a,s.start(d)),endPTS:Math.min(o,s.end(d))});break}else if(a<u&&o>h){let f=Math.max(a,s.start(d)),g=Math.min(o,s.end(d));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}else if(o<=h)break}return n}getPartialFragment(e){let t=null,i,s,n,a=0,{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{let d=c[l];d&&ai(d)&&(s=d.body.start-o,n=d.body.end+o,e>=s&&e<=n&&(i=Math.min(e-s,n-e),a<=i&&(t=d.body,a=i)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||ai(t))}getState(e){let t=Et(e),i=this.fragments[t];return i?i.buffered?ai(i)?de.PARTIAL:de.OK:de.APPENDING:de.NOT_LOADED}isTimeBuffered(e,t,i){let s,n;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=s&&t<=n)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;let i=t.frag,s=t.part?null:t,n=Et(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:s,timeRanges:n,type:a}=t;if(i.sn==="initSegment")return;let o=i.type;if(s){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(s)}this.timeRanges=n;let c=n[a];this.detectEvictedFragments(a,c,o,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Et(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){let n=t[i[s]];if(n?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let c=o.body;c.type!==i||s&&!c.gap||c.start<t&&c.end>e&&(o.buffered||n)&&this.removeFragment(c)})}removeFragment(e){let t=Et(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let s=e.sn;this.activePartLists[e.type]=ra(i,n=>n.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}};function ai(r){var e,t,i;return r.buffered&&!!(r.body.gap||(e=r.range.video)!=null&&e.partial||(t=r.range.audio)!=null&&t.partial||(i=r.range.audiovideo)!=null&&i.partial)}function Et(r){return`${r.type}_${r.level}_${r.sn}`}function ra(r,e){return r.filter(t=>{let i=e(t);return i||t.clearElementaryStreamInfo(),i})}var st={cbc:0,ctr:1},an=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case st.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case st.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 on=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],a=i[2],o=i[3],c=this.invSubMix,l=c[0],d=c[1],h=c[2],u=c[3],f=new Uint32Array(256),g=0,y=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let v=y^y<<1^y<<2^y<<3^y<<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;s[g]=x<<24|x>>>8,n[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,d[v]=x<<16|x>>>16,h[v]=x<<8|x>>>24,u[v]=x,g?(g=E^f[f[f[S^E]]],y^=f[f[y]]):g=y=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let a=this.ksRows=(n+6+1)*4,o,c,l=this.keySchedule=new Uint32Array(a),d=this.invKeySchedule=new Uint32Array(a),h=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],y=f[1],m=f[2],v=f[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]=g[h[T>>>24]]^y[h[T>>>16&255]]^m[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,i){let s=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_(i),f=u[0],g=u[1],y=u[2],m=u[3],v=new Int32Array(e),E=new Int32Array(v.length),T,S,x,_,b,R,I,A,P,M,B,V,U,C,$=this.networkToHostOrderSwap;for(;t<v.length;){for(P=$(v[t]),M=$(v[t+1]),B=$(v[t+2]),V=$(v[t+3]),b=P^n[0],R=V^n[1],I=B^n[2],A=M^n[3],U=4,C=1;C<s;C++)T=c[b>>>24]^l[R>>16&255]^d[I>>8&255]^h[A&255]^n[U],S=c[R>>>24]^l[I>>16&255]^d[A>>8&255]^h[b&255]^n[U+1],x=c[I>>>24]^l[A>>16&255]^d[b>>8&255]^h[R&255]^n[U+2],_=c[A>>>24]^l[b>>16&255]^d[R>>8&255]^h[I&255]^n[U+3],b=T,R=S,I=x,A=_,U=U+4;T=a[b>>>24]<<24^a[R>>16&255]<<16^a[I>>8&255]<<8^a[A&255]^n[U],S=a[R>>>24]<<24^a[I>>16&255]<<16^a[A>>8&255]<<8^a[b&255]^n[U+1],x=a[I>>>24]<<24^a[A>>16&255]<<16^a[b>>8&255]<<8^a[R&255]^n[U+2],_=a[A>>>24]<<24^a[b>>16&255]<<16^a[R>>8&255]<<8^a[I&255]^n[U+3],E[t]=$(T^f),E[t+1]=$(_^g),E[t+2]=$(x^y),E[t+3]=$(S^m),f=P,g=M,y=B,m=V,t=t+4}return E.buffer}},ln=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){let e=Vc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function Vc(r){switch(r){case st.cbc:return"AES-CBC";case st.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}var Hc=16,Ht=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 i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Kc(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s){return this.useSoftware?new Promise((n,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,i,s);let c=this.flush();c?n(c.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){let{currentIV:n,currentResult:a,remainderData:o}=this;if(s!==st.cbc||t.byteLength!==16)return te.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;n&&(i=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new on),l.expandKey(t);let d=a;return this.currentResult=l.decrypt(c.buffer,0,i),this.currentIV=c.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new ln(this.subtle,t,s)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new an(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(te.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%Hc;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(te.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},aa=Math.pow(2,17),cn=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 i=e.url;if(!i)return Promise.reject(new Ne({type:K.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();let s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){c(la(e));return}else e.gap=!1;let l=this.loader=n?new n(s):new a(s),d=oa(e);e.loader=l;let h=na(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:aa};e.stats=l.stats;let f={onSuccess:(g,y,m,v)=>{this.resetLoader(e,l);let E=g.data;m.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,y,m,v)=>{this.resetLoader(e,l),c(new Ne({type:K.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ee({url:i,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:m,stats:v}))},onAbort:(g,y,m)=>{this.resetLoader(e,l),c(new Ne({type:K.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:m,stats:g}))},onTimeout:(g,y,m)=>{this.resetLoader(e,l),c(new Ne({type:K.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:m,stats:g}))}};t&&(f.onProgress=(g,y,m,v)=>t({frag:e,part:null,payload:m,networkDetails:v})),l.load(d,u,f)})}loadPart(e,t,i){this.abort();let s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(la(e,t));return}let l=this.loader=n?new n(s):new a(s),d=oa(e,t);e.loader=l;let h=na(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:aa};t.stats=l.stats,l.load(d,u,{onSuccess:(f,g,y,m)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:m};i(v),o(v)},onError:(f,g,y,m)=>{this.resetLoader(e,l),c(new Ne({type:K.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ee({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:m}))},onAbort:(f,g,y)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new Ne({type:K.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,g,y)=>{this.resetLoader(e,l),c(new Ne({type:K.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:y,stats:f}))}})})}updateStatsFromPart(e,t){let i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){let c=Math.round(e.duration/t.duration),l=Math.min(Math.round(i.loaded/n),c),h=(c-l)*Math.round(i.loaded/l);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);let a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function oa(r,e=null){let t=e||r,i={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},s=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(O(s)&&O(n)){var a;let o=s,c=n;if(r.sn==="initSegment"&&Yc((a=r.decryptdata)==null?void 0:a.method)){let l=n-s;l%16&&(c=n+(16-l%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=c}return i}function la(r,e){let t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:K.MEDIA_ERROR,details:L.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new Ne(i)}function Yc(r){return r==="AES-128"||r==="AES-256"}var Ne=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},wi=class extends Le{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(){}},Yt=class{constructor(e,t,i,s=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=oi(),this.buffering={audio:oi(),video:oi(),audiovideo:oi()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=a}};function oi(){return{start:0,executeStart:0,executeEnd:0,end:0}}var ca={length:0,start:()=>0,end:()=>0},q=class r{static isBuffered(e,t){if(e){let i=r.getBuffered(e);for(let s=i.length;s--;)if(t>=i.start(s)&&t<=i.end(s))return!0}return!1}static bufferedRanges(e){if(e){let t=r.getBuffered(e);return r.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let s=r.bufferedRanges(e);if(s.length)return r.bufferedInfo(s,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((d,h)=>d.start-h.start||h.end-d.end);let s=-1,n=[];if(i)for(let d=0;d<e.length;d++){t>=e[d].start&&t<=e[d].end&&(s=d);let h=n.length;if(h){let u=n[h-1].end;e[d].start-u<i?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(s===-1&&t>=h&&t<=u&&(s=d),t+i>=h&&t<u)c=h,l=u,a=l-t;else if(t+i<h){o=h;break}}return{len:a,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||ca}catch(t){return te.log("failed to get media.buffered",t),ca}}},xo=/\{\$([a-zA-Z0-9-_]+)\}/g;function da(r){return xo.test(r)}function dn(r,e){if(r.variableList!==null||r.hasVariableRefs){let t=r.variableList;return e.replace(xo,i=>{let s=i.substring(2,i.length-1),n=t?.[s];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return e}function ha(r,e,t){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(s))n=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(a){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,n=e.VALUE;s in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function qc(r,e,t){let i=e.IMPORT;if(t&&i in t){let s=r.variableList;s||(r.variableList=s={}),s[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}var Wc=/^(\d+)x(\d+)$/,ua=/(.+?)=(".*?"|.*?)(?:,|$)/g,re=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 i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((s,n)=>(s[n.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=Wc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,s={};for(ua.lastIndex=0;(i=ua.exec(e))!==null;){let a=i[1].trim(),o=i[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=dn(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":te.warn(`${e}: attribute ${a} is missing quotes`)}s[a]=o}return s}},jc="com.apple.hls.interstitial";function Qc(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function zc(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}var Mi=class{constructor(e,t,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(s=t?.tagOrder)!=null?s:i,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){te.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ie(new re({}),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"]);O(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?(te.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===jc}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)}},Xc=10,hn=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,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?O(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Xc}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function Oi(r,e){return r.length===e.length?!r.some((t,i)=>t!==e[i]):!1}function fa(r,e){return!r&&!e?!0:!r||!e?!1:Oi(r,e)}function Rt(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function Tr(r){switch(r){case"AES-128":case"AES-256":return st.cbc;case"AES-256-CTR":return st.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Sr(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function un(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function Zc(r){let e=un(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function bo(r){let e=function(i,s,n){let a=i[s];i[s]=i[n],i[n]=a};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function Ao(r){let e=r.split(":"),t=null;if(e[0]==="data"&&e.length===2){let i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){let n=s[0]==="base64",a=s[1];n?(i.splice(-1,1),t=Sr(a)):t=Zc(a)}}return t}var Fi=typeof self<"u"?self:void 0,ae={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},me={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ti(r){switch(r){case me.FAIRPLAY:return ae.FAIRPLAY;case me.PLAYREADY:return ae.PLAYREADY;case me.WIDEVINE:return ae.WIDEVINE;case me.CLEARKEY:return ae.CLEARKEY}}function Ps(r){switch(r){case ae.FAIRPLAY:return me.FAIRPLAY;case ae.PLAYREADY:return me.PLAYREADY;case ae.WIDEVINE:return me.WIDEVINE;case ae.CLEARKEY:return me.CLEARKEY}}function Ft(r){let{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[ae.FAIRPLAY,ae.WIDEVINE,ae.PLAYREADY,ae.CLEARKEY].filter(s=>!!e[s]):[];return!i[ae.WIDEVINE]&&t&&i.push(ae.WIDEVINE),i}var Lo=(function(r){return Fi!=null&&(r=Fi.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Jc(r,e,t,i){let s;switch(r){case ae.FAIRPLAY:s=["cenc","sinf"];break;case ae.WIDEVINE:case ae.PLAYREADY:s=["cenc"];break;case ae.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return ed(s,e,t,i)}function ed(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function td(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Io(r){let e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let c=Sr(o).subarray(0,16);return bo(c),c}}return null}var Tt={},Ct=class r{static clearKeyUriToKeyIdMap(){Tt={}}static setKeyIdForUri(e,t){Tt[e]=t}static addKeyIdForUri(e){let t=Object.keys(Tt).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Tt[e]=i,i}constructor(e,t,i,s=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Rt(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(io(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Oi(e.keyFormatVersions,this.keyFormatVersions)&&fa(e.iv,this.iv)&&fa(e.keyId,this.keyId)}isSupported(){if(this.method){if(Rt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case me.FAIRPLAY:case me.WIDEVINE:case me.PLAYREADY:case me.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(Rt(this.method)){let n=this.iv;return n||(typeof e!="number"&&(te.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=sd(e)),new r(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){let n=Tt[this.uri];if(n&&!Oi(this.keyId,n)&&r.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let i=Ao(this.uri);if(i)switch(this.keyFormat){case me.WIDEVINE:if(this.pssh=i,!this.keyId){let n=gc(i.buffer);if(n.length){var s;let a=n[0];this.keyId=(s=a.kids)!=null&&s.length?a.kids[0]:null}}this.keyId||(this.keyId=ga(t));break;case me.PLAYREADY:{let n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=fc(n,null,i),this.keyId=Io(i);break}default:{let n=i.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=id(t),n||(n=ga(t),n||(n=Tt[this.uri])),n&&(this.keyId=n,r.setKeyIdForUri(this.uri,n))}return this}};function id(r){let e=r?.[me.WIDEVINE];return e?e.keyId:null}function ga(r){let e=r?.[me.PLAYREADY];if(e){let t=Ao(e.uri);if(t)return Io(t)}return null}function sd(r){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}var pa=/#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,ma=/#EXT-X-MEDIA:(.*)/g,nd=/^#EXT(?:INF|-X-TARGETDURATION):/m,Cs=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),rd=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("|")),dt=class r{static findGroup(e,t){for(let i=0;i<e.length;i++){let s=e[i];if(s.id===t)return s}}static resolve(e,t){return pr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return nd.test(e)}static parseMasterPlaylist(e,t){let i=da(e),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];if(pa.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let a;for(;(a=pa.exec(e))!=null;)if(a[1]){var o;let l=new re(a[1],s),d=dn(s,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),Ea(l.CODECS,h);let f=l["SUPPLEMENTAL-CODECS"];f&&(h.supplemental={},Ea(f,h.supplemental)),(o=h.unknownCodecs)!=null&&o.length||n.push(h),s.levels.push(h)}else if(a[3]){let l=a[3],d=a[4];switch(l){case"SESSION-DATA":{let h=new re(d,s),u=h["DATA-ID"];u&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[u]=h);break}case"SESSION-KEY":{let h=ya(d,t,s);h.encrypted&&h.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(h)):te.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{let h=new re(d,s);ha(s,h,t)}break}case"CONTENT-STEERING":{let h=new re(d,s);s.contentSteering={uri:r.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=va(d);break}}}let c=n.length>0&&n.length<s.levels.length;return s.levels=c?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s,n={},a=i.levels,o={AUDIO:a.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]},c=0;for(ma.lastIndex=0;(s=ma.exec(e))!==null;){let l=new re(s[1],i),d=l.TYPE;if(d){let h=o[d],u=n[d]||[];n[d]=u;let f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],y=l.CHANNELS,m=l.CHARACTERISTICS,v=l["INSTREAM-ID"],E={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:d,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?r.resolve(l.URI,t):""};if(g&&(E.assocLang=g),y&&(E.channels=y),m&&(E.characteristics=m),v&&(E.instreamId=v),h!=null&&h.length){let T=r.findGroup(h,E.groupId)||h[0];Ta(E,T,"audioCodec"),Ta(E,T,"textCodec")}u.push(E)}}return n}static parseLevelPlaylist(e,t,i,s,n,a){var o;let c={url:t},l=new hn(t),d=l.fragments,h=[],u=null,f=0,g=0,y=0,m=0,v=0,E=null,T=new Nt(s,c),S,x,_,b=-1,R=!1,I=null,A;if(Cs.lastIndex=0,l.m3u8=e,l.hasVariableRefs=da(e),((o=Cs.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=Cs.exec(e))!==null;){R&&(R=!1,T=new Nt(s,c),T.playlistOffset=y,T.setStart(y),T.sn=f,T.cc=m,v&&(T.bitrate=v),T.level=i,u&&(T.initSegment=u,u.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),I&&(T.setByteRange(I),I=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=y,T.setStart(y),_&&xa(T,_,l),T.sn=f,T.level=i,T.cc=m,d.push(T);let U=(" "+S[3]).slice(1);T.relurl=dn(l,U),fn(T,E,h),E=T,y+=T.duration,f++,g=0,R=!0}}else{if(S=S[0].match(rd),!S){te.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),C=(" "+S[x+1]).slice(1),$=S[x+2]?(" "+S[x+2]).slice(1):null;switch(U){case"BYTERANGE":E?T.setByteRange(C,E):T.setByteRange(C);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=C,T.tagList.push(["PROGRAM-DATE-TIME",C]),b===-1&&(b=d.length);break;case"PLAYLIST-TYPE":l.type&&Ye(l,U,S),l.type=C.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Ye(l,U,S):d.length>0&&ba(l,U,S),f=l.startSN=parseInt(C);break;case"SKIP":{l.skippedSegments&&Ye(l,U,S);let F=new re(C,l),G=F.decimalInteger("SKIPPED-SEGMENTS");if(O(G)){l.skippedSegments+=G;for(let k=G;k--;)d.push(null);f+=G}let H=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");H&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(H.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&Ye(l,U,S),l.targetduration=Math.max(parseInt(C),1);break;case"VERSION":l.version!==null&&Ye(l,U,S),l.version=parseInt(C);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Ye(l,U,S),l.live=!1;break;case"#":(C||$)&&T.tagList.push($?[C,$]:[C]);break;case"DISCONTINUITY":m++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([U]);break;case"BITRATE":T.tagList.push([U,C]),v=parseInt(C)*1e3,O(v)?T.bitrate=v:v=0;break;case"DATERANGE":{let F=new re(C,l),G=new Mi(F,l.dateRanges[F.ID],l.dateRangeTagCount);l.dateRangeTagCount++,G.isValid||l.skippedSegments?l.dateRanges[G.id]=G:te.warn(`Ignoring invalid DATERANGE tag: "${C}"`),T.tagList.push(["EXT-X-DATERANGE",C]);break}case"DEFINE":{{let F=new re(C,l);"IMPORT"in F?qc(l,F,a):ha(l,F,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Ye(l,U,S):d.length>0&&ba(l,U,S),l.startCC=m=parseInt(C);break;case"KEY":{let F=ya(C,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 te.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${C}"`);break}case"START":l.startTimeOffset=va(C);break;case"MAP":{let F=new re(C,l);if(T.duration){let G=new Nt(s,c);Sa(G,F,i,_),u=G,T.initSegment=u,u.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime)}else{let G=T.byteRangeEndOffset;if(G){let H=T.byteRangeStartOffset;I=`${G-H}@${H}`}else I=null;Sa(T,F,i,_),u=T,R=!0}u.cc=m;break}case"SERVER-CONTROL":{A&&Ye(l,U,S),A=new re(C),l.canBlockReload=A.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=A.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&A.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=A.optionalFloat("PART-HOLD-BACK",0),l.holdBack=A.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Ye(l,U,S);let F=new re(C);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,H=g++,k=new re(C,l),w=new Zs(k,T,c,H,G);F.push(w),T.duration+=w.duration;break}case"PRELOAD-HINT":{let F=new re(C,l);l.preloadHint=F;break}case"RENDITION-REPORT":{let F=new re(C,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(F);break}default:te.warn(`line parsed but not handled: ${S}`);break}}}E&&!E.relurl?(d.pop(),y-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(fn(T,E,h),T.cc=m,l.fragmentHint=T,_&&xa(T,_,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));let P=d.length,M=d[0],B=d[P-1];if(y+=l.skippedSegments*l.targetduration,y>0&&P&&B){l.averagetargetduration=y/P;let V=B.sn;l.endSN=V!=="initSegment"?V:0,l.live||(B.endList=!0),b>0&&(od(d,b),M&&h.unshift(M))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,h.length&&l.dateRangeTagCount&&M&&Ro(h,l),l.endCC=m,l}};function Ro(r,e){let t=r.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];r.push(o),t++}else return;let i=r[t-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let c=e.dateRanges[n[o]],l=c.startDate.getTime();c.tagAnchor=i.ref;for(let d=t;d--;){var a;if(((a=r[d])==null?void 0:a.sn)<e.startSN)break;let h=ad(e,l,r,d,s);if(h!==-1){c.tagAnchor=e.fragments[h].ref;break}}}}function ad(r,e,t,i,s){let n=t[i];if(n){let o=n.programDateTime;if(e>=o||i===0){var a;let c=(((a=t[i+1])==null?void 0:a.start)||s)-n.start;if(e<=o+c*1e3){let l=t[i].sn-r.startSN;if(l<0)return-1;let d=r.fragments;if(d.length>t.length){let u=(t[i+1]||d[d.length-1]).sn-r.startSN;for(let f=u;f>l;f--){let g=d[f].programDateTime;if(e>=g&&e<g+d[f].duration*1e3)return f}}return l}}}return-1}function ya(r,e,t){var i,s;let n=new re(r,t),a=(i=n.METHOD)!=null?i:"",o=n.URI,c=n.hexadecimalInteger("IV"),l=n.KEYFORMATVERSIONS,d=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!c&&te.error(`Invalid IV: ${n.IV}`);let h=o?dt.resolve(o,e):"",u=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Ct(a,h,d,u,c,n.KEYID)}function va(r){let t=new re(r).decimalFloatingPoint("TIME-OFFSET");return O(t)?t:null}function Ea(r,e){let t=(r||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{let s=t.filter(n=>yr(n,i));s.length&&(e[`${i}Codec`]=s.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>s.indexOf(n)===-1))}),e.unknownCodecs=t}function Ta(r,e,t){let i=e[t];i&&(r[t]=i)}function od(r,e){let t=r[e];for(let i=e;i--;){let s=r[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function fn(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function Sa(r,e,t,i){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function xa(r,e,t){r.levelkeys=e;let{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(r)}function Ye(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function ba(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function ks(r,e){let t=e.startPTS;if(O(t)){let i=0,s;e.sn>r.sn?(i=t-r.start,s=r):(i=r.start-t,s=e),s.duration!==i&&s.setDuration(i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function _o(r,e,t,i,s,n,a){i-t<=0&&(a.warn("Fragment should have a positive duration",e),i=t+e.duration,n=s+e.duration);let c=t,l=i,d=e.startPTS,h=e.endPTS;if(O(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}`):O(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,c=Math.max(t,d),t=Math.min(t,d),s=e.startDTS!==void 0?Math.min(s,e.startDTS):s,l=Math.min(i,h),i=Math.max(i,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(i-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=s,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;let f=e.sn;if(!r||f<r.startSN||f>r.endSN)return 0;let g,y=f-r.startSN,m=r.fragments;for(m[y]=e,g=y;g>0;g--)ks(m[g],m[g-1]);for(g=y;g<m.length-1;g++)ks(m[g],m[g+1]);return r.fragmentHint&&ks(m[m.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,u}function ld(r,e,t){if(r===e)return;let i=null,s=r.fragments;for(let d=s.length-1;d>=0;d--){let h=s[d].initSegment;if(h){i=h;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;hd(r,e,(d,h,u,f)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==d.cc){let g=d.cc-h.cc;for(let y=u;y<f.length;y++)f[y].cc+=g;e.endCC=f[f.length-1].cc}O(d.startPTS)&&O(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,i=d.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(d=>{var h;d&&(!d.initSegment||d.initSegment.relurl===((h=i)==null?void 0:h.relurl))&&(d.initSegment=i)}),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=cd(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&&fn(o[h],o[h-1],d);Ro(d,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var c;let d=Co(r,e.startSN-1);e.startCC=(c=d?.cc)!=null?c:a[0].cc}dd(r.partList,e.partList,(d,h)=>{h.elementaryStreams=d.elementaryStreams,h.stats=d.stats}),n?_o(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):Do(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 cd(r,e,t){let{dateRanges:i,recentlyRemovedDateranges:s}=e,n=ie({},r);s&&s.forEach(c=>{delete n[c]});let o=Object.keys(n).length;return o?(Object.keys(i).forEach(c=>{let l=n[c],d=new Mi(i[c].attr,l);d.isValid?(n[c]=d,l||(d.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ne(i[c].attr)}"`)}),n):i}function dd(r,e,t){if(r&&e){let i=0;for(let s=0,n=r.length;s<=n;s++){let a=r[s],o=e[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function hd(r,e,t){let i=e.skippedSegments,s=Math.max(r.startSN,e.startSN)-e.startSN,n=(r.fragmentHint?1:0)+(i?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=s;l<=n;l++){let d=c[a+l],h=o[l];if(i&&!h&&d&&(h=e.fragments[l]=d),d&&h){t(d,h,l,o);let u=d.relurl,f=h.relurl;if(u&&ud(u,f)){e.playlistParsingError=Aa(`media sequence mismatch ${h.sn}:`,r,e,d,h);return}else if(d.cc!==h.cc){e.playlistParsingError=Aa(`discontinuity sequence mismatch (${d.cc}!=${h.cc})`,r,e,d,h);return}}}}function Aa(r,e,t,i,s){return new Error(`${r} ${s.url}
|
|
12
|
+
Playlist starting @${e.startSN}
|
|
13
|
+
${e.m3u8}
|
|
14
|
+
|
|
15
|
+
Playlist starting @${t.startSN}
|
|
16
|
+
${t.m3u8}`)}function Do(r,e,t=!0){let i=e.startSN+e.skippedSegments-r.startSN,s=r.fragments,n=i>=0,a=0;if(n&&i<s.length)a=s[i].start;else if(n&&e.startSN===r.endSN+1)a=r.fragmentEnd;else if(n&&t)a=r.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=r.fragmentStart;else return;gn(e,a)}function gn(r,e){if(e){let t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function Po(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){let i=r.fragments;if(i.length&&t*4>e){let n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function Co(r,e,t){if(!r)return null;let i=r.fragments[e-r.startSN];return i||(i=r.fragmentHint,i&&i.sn===e)?i:e<r.startSN&&t&&t.sn===e?t:null}function La(r,e,t){return r?ko(r.partList,e,t):null}function ko(r,e,t){if(r)for(let i=r.length;i--;){let s=r[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function wo(r){r.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(s=>{s.level=t,s.initSegment&&(s.initSegment.level=t)})})}function ud(r,e){return r!==e&&e?Ia(r)!==Ia(e):!1}function Ia(r){return r.replace(/\?[^?]*$/,"")}function Bt(r,e){for(let i=0,s=r.length;i<s;i++){var t;if(((t=r[i])==null?void 0:t.cc)===e)return r[i]}return null}function fd(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function Ra(r,e){let t=r.start+e;r.startPTS=t,r.setStart(t),r.endPTS=t+r.duration}function Mo(r,e){let t=e.fragments;for(let i=0,s=t.length;i<s;i++)Ra(t[i],r);e.fragmentHint&&Ra(e.fragmentHint,r),e.alignedSliding=!0}function gd(r,e){r&&(Oo(e,r),e.alignedSliding||Ni(e,r),!e.alignedSliding&&!e.skippedSegments&&Do(r,e,!1))}function Oo(r,e){if(!fd(e,r))return;let t=Math.min(e.endCC,r.endCC),i=Bt(e.fragments,t),s=Bt(r.fragments,t);if(!i||!s)return;te.log(`Aligning playlist at start of dicontinuity sequence ${t}`);let n=i.start-s.start;Mo(n,r)}function Ni(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;let t=r.fragments,i=e.fragments;if(!t.length||!i.length)return;let s,n,a=Math.min(e.endCC,r.endCC);e.startCC<a&&r.startCC<a&&(s=Bt(i,a),n=Bt(t,a)),(!s||!n)&&(s=i[Math.floor(i.length/2)],n=Bt(t,s.cc)||t[Math.floor(t.length/2)]);let o=s.programDateTime,c=n.programDateTime;if(!o||!c)return;let l=(c-o)/1e3-(n.start-s.start);Mo(l,r)}function Te(r,e,t){Ae(r,e,t),r.addEventListener(e,t)}function Ae(r,e,t){r.removeEventListener(e,t)}var pd={toString:function(r){let e="",t=r.length;for(let i=0;i<t;i++)e+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return e}},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"},qt=class extends wi{constructor(e,t,i,s,n){super(s,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:d}=this,h=c?c.currentTime:0,u=q.bufferInfo(l||c,h,a.maxBufferHole),f=!u.len;if(this.log(`Media seeking to ${O(h)?h.toFixed(3):h}, state: ${d}, ${f?"out of":"in"} buffer`),this.state===D.ENDED)this.resetLoadingState();else if(o){let g=a.maxFragLookUpTolerance,y=o.start-g,m=o.start+o.duration+g;if(f||m<u.start||y>u.end){let v=h>m;(h<y||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 g=this.lastCurrentTime;if(h>g&&(this.lastCurrentTime=h),!this.loadingParts){let y=Math.max(u.end,h),m=this.shouldLoadParts(this.getLevelDetails(),y);m&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${y.toFixed(2)}`),this.loadingParts=m)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,f&&(this.startPosition=h)),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=n,this.hls=e,this.fragmentLoader=new cn(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ht(e.config)}registerListeners(){let{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.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 i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=q.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>s&&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 i=this.media=this.mediaBuffer=t.media;Te(i,"seeking",this.onMediaSeeking),Te(i,"ended",this.onMediaEnded);let s=this.config;this.levels&&s.autoStartLoad&&this.state===D.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){let i=!!t.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ae(s,"seeking",this.onMediaSeeking),Ae(s,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(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,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){let s=n=>{let a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,s).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===D.FRAG_LOADING||!this.fragCurrent&&a===D.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=D.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(p.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===D.STOPPED||this.state===D.ERROR||(this.warn(`Frag error: ${n?.message||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===de.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))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===de.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let s={startOffset:e,endOffset:t,type:i};this.hls.trigger(p.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{let s=i?.frag;if(!s||this.fragContextChanged(s)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{let{hls:s}=this,{frag:n,payload:a}=i,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&Rt(o.method)){let c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Tr(o.method)).catch(l=>{throw s.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:n}),l}).then(l=>{let d=self.performance.now();return s.trigger(p.FRAG_DECRYPTED,{frag:n,payload:l,stats:{tstart:c,tdecrypt:d}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===D.STOPPED||this.state===D.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let i=e.frag.stats;this.state!==D.STOPPED&&(this.state=D.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,s;let n=e.tracks;if(n&&!t.encrypted&&((i=n.audio)!=null&&i.encrypted||(s=n.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(p.ERROR,{type:K.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?pd.toString(q.getBuffered(i)):"(detached)"})`),le(e)){var s;if(e.type!==N.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=D.IDLE;return}}let n=(s=this.levels)==null?void 0:s[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=D.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:s,partsLoaded:n}=e,a=!n||n.length===0||n.some(c=>!c),o=new Yt(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){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=D.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(p.KEY_LOADED,u),this.state===D.KEY_LOADING&&(this.state=D.IDLE),u}),this.hls.trigger(p.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(le(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(i=Math.max(e.start,i||0),this.loadingParts&&le(e)){let u=a.partList;if(u&&s){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let f=this.getNextPart(u,e,i);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(i.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=D.FRAG_LOADING;let y;return o?y=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,g,t,s)).catch(m=>this.handleFragLoadError(m)):y=this.doFragPartsLoad(e,g,t,s).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(p.FRAG_LOADING,{frag:e,part:g,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):y}else if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}if(le(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${i.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(i.toFixed(3))}`),O(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=D.FRAG_LOADING;let d=this.config.progressive&&e.type!==N.SUBTITLE,h;return d&&o?h=o.then(u=>!u||this.fragContextChanged(u.frag)?null:this.fragmentLoader.load(e,s)).catch(u=>this.handleFragLoadError(u)):h=Promise.all([this.fragmentLoader.load(e,d?s:void 0),o]).then(([u])=>(!d&&s&&s(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,i,s){return new Promise((n,a)=>{var o;let c=[],l=(o=i.details)==null?void 0:o.partList,d=h=>{this.fragmentLoader.loadPart(e,h,s).then(u=>{c[h.index]=u;let f=u.part;this.hls.trigger(p.FRAG_LOADED,u);let g=La(i.details,e.sn,h.index+1)||ko(l,e.sn,h.index+1);if(g)d(g);else return n({frag:e,part:f,partsLoaded:c})}).catch(a)};d(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===L.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===K.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:K.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==D.PARSING){!this.fragCurrent&&this.state!==D.STOPPED&&this.state!==D.ERROR&&(this.state=D.IDLE);return}let{frag:i,part:s,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a);let o=this.getLevelDetails(),l=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(i,s,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;let n=e.partList[0];if(n.fragment.type===N.SUBTITLE)return!1;let a=n.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){var s;if((this.hls.hasEnoughToStart?((s=this.media)==null?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:s,sn:n,part:a}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;let o=t[s],c=o.details,l=a>-1?La(c,n,a):null,d=l?l.fragment:Co(c,n,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:o}):null}bufferFragmentData(e,t,i,s,n){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],d=l?-l.baseTime/l.timescale:void 0,h={type:e.type,frag:t,part:i,chunkMeta:s,offset:d,parent:t.type,data:c};if(this.hls.trigger(p.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){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 i=t.currentTime,s=q.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,s.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;let s=this.getLoadPosition();if(!O(s))return null;let a=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,a)}getFwdBufferInfoAtPos(e,t,i,s){let n=q.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,s);return q.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return n>=s?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=N.MAIN){let i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,s=i.length;if(!s)return null;let{config:n}=this,a=i[0].start,o=n.lowLatencyMode&&!!t.partList,c=null;if(t.live){let h=n.initialLiveManifestSize;if(s<h)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${h})`),null;if(!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.hls.startPosition,f=this.hls.liveSyncPosition,g=c?(u!==-1&&u>=a?u:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${u} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=a&&(c=i[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(i[h+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){let i=this.fragmentTracker.getState(e);return(i===de.OK||i===de.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(o!==null&&i.len+o.len>=n){let c=a.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(_a(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(_a(this.config)&&e.type!==N.SUBTITLE){let i=this.hls.interstitialsManager,s=i?.bufferingItem;if(s){let a=s.event;if(a){if(a.appendInPlace||Math.abs(e.start-s.start)>1||s.start===0)return null}else if(e.end<=s.start&&t?.live===!1||e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}let n=i?.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,i){let s=-1,n=!1,a=!0;for(let o=0,c=e.length;o<c;o++){let l=e[o];if(a=a&&!l.independent,s>-1&&i<l.start)break;let d=l.loaded;d?s=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${l.start}`),s=o),n=d}return s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=Bc(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){let n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Eo(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{let n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){let{config:s}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=i,{fragmentHint:c}=i,{maxFragLookUpTolerance:l}=s,d=i.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 f;let y=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;u=gt(n,a,e,y)}else u=a[a.length-1];if(u){let g=u.sn-i.startSN,y=this.fragmentTracker.getState(u);if((y===de.OK||y===de.PARTIAL&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!h||d[0].fragment.sn>u.sn||!i.live)&&u.level===n.level){let v=a[g+1];u.sn<o&&this.fragmentTracker.getState(v)!==de.OK?u=v:u=null}}return u}alignPlaylists(e,t,i){let s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&O(n);if(a||!o&&!n){gd(i,e);let c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),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 i=this.startPosition;i<t&&(i=-1);let s=this.timelineOffset;if(i===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&O(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;let{media:t}=this,i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&le(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 i;if(t.chunkMeta&&!t.frag){let v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}let s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var n;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}let a=t.details===L.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);let o=t.errorAction;if(!o){this.state=D.ERROR;return}let{action:c,flags:l,retryCount:d=0,retryConfig:h}=o,u=!!h,f=u&&c===fe.RetryRequest,g=u&&!o.resolved&&l===Re.MoveAllAlternatesMatchingHost,y=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!f&&g&&le(s)&&!s.endList&&y&&!So(t))this.resetFragmentErrors(e),this.treatAsGap(s),o.resolved=!0;else if((f||g)&&d<h.maxNumRetry){var m;let v=sn((m=t.response)==null?void 0:m.code),E=Er(h,d);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 ${s.sn} of ${e} ${s.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!==fe.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${d})`);return}else c===fe.SendAlternateToPenaltyBox?this.state=D.WAITING_LEVEL:this.state=D.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!sn(0))&&(i&&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,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),n=s&&s.len>.5;n&&this.reduceMaxBufferLength(s.len,t?.duration||10);let a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} 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,i){if(!e)return;let s=q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),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,i,s){let n=i.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=s?0:_o(n,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS,this);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:n,level:i,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((i.fragmentError===0||c&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),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(p.ERROR,{type:K.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.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(p.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===N.MAIN?"level":"track"}fragInfo(e,t=!0,i){var s,n;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN).toFixed(3)}-${((n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(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 _a(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}var Bi=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,i;if(e.length)e.length===1?i=e[0]:i=md(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}};function md(r,e){let t=new Uint8Array(e),i=0;for(let s=0;s<r.length;s++){let n=r[s];t.set(n,i),i+=n.length}return t}var ws={exports:{}},Da;function yd(){return Da||(Da=1,(function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(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 f=new s(d,h||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 i:delete c._events[l]}function o(){this._events=new i,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,f=h.length,g=new Array(f);u<f;u++)g[u]=h[u].fn;return g},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,f,g){var y=t?t+l:l;if(!this._events[y])return!1;var m=this._events[y],v=arguments.length,E,T;if(m.fn){switch(m.once&&this.removeListener(l,m.fn,void 0,!0),v){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,d),!0;case 3:return m.fn.call(m.context,d,h),!0;case 4:return m.fn.call(m.context,d,h,u),!0;case 5:return m.fn.call(m.context,d,h,u,f),!0;case 6:return m.fn.call(m.context,d,h,u,f,g),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];m.fn.apply(m.context,E)}else{var S=m.length,x;for(T=0;T<S;T++)switch(m[T].once&&this.removeListener(l,m[T].fn,void 0,!0),v){case 1:m[T].fn.call(m[T].context);break;case 2:m[T].fn.call(m[T].context,d);break;case 3:m[T].fn.call(m[T].context,d,h);break;case 4:m[T].fn.call(m[T].context,d,h,u);break;default:if(!E)for(x=1,E=new Array(v-1);x<v;x++)E[x-1]=arguments[x];m[T].fn.apply(m[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 f=t?t+l:l;if(!this._events[f])return this;if(!d)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===d&&(!u||g.once)&&(!h||g.context===h)&&a(this,f);else{for(var y=0,m=[],v=g.length;y<v;y++)(g[y].fn!==d||u&&!g[y].once||h&&g[y].context!==h)&&m.push(g[y]);m.length?this._events[f]=m.length===1?m[0]:m:a(this,f)}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 i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o})(ws)),ws.exports}var vd=yd(),xr=Zl(vd),Wt="1.6.15",kt={};function Ed(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Td(){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),s={worker:new self.Worker(t),objectURL:t,clientCount:1};return kt[Wt]=s,s}function Sd(r){let e=kt[r];if(e)return e.clientCount++,e;let t=new self.URL(r,self.location.href).href,s={worker:new self.Worker(t),scriptURL:t,clientCount:1};return kt[r]=s,s}function xd(r){let e=kt[r||Wt];if(e&&e.clientCount--===1){let{worker:i,objectURL:s}=e;delete kt[r||Wt],s&&self.URL.revokeObjectURL(s),i.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 br(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 Zi(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 jt(r,e){let t=e,i=0;for(;br(r,e);){i+=10;let s=Zi(r,e+6);i+=s,Fo(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)}function bd(r,e,t,i){let s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){let f=new Error(`invalid ADTS sampling index:${a}`);r.emit(p.ERROR,p.ERROR,{type:K.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}let o=(n>>6&3)+1,c=e[t+3]>>6&3|(n&1)<<2,l="mp4a.40."+o,d=s[a],h=a;(o===5||o===29)&&(h-=3);let u=[o<<3|(h&14)>>1,(h&1)<<7|c<<3];return te.log(`manifest codec:${i}, 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:i}}function No(r,e){return r[e]===255&&(r[e+1]&246)===240}function Bo(r,e){return r[e+1]&1?7:9}function Ar(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function Ad(r,e){return e+5<r.length}function Ui(r,e){return e+1<r.length&&No(r,e)}function Ld(r,e){return Ad(r,e)&&No(r,e)&&Ar(r,e)<=r.length-e}function Id(r,e){if(Ui(r,e)){let t=Bo(r,e);if(e+t>=r.length)return!1;let i=Ar(r,e);if(i<=t)return!1;let s=e+i;return s===r.length||Ui(r,s)}return!1}function Uo(r,e,t,i,s){if(!r.samplerate){let n=bd(e,t,i,s);if(!n)return;ie(r,n)}}function $o(r){return 1024*9e4/r}function Rd(r,e){let t=Bo(r,e);if(e+t<=r.length){let i=Ar(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Go(r,e,t,i,s){let n=$o(r.samplerate),a=i+s*n,o=Rd(e,t),c;if(o){let{frameLength:h,headerLength:u}=o,f=u+h,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 y={unit:c,pts:a};return g||r.samples.push(y),{sample:y,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 _d(r,e){return br(r,e)&&Zi(r,e+6)+10<=r.length-e}function Dd(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function Ms(r,e=0,t=1/0){return Pd(r,e,t,Uint8Array)}function Pd(r,e,t,i){let s=Cd(r),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);let a=kd(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 i(s,l,d-l)}function Cd(r){return r instanceof ArrayBuffer?r:r.buffer}function kd(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function wd(r){let e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let i=r.data.subarray(1).indexOf(0);if(i===-1)return;let s=Pe(Ms(r.data,1,i)),n=r.data[2+i],a=r.data.subarray(3+i).indexOf(0);if(a===-1)return;let o=Pe(Ms(r.data,3+i,a)),c;return s==="-->"?c=Pe(Ms(r.data,4+i+a)):c=Dd(r.data.subarray(4+i+a)),e.mimeType=s,e.pictureType=n,e.description=o,e.data=c,e}function Md(r){if(r.size<2)return;let e=Pe(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function Od(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1,i=Pe(r.data.subarray(t),!0);t+=i.length+1;let s=Pe(r.data.subarray(t));return{key:r.type,info:i,data:s}}let e=Pe(r.data.subarray(1));return{key:r.type,info:"",data:e}}function Fd(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1,i=Pe(r.data.subarray(t),!0);t+=i.length+1;let s=Pe(r.data.subarray(t));return{key:r.type,info:i,data:s}}let e=Pe(r.data);return{key:r.type,info:"",data:e}}function Nd(r){return r.type==="PRIV"?Md(r):r.type[0]==="W"?Fd(r):r.type==="APIC"?wd(r):Od(r)}function Bd(r){let e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Zi(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}}var li=10,Ud=10;function Ko(r){let e=0,t=[];for(;br(r,e);){let i=Zi(r,e+6);r[e+5]>>6&1&&(e+=li),e+=li;let s=e+i;for(;e+Ud<s;){let n=Bd(r.subarray(e)),a=Nd(n);a&&t.push(a),e+=n.size+li}Fo(r,e)&&(e+=li)}return t}function Vo(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function $d(r){if(r.data.byteLength===8){let e=new Uint8Array(r.data),t=e[3]&1,i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Lr(r){let e=Ko(r);for(let t=0;t<e.length;t++){let i=e[t];if(Vo(i))return $d(i)}}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 Ke(r="",e=9e4){return{type:r,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,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=we(this.cachedData,e),this.cachedData=null);let i=jt(e,0),s=i?i.length:0,n,a=this._audioTrack,o=this._id3Track,c=i?Lr(i):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&O(c))&&(this.basePTS=Gd(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:De.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){let d=this.appendFrame(a,e,s);d?(this.frameIndex++,this.lastPTS=d.sample.pts,s+=d.length,n=s):s=l}else _d(e,s)?(i=jt(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:De.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===l&&n!==l){let d=e.slice(n);this.cachedData?this.cachedData=we(this.cachedData,d):this.cachedData=d}}return{audioTrack:a,videoTrack:Ke(),id3Track:o,textTrack:Ke()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ke(),id3Track:this._id3Track,textTrack:Ke()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},Gd=(r,e,t)=>{if(O(r))return r*90;let i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},ci=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],Vd=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Hd=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Yd=[0,1,1,4];function Ho(r,e,t,i,s){if(t+24>e.length)return;let n=Yo(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*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 Yo(r,e){let t=r[e+1]>>3&3,i=r[e+1]>>1&3,s=r[e+2]>>4&15,n=r[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&n!==3){let a=r[e+2]>>1&1,o=r[e+3]>>6,c=t===3?3-i:i===3?3:4,l=Kd[c*14+s-1]*1e3,h=Vd[(t===3?0:t===2?1:2)*3+n],u=o===3?1:2,f=Hd[t][i],g=Yd[i],y=f*8*g,m=Math.floor(f*l/h+a)*g;if(ci===null){let T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ci=T?parseInt(T[1]):0}return ci&&ci<=87&&i===2&&l>=224e3&&o===0&&(r[e+3]=r[e+3]|128),{sampleRate:h,channelCount:u,frameLength:m,samplesPerFrame:y}}}function Ir(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function qo(r,e){return e+1<r.length&&Ir(r,e)}function qd(r,e){return Ir(r,e)&&4<=r.length-e}function Wo(r,e){if(e+1<r.length&&Ir(r,e)){let i=Yo(r,e),s=4;i!=null&&i.frameLength&&(s=i.frameLength);let n=e+s;return n===r.length||qo(r,n)}return!1}var pn=class extends Qt{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let i=jt(e,0),s=i?.length||0;if(Wo(e,s))return!1;for(let n=e.length;s<n;s++)if(Id(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Ld(e,t)}appendFrame(e,t,i){Uo(e,this.observer,t,i,e.manifestCodec);let s=Go(e,t,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}},jo=(r,e)=>{let t=0,i=5;e+=i;let s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=r[e];let o=Math.min(i,8),c=8-o;n[0]=4278190080>>>24+c<<c,s[0]=(a[0]&n[0])>>c,t=t?t<<o|s[0]:s[0],e+=1,i-=o}return t},mn=class extends Qt{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let s=Qo(e,t,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;let t=jt(e,0);if(!t)return!1;let i=t.length;return e[i]===11&&e[i+1]===119&&Lr(t)!==void 0&&jo(e,i)<16}};function Qo(r,e,t,i,s){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;let n=e[t+4]>>6;if(n>=3)return-1;let o=[48e3,44100,32e3][n],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 f=(e[t+6]<<8|e[t+7])>>12-u&1,y=[2,1,2,3,3,4,4,5][h]+f,m=e[t+5]>>3,v=e[t+5]&7,E=new Uint8Array([n<<6|m<<1|v>>2,(v&3)<<6|h<<3|f<<2|c>>4,c<<4&224]),T=1536/o*9e4,S=i+s*T,x=e.subarray(t,t+d);return r.config=E,r.channelCount=y,r.samplerate=o,r.samples.push({unit:x,pts:S}),d}var yn=class extends Qt{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=jt(e,0),i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Lr(t)!==void 0&&jo(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(Wo(e,i))return te.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return qd(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Ho(e,t,i,this.basePTS,this.frameIndex)}},Wd=/\/emsg[-/]ID3/i,vn=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,i,s){let n=this.videoTrack=Ke("video",1),a=this.audioTrack=Ke("audio",1),o=this.txtTrack=Ke("text",1);if(this.id3Track=Ke("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let c=oo(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=no.text,n.sampleDuration=0,n.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return ic(e)}demux(e,t){this.timeOffset=t;let i=e,s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=we(this.remainderData,e));let o=cc(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;let a=this.extractID3Track(s,t);return n.samples=jr(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let s=this.extractID3Track(t,this.timeOffset);return i.samples=jr(e,t),{videoTrack:t,audioTrack:Ke(),id3Track:s,textTrack:Ke()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let s=Q(e.samples,["emsg"]);s&&s.forEach(n=>{let a=hc(n);if(Wd.test(a.schemeIdUri)){let o=Pa(a,t),c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);let l=a.payload;i.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=Pa(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:De.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function Pa(r,e){return O(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}var En=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ht(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,st.cbc)}decryptAacSample(e,t,i){let s=e[t].unit;if(s.length<=16)return;let n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let c=new Uint8Array(o);s.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),s=0;for(let n=32;n<e.length-16;n+=160,s+=16)i.set(e.subarray(n,n+16),s);return i}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),s=0;for(let n=32;n<e.length-16;n+=160,s+=16)e.set(i.subarray(s,s+16),n);return e}decryptAvcSample(e,t,i,s,n){let a=ho(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,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}let n=e[t].units;for(;!(i>=n.length);i++){let a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,s,a),!this.decrypter.isSync()))return}}}},$i=class{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){let n=i.units;s=n[n.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,s=i.length;if(s){let n=i[s-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){let s=t.byteLength,n=e.naluState||0,a=n,o=[],c=0,l,d,h,u=-1,f=0;for(n===-1&&(u=0,f=this.getNALuType(t,0),n=0,c=1);c<s;){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 g={data:t.subarray(u,d),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)),d>0&&(g.data=we(g.data,t.subarray(0,d)),g.state=0))}c<s?(h=this.getNALuType(t,c),u=c,f=h,n=0):n=-1}else n=0}if(u>=0&&n>=0){let g={data:t.subarray(u,s),type:f,state:n};o.push(g)}if(o.length===0){let g=this.getLastNalUnit(e.samples);g&&(g.data=we(g.data,t))}return e.naluState=n,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,i=e.byteLength-t,s=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");s.set(e.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&te.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==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)}},Tn=class extends $i{parsePES(e,t,i,s){let n=this.parseNALu(e,i.data,s),a=this.VideoSample,o,c=!1;i.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.forEach(l=>{var d,h;switch(l.type){case 1:{let y=!1;o=!0;let m=l.data;if(c&&m.length>4){let v=this.readSliceType(m);(v===2||v===4||v===7||v===9)&&(y=!0)}if(y){var u;(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=y;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,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,mr(l.data,1,i.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;let y=l.data,m=this.readSPS(y);if(!e.sps||e.width!==m.width||e.height!==m.height||((f=e.pixelRatio)==null?void 0:f[0])!==m.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[y];let v=y.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,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),s&&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 i=8,s=8,n;for(let a=0;a<e;a++)s!==0&&(n=t.readEG(),s=(i+n+256)%256),i=s===0?i:s}readSPS(e){let t=new ut(e),i=0,s=0,n=0,a=0,o,c,l,d=t.readUByte.bind(t),h=t.readBits.bind(t),u=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),y=t.skipEG.bind(t),m=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);d();let E=d();if(h(5),g(3),d(),m(),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),m(),m(),g(1),f())for(c=R!==3?8:12,l=0;l<c;l++)f()&&(l<6?v(16,t):v(64,t))}m();let T=u();if(T===0)u();else if(T===1)for(g(1),y(),y(),o=u(),l=0;l<o;l++)y();m(),g(1);let S=u(),x=u(),_=h(1);_===0&&g(1),g(1),f()&&(i=u(),s=u(),n=u(),a=u());let b=[1,1];if(f()&&f())switch(d()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:{b=[d()<<8|d(),d()<<8|d()];break}}return{width:Math.ceil((S+1)*16-i*2-s*2),height:(2-_)*(x+1)*16-(_?2:4)*(n+a),pixelRatio:b}}},Sn=class extends $i{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){let n=this.parseNALu(e,i.data,s),a=this.VideoSample,o,c=!1;i.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.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,i.pts,i.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,i.pts,i.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,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,mr(l.data,2,i.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,i.pts,i.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,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:o=!1;break}a&&o&&a.units.push(l)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let s=0;s<e.byteLength;s++)s>=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new ut(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let i=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(e){let t=new ut(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let s=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),d=t.readUByte(),h=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),y=t.readUByte(),m=t.readUByte(),v=t.readUByte(),E=[],T=[];for(let Z=0;Z<i;Z++)E.push(t.readBoolean()),T.push(t.readBoolean());if(i>0)for(let Z=i;Z<8;Z++)t.readBits(2);for(let Z=0;Z<i;Z++)E[Z]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[Z]&&t.readUByte();t.readUEG();let S=t.readUEG();S==3&&t.skipBits(1);let x=t.readUEG(),_=t.readUEG(),b=t.readBoolean(),R=0,I=0,A=0,P=0;b&&(R+=t.readUEG(),I+=t.readUEG(),A+=t.readUEG(),P+=t.readUEG());let M=t.readUEG(),B=t.readUEG(),V=t.readUEG(),U=t.readBoolean();for(let Z=U?0:i;Z<=i;Z++)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 ve=0;ve<4;ve++)for(let ke=0;ke<(ve===3?2:6);ke++)if(!t.readBoolean())t.readUEG();else{let Me=Math.min(64,1<<4+(ve<<1));ve>1&&t.readEG();for(let pt=0;pt<Me;pt++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let F=t.readUEG(),G=0;for(let Z=0;Z<F;Z++){let ve=!1;if(Z!==0&&(ve=t.readBoolean()),ve){Z===F&&t.readUEG(),t.readBoolean(),t.readUEG();let ke=0;for(let rt=0;rt<=G;rt++){let Me=t.readBoolean(),pt=!1;Me||(pt=t.readBoolean()),(Me||pt)&&ke++}G=ke}else{let ke=t.readUEG(),rt=t.readUEG();G=ke+rt;for(let Me=0;Me<ke;Me++)t.readUEG(),t.readBoolean();for(let Me=0;Me<rt;Me++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let Z=t.readUEG();for(let ve=0;ve<Z;ve++){for(let ke=0;ke<V+4;ke++)t.readBits(1);t.readBits(1)}}let k=0,w=1,W=1,J=!0,j=1,X=0;t.readBoolean(),t.readBoolean();let ye=!1;if(t.readBoolean()){if(t.readBoolean()){let at=t.readUByte(),Or=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],ei=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];at>0&&at<16?(w=Or[at-1],W=ei[at-1]):at===255&&(w=t.readBits(16),W=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(),ye=t.readBoolean(),ye&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(j=t.readBits(32),X=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let ei=t.readBoolean(),Fr=t.readBoolean(),wt=!1;(ei||Fr)&&(wt=t.readBoolean(),wt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),wt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Nr=0;Nr<=i;Nr++){J=t.readBoolean();let kl=J||t.readBoolean(),Br=!1;kl?t.readEG():Br=t.readBoolean();let Ur=Br?1:t.readUEG()+1;if(ei)for(let Mt=0;Mt<Ur;Mt++)t.readUEG(),t.readUEG(),wt&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Fr)for(let Mt=0;Mt<Ur;Mt++)t.readUEG(),t.readUEG(),wt&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),k=t.readUEG())}let Ce=x,Be=_;if(b){let Z=1,ve=1;S===1?Z=ve=2:S==2&&(Z=2),Ce=x-Z*I-Z*R,Be=_-ve*P-ve*A}let nt=s?["A","B","C"][s]:"",Cl=o<<24|c<<16|l<<8|d,Ss=0;for(let Z=0;Z<32;Z++)Ss=(Ss|(Cl>>Z&1)<<31-Z)>>>0;let xs=Ss.toString(16);return a===1&&xs==="2"&&(xs="6"),{codecString:`hvc1.${nt}${a}.${xs}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:s,general_profile_compatibility_flags:[o,c,l,d],general_constraint_indicator_flags:[h,u,f,g,y,m],general_level_idc:v,bit_depth:M+8,bit_depth_luma_minus8:M,bit_depth_chroma_minus8:B,min_spatial_segmentation_idc:k,chroma_format_idc:S,frame_rate:{fixed:J,fps:X/j}},width:Ce,height:Be,pixelRatio:[w,W]}}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 s=t.readBoolean(),n=t.readBoolean(),a=1;return n&&s?a=0:n?a=3:s&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},ue=188,xn=class r{constructor(e,t,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){let i=r.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){let t=e.length,i=Math.min(ue*5,t-ue)+1,s=0;for(;s<i;){let n=!1,a=-1,o=0;for(let c=s;c<t;c+=ue)if(e[c]===71&&(t-c===ue||e[c+ue]===71)){if(o++,a===-1&&(a=c,a!==0&&(i=Math.min(a+ue*99,e.length-ue)+1)),n||(n=bn(e,c)===0),n&&o>1&&(a===0&&o>2||c+ue>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:no[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=r.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=r.createTrack("audio",s),this._id3Track=r.createTrack("id3"),this._txtTrack=r.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,s=!1){i||(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,f=c.pid,g=o.pesData,y=c.pesData,m=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<ue&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};let S=Math.max(0,r.syncOffset(e));T-=(T-S)%ue,T<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let x=0;for(let b=S;b<T;b+=ue)if(e[b]===71){let R=!!(e[b+1]&64),I=bn(e,b),A=(e[b+3]&48)>>4,P;if(A>1){if(P=b+5+e[b+4],P===b+ue)continue}else P=b+4;switch(I){case d:R&&(h&&(n=St(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(P,b+ue)),h.size+=b+ue-P);break;case u:if(R){if(g&&(n=St(g,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}g={data:[],size:0}}g&&(g.data.push(e.subarray(P,b+ue)),g.size+=b+ue-P);break;case f:R&&(y&&(n=St(y,this.logger))&&this.parseID3PES(c,n),y={data:[],size:0}),y&&(y.data.push(e.subarray(P,b+ue)),y.size+=b+ue-P);break;case 0:R&&(P+=e[P]+1),E=this._pmtId=jd(e,P);break;case E:{R&&(P+=e[P]+1);let M=Qd(e,P,this.typeSupported,i,this.observer,this.logger);d=M.videoPid,d>0&&(a.pid=d,a.segmentCodec=M.segmentVideoCodec),u=M.audioPid,u>0&&(o.pid=u,o.segmentCodec=M.segmentAudioCodec),f=M.id3Pid,f>0&&(c.pid=f),m!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${b} after unknown PID '${m}'. Backtracking to sync byte @${S} to parse all TS packets.`),m=null,b=S-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=I;break}}else x++;x>0&&An(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,o.pesData=g,c.pesData=y;let _={audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};return s&&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:i,id3Track:s,textTrack:n}=e,a=i.pesData,o=t.pesData,c=s.pesData,l;if(a&&(l=St(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,n,l,!0),i.pesData=null)):i.pesData=a,o&&(l=St(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=St(c,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=c}demuxSampleAes(e,t,i){let s=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new En(this.observer,this.config,t);return this.decrypt(s,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Tn:e==="hevc"&&(this.videoParser=new Sn))}decrypt(e,t){return new Promise(i=>{let{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0,s=this.aacOverFlow,n=t.data;if(s){this.aacOverFlow=null;let h=s.missing,u=s.sample.unit.byteLength;if(h===-1)n=we(s.sample.unit,n);else{let f=u-h;s.sample.unit.set(n.subarray(0,h),f),e.samples.push(s.sample),i=s.missing}}let a,o;for(a=i,o=n.length;a<o-1&&!Ui(n,a);a++);if(a!==i){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",An(this.observer,new Error(h),u,this.logger),!u)return}Uo(e,this.observer,n,a,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(s){let h=$o(e.samplerate);c=s.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,d;for(;a<o;)if(d=Go(e,n,a,c,l),a+=d.length,d.missing){this.aacOverFlow=d;break}else for(l++;a<o-1&&!Ui(n,a);a++);}parseMPEGPES(e,t){let i=t.data,s=i.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(qo(i,a)){let c=Ho(e,i,a,o,n);if(c)a+=c.length,n++;else break}else a++}parseAC3PES(e,t){{let i=t.data,s=t.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=i.length,a=0,o=0,c;for(;o<n&&(c=Qo(e,i,o,s,a++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=ie({},t,{type:this._videoTrack?De.emsg:De.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}};function bn(r,e){return((r[e+1]&31)<<8)+r[e+2]}function jd(r,e){return(r[e+10]&31)<<8|r[e+11]}function Qd(r,e,t,i,s,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=bn(r,e),h=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!i){Os("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(!i){Os("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(!i){Os("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,f=h;for(;f>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 y=r[u+1]+2;u+=y,f-=y}}break;case 194:case 135:return An(s,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 An(r,e,t,i){i.warn(`parsing error: ${e.message}`),r.emit(p.ERROR,p.ERROR,{type:K.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Os(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function St(r,e){let t=0,i,s,n,a,o,c=r.data;if(!r||r.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=we(c[0],c[1]),c.splice(1,1);if(i=c[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(s=(i[4]<<8)+i[5],s&&s>r.size-6)return null;let d=i[7];d&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,d&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=i[8];let h=n+9;if(r.size<=h)return null;r.size-=h;let u=new Uint8Array(r.size);for(let f=0,g=c.length;f<g;f++){i=c[f];let y=i.byteLength;if(h)if(h>y){h-=y;continue}else i=i.subarray(h),y-=h,h=0;u.set(i,t),t+=y}return s&&(s-=n+3),{data:u,pts:a,dts:o,len:s}}return null}var Ln=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,he=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]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);r.HDLR_TYPES={video:t,audio:i};let s=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,s))}static box(e,...t){let i=8,s=t.length,n=s;for(;s--;)i+=t[s].byteLength;let a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),s=0,i=8;s<n;s++)a.set(t[s],i),i+=t[s].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 i=Math.floor(t/(Ze+1)),s=Math.floor(t%(Ze+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,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return r.box(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,i){return r.box(r.types.moof,r.mfhd(e),r.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=r.trak(e[t]);return r.box.apply(null,[r.types.moov,r.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(r.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=r.trex(e[t]);return r.box.apply(null,[r.types.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(Ze+1)),s=Math.floor(t%(Ze+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return r.box(r.types.mvhd,n)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),s,n;for(s=0;s<t.length;s++)n=t[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return r.box(r.types.sdtp,i)}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=[],i=[],s,n,a;for(s=0;s<e.sps.length;s++)n=e.sps[s],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(s=0;s<e.pps.length;s++)n=e.pps[s],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));let o=r.box(r.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),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,i=(e.duration||0)*(e.timescale||0),s=e.width||0,n=e.height||0,a=Math.floor(i/(Ze+1)),o=Math.floor(i%(Ze+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,s>>8&255,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let i=r.sdtp(e),s=e.id,n=Math.floor(t/(Ze+1)),a=Math.floor(t%(Ze+1));return r.box(r.types.traf,r.box(r.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&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,i.length+16+20+8+16+8+8),i)}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 i=e.samples||[],s=i.length,n=12+16*s,a=new Uint8Array(n),o,c,l,d,h,u;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)c=i[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 we(r.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],s=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),s-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]),a=n.length;for(let g=0;g<i.length;g+=1){a+=3;for(let y=0;y<i[g].length;y+=1)a+=2+i[g][y].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let c=i.length-1;for(let g=0;g<i.length;g+=1){o.set(new Uint8Array([32+g|(g===c?128:0),0,i[g].length]),a),a+=3;for(let y=0;y<i[g].length;y+=1)o.set(new Uint8Array([i[g][y].length>>8,i[g][y].length&255]),a),a+=2,o.set(i[g][y],a),a+=i[g][y].length}let l=r.box(r.types.hvcC,o),d=e.width,h=e.height,u=e.pixelRatio[0],f=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,f>>24,f>>16&255,f>>8&255,f&255])))}};he.types=void 0;he.HDLR_TYPES=void 0;he.STTS=void 0;he.STSC=void 0;he.STCO=void 0;he.STSZ=void 0;he.VMHD=void 0;he.SMHD=void 0;he.STSD=void 0;he.FTYP=void 0;he.DINF=void 0;var zo=9e4;function Rr(r,e,t=1,i=!1){let s=r*e*t;return i?Math.round(s):s}function zd(r,e,t=1,i=!1){return Rr(r,e,1/t,i)}function Ot(r,e=!1){return Rr(r,1e3,1/zo,e)}function Xd(r,e=1){return Rr(r,zo,1/e)}function Ca(r){let{baseTime:e,timescale:t,trackId:i}=r;return`${e/t} (${e}/${t}) trackId: ${i}`}var Zd=10*1e3,Jd=1024,eh=1152,th=1536,xt=null,Fs=null;function ka(r,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}var _t=class extends Le{constructor(e,t,i,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,xt===null){let a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);xt=a?parseInt(a[1]):0}if(Fs===null){let n=navigator.userAgent.match(/Safari\/(\d+)/i);Fs=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&&Ca(t)} > ${e&&Ca(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e[0].pts,s=e.reduce((n,a)=>{let o=a.pts,c=o-n;return c<-4294967296&&(t=!0,o=_e(o,i),c=o-n),c>0?n:o},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,n,a,o,c){let l,d,h,u,f,g,y=n,m=n,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 b,R,I,A;let V=this.videoTrackConfig;(V&&(t.width!==V.width||t.height!==V.height||((b=t.pixelRatio)==null?void 0:b[0])!==((R=V.pixelRatio)==null?void 0:R[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((A=V.pixelRatio)==null?void 0:A[1]))||!V&&x||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));let P=this.isVideoContiguous,M=-1,B;if(x&&(M=ih(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,m+=(t.samples[0].pts-V)/t.inputTimeScale,B=m}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),C=(_e(e.samples[0].pts,V)-V)/t.inputTimeScale;y+=Math.max(0,C),m+=Math.max(0,-C)}if(S){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),d=this.remuxAudio(e,y,this.isAudioContiguous,a,E||x||c===N.AUDIO?m:void 0),x){let V=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,m,P,V)}}else x&&(l=this.remuxVideo(t,m,P,0));l&&(l.firstKeyFrame=M,l.independent=M!==-1,l.firstKeyFramePTS=B)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Xo(i,n,this._initPTS,this._initDTS)),s.samples.length&&(u=Zo(s,n,this._initPTS))),{audio:d,video:l,initSegment:h,independent:g,text:u,id3:f}}computeInitPts(e,t,i,s){let n=Math.round(i*t),a=_e(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${s}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,i,s){let n=e.samples,a=t.samples,o=this.typeSupported,c={},l=this._initPTS,d=!l||s,h="audio/mp4",u,f,g,y=-1;if(d&&(u=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):he.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(y=e.id,g=e.inputTimeScale,!l||g!==l.timescale?u=f=this.computeInitPts(n[0].pts,g,i,"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:he.initSegment([t]),metadata:{width:t.width,height:t.height}},d)if(y=t.id,g=t.inputTimeScale,!l||g!==l.timescale){let m=this.getVideoStartPts(a),v=_e(a[0].dts,m),E=this.computeInitPts(v,g,i,"video"),T=this.computeInitPts(m,g,i,"video");f=Math.min(f,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: ${s?"":"~"}${i} ${u/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${u/g} (${u}/${g}) trackId: ${y}`),this._initPTS={baseTime:u,timescale:g,trackId:y},this._initDTS={baseTime:f,timescale:g,trackId:y}):u=g=void 0,{tracks:c,initPTS:u,timescale:g,trackId:y}}remuxVideo(e,t,i,s){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,f=this.videoSampleDuration,g,y,m=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,E=!1;if(!i||h===null){let k=d+t*n,w=a[0].pts-_e(a[0].dts,a[0].pts);xt&&h!==null&&Math.abs(k-w-(h+d))<15e3?i=!0:h=k-w-d}let T=h+d;for(let k=0;k<c;k++){let w=a[k];w.pts=_e(w.pts,T),w.dts=_e(w.dts,T),w.dts<a[k>0?k-1:k].dts&&(E=!0)}E&&a.sort(function(k,w){let W=k.dts-w.dts,J=k.pts-w.pts;return W||J}),g=a[0].dts,y=a[a.length-1].dts;let S=y-g,x=S?Math.round(S/(c-1)):f||e.inputTimeScale/30;if(i){let k=g-T,w=k>x,W=k<-1;if((w||W)&&(w?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ot(k,!0)} ms (${k}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ot(-k,!0)} ms (${k}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!W||T>=a[0].pts||xt)){g=T;let J=a[0].pts-k;if(w)a[0].dts=g,a[0].pts=J;else{let j=!0;for(let X=0;X<a.length&&!(a[X].dts>J&&j);X++){let ye=a[X].pts;if(a[X].dts-=k,a[X].pts-=k,X<a.length-1){let ge=a[X+1].pts,Ce=a[X].pts,Be=ge<=Ce,nt=ge<=ye;j=Be==nt}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ot(J,!0)}/${Ot(g,!0)}, delta: ${Ot(k,!0)} ms`)}}g=Math.max(0,g);let _=0,b=0,R=g;for(let k=0;k<c;k++){let w=a[k],W=w.units,J=W.length,j=0;for(let X=0;X<J;X++)j+=W[X].data.length;b+=j,_+=J,w.length=j,w.dts<R?(w.dts=R,R+=x/4|0||1):R=w.dts,m=Math.min(w.pts,m),v=Math.max(w.pts,v)}y=a[c-1].dts;let I=b+4*_+8,A;try{A=new Uint8Array(I)}catch(k){this.observer.emit(p.ERROR,p.ERROR,{type:K.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:k,bytes:I,reason:`fail allocating video mdat ${I}`});return}let P=new DataView(A.buffer);P.setUint32(0,I),A.set(he.types.mdat,4);let M=!1,B=Number.POSITIVE_INFINITY,V=Number.POSITIVE_INFINITY,U=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let k=0;k<c;k++){let w=a[k],W=w.units,J=0;for(let ye=0,ge=W.length;ye<ge;ye++){let Ce=W[ye],Be=Ce.data,nt=Ce.data.byteLength;P.setUint32(u,nt),u+=4,A.set(Be,u),u+=nt,J+=4+nt}let j;if(k<c-1)f=a[k+1].dts-w.dts,j=a[k+1].pts-w.pts;else{let ye=this.config,ge=k>0?w.dts-a[k-1].dts:x;if(j=k>0?w.pts-a[k-1].pts:x,ye.stretchShortVideoTrack&&this.nextAudioTs!==null){let Ce=Math.floor(ye.maxBufferHole*n),Be=(s?m+s*n:this.nextAudioTs+d)-w.pts;Be>Ce?(f=Be-ge,f<0?f=ge:M=!0,this.log(`It is approximately ${Be/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=ge}else f=ge}let X=Math.round(w.pts-w.dts);B=Math.min(B,f),U=Math.max(U,f),V=Math.min(V,j),C=Math.max(C,j),o.push(ka(w.key,f,J,X))}if(o.length){if(xt){if(xt<70){let k=o[0].flags;k.dependsOn=2,k.isNonSync=0}}else if(Fs&&C-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 k=g;for(let w=0,W=o.length;w<W;w++){let J=k+o[w].duration,j=k+o[w].cts;if(w<W-1){let X=J+o[w+1].cts;o[w].duration=X-j}else o[w].duration=w?o[w-1].duration:x;o[w].cts=0,k=J}}}f=M||!f?x:f;let $=y+f;this.nextVideoTs=h=$-d,this.videoSampleDuration=f,this.isVideoContiguous=!0;let H={data1:he.moof(e.sequenceNumber++,g,ie(e,{samples:o})),data2:A,startPTS:(m-d)/n,endPTS:(v+f-d)/n,startDTS:(g-d)/n,endDTS:h/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,H}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return eh;case"ac3":return th;default:return Jd}}remuxAudio(e,t,i,s,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,f=[],g=n!==void 0,y=e.samples,m=u?0:8,v=this.nextAudioTs||-1,E=h.baseTime*a/h.timescale,T=E+t*a;if(this.isAudioContiguous=i=i||y.length&&v>0&&(s&&Math.abs(T-(v+E))<9e3||Math.abs(_e(y[0].pts,T)-(v+E))<20*d),y.forEach(function(C){C.pts=_e(C.pts,T)}),!i||v<0){let C=y.length;if(y=y.filter($=>$.pts>=0),C!==y.length&&this.warn(`Removed ${y.length-C} of ${C} samples (initPTS ${E} / ${a})`),!y.length)return;n===0?v=0:s&&!g?v=Math.max(0,T-E):v=y[0].pts-E}if(e.segmentCodec==="aac"){let C=this.config.maxAudioFramesDrift;for(let $=0,F=v+E;$<y.length;$++){let G=y[$],H=G.pts,k=H-F,w=Math.abs(1e3*k/a);if(k<=-C*d&&g)$===0&&(this.warn(`Audio frame @ ${(H/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*k/a)} ms.`),this.nextAudioTs=v=H-E,F=H);else if(k>=C*d&&w<Zd&&g){let W=Math.round(k/d);for(F=H-W*d;F<0&&W&&d;)W--,F+=d;$===0&&(this.nextAudioTs=v=F-E),this.warn(`Injecting ${W} audio frames @ ${((F-E)/a).toFixed(3)}s due to ${Math.round(1e3*k/a)} ms gap.`);for(let J=0;J<W;J++){let j=Ln.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);j||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),j=G.unit.subarray()),y.splice($,0,{unit:j,pts:F}),F+=d,$++}}G.pts=F,F+=d}}let S=null,x=null,_,b=0,R=y.length;for(;R--;)b+=y[R].unit.byteLength;for(let C=0,$=y.length;C<$;C++){let F=y[C],G=F.unit,H=F.pts;if(x!==null){let w=f[C-1];w.duration=Math.round((H-x)/c)}else if(i&&e.segmentCodec==="aac"&&(H=v+E),S=H,b>0){b+=m;try{_=new Uint8Array(b)}catch(w){this.observer.emit(p.ERROR,p.ERROR,{type:K.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:b,reason:`fail allocating audio mdat ${b}`});return}u||(new DataView(_.buffer).setUint32(0,b),_.set(he.types.mdat,4))}else return;_.set(G,m);let k=G.byteLength;m+=k,f.push(ka(!0,l,k,0)),x=H}let I=f.length;if(!I)return;let A=f[f.length-1];v=x-E,this.nextAudioTs=v+c*A.duration;let P=u?new Uint8Array(0):he.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:I};return this.isAudioContiguous=!0,U}};function _e(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 ih(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function Xo(r,e,t,i){let s=r.samples.length;if(!s)return;let n=r.inputTimeScale;for(let o=0;o<s;o++){let c=r.samples[o];c.pts=_e(c.pts-t.baseTime*n/t.timescale,e*n)/n,c.dts=_e(c.dts-i.baseTime*n/i.timescale,e*n)/n}let a=r.samples;return r.samples=[],{samples:a}}function Zo(r,e,t){let i=r.samples.length;if(!i)return;let s=r.inputTimeScale;for(let a=0;a<i;a++){let o=r.samples[a];o.pts=_e(o.pts-t.baseTime*s/t.timescale,e*s)/s}r.samples.sort((a,o)=>a.pts-o.pts);let n=r.samples;return r.samples=[],{samples:n}}var In=class extends Le{constructor(e,t,i,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:a}=this.initData=oo(e);if(t)ac(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&&(i=wa(n,se.AUDIO,this)),a&&(s=wa(a,se.VIDEO,this));let o={};n&&a?o.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:s,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,i,s,n,a){var o,c;let{initPTS:l,lastEndTime:d}=this,h={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};O(d)||(d=this.lastEndTime=n||0);let u=t.samples;if(!u.length)return h;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."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);let y=lc(u,g,this),m=g.audio?y[g.audio.id]:null,v=g.video?y[g.video.id]:null,E=di(v,1/0),T=di(m,1/0),S=di(v,0,!0),x=di(m,0,!0),_=n,b=0,R=m&&(!v||!l&&T<E||l&&l.trackId===g.audio.id),I=R?m:v;if(I){let F=I.timescale,G=I.start-n*F,H=R?g.audio.id:g.video.id;_=I.start/F,b=R?x-T:S-E,(a||!l)&&(sh(l,_,n,b)||F!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${G/F} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${_-n} (${G}/${F}) trackId: ${H}`),l=null,f.initPTS=G,f.timescale=F,f.trackId=H)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);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 A=_-l.baseTime/l.timescale,P=A+b;b>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),C={data1:u,startPTS:A,startDTS:A,endPTS:P,endDTS:P,type:V,hasAudio:M,hasVideo:B,nb:1,dropped:0,encrypted:U};h.audio=M&&!B?C:void 0,h.video=B?C:void 0;let $=v?.sampleCount;if($){let F=v.keyFrameIndex,G=F!==-1;C.nb=$,C.dropped=F===0||this.isVideoContiguous?0:G?F:$,C.independent=G,C.firstKeyFrame=F,G&&v.keyFrameStart&&(C.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=G),this.isVideoContiguous||(this.isVideoContiguous=G),C.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${F}/${$} dropped: ${C.dropped} start: ${C.firstKeyFramePTS||"NA"}`)}return h.initSegment=f,h.id3=Xo(i,n,l,l),s.samples.length&&(h.text=Zo(s,n,l)),h}};function di(r,e,t=!1){return r?.start!==void 0?(r.start+(t?r.duration:0))/r.timescale:e}function sh(r,e,t,i){if(r===null)return!0;let s=Math.max(i,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>s}function wa(r,e,t){let i=r.codec;return i&&i.length>4?i:e===se.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Ri(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}var We;try{We=self.performance.now.bind(self.performance)}catch{We=Date.now}var Si=[{demux:vn,remux:In},{demux:xn,remux:_t},{demux:pn,remux:_t},{demux:yn,remux:_t}];Si.splice(2,0,{demux:mn,remux:_t});var Gi=class{constructor(e,t,i,s,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){let n=i.transmuxing;n.executeStart=We();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:c}=this;s&&(this.currentTransmuxState=s);let{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=s||o,{audioCodec:y,videoCodec:m,defaultInitPts:v,duration:E,initSegmentData:T}=c,S=nh(a,t);if(S&&Rt(S.method)){let R=this.getDecrypter(),I=Tr(S.method);if(R.isSync()){let A=R.softwareDecrypt(a,S.key.buffer,S.iv.buffer,I);if(i.part>-1){let M=R.flush();A=M&&M.buffer}if(!A)return n.executeEnd=We(),Ns(i);a=new Uint8Array(A)}else return this.asyncResult=!0,this.decryptionPromise=R.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer,I).then(A=>{let P=this.push(A,null,i);return this.decryptionPromise=null,P}),this.decryptionPromise}let x=this.needsProbing(d,h);if(x){let R=this.configureTransmuxer(a);if(R)return this.logger.warn(`[transmuxer] ${R.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:K.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),n.executeEnd=We(),Ns(i)}(d||h||g||x)&&this.resetInitSegment(T,y,m,E,t),(d||g||x)&&this.resetInitialTimestamp(v),l||this.resetContiguity();let _=this.transmux(a,S,f,u,i);this.asyncResult=zt(_);let b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,n.executeEnd=We(),_}flush(e){let t=e.transmuxing;t.executeStart=We();let{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=s;if(i){let h=i.flush();h&&a.push(this.push(h.buffer,null,e))}let{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=We();let h=[Ns(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,i){let{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===N.MAIN?"level":"track"} ${i.level}`);let d=this.remuxer.remux(s,n,a,o,l,c,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=We()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,n){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,s),o.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,s,n):a=this.transmuxUnencrypted(e,i,s,n),a}transmuxUnencrypted(e,t,i,s){let{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,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:s}=this,n;for(let h=0,u=Si.length;h<u;h++){var a;if((a=Si[h].demux)!=null&&a.probe(e,this.logger)){n=Si[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(i,t,s,this.logger)),(!o||!(o instanceof d))&&(this.demuxer=new d(i,t,s,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 Ht(this.config)),e}};function nh(r,e){let t=null;return r.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var Ns=r=>({remuxResult:{},chunkMeta:r});function zt(r){return"then"in r&&r.then instanceof Function}var Rn=class{constructor(e,t,i,s,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=n||null}},_n=class{constructor(e,t,i,s,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=n,this.initSegmentChange=a}},Ma=0,Ki=class{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ma++,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(p.ERROR,{type:K.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;let a=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===p.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new xr,this.observer.on(p.FRAG_DECRYPTED,a),this.observer.on(p.ERROR,a);let o=Xr(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let c=this.hls.logger;if(n.workerPath||Ed()){try{n.workerPath?(c.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Sd(n.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=Td());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:ne(n)})}catch(d){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.terminateWorker(),this.error=null,this.transmuxer=new Gi(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Gi(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Ma++;let t=this.hls.config,i=Xr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,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),xd(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,n,a,o,c,l,d){var h,u;l.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:g}=this,y=a?a.start:n.start,m=n.decryptdata,v=this.frag,E=!(v&&n.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,b=!T&&(S===1||S===0&&(x===1||_&&x<=0)),R=self.performance.now();(T||S||n.stats.parsing.start===0)&&(n.stats.parsing.start=R),a&&(x||!b)&&(a.stats.parsing.start=R);let I=!(v&&((h=n.initSegment)==null?void 0:h.url)===((u=v.initSegment)==null?void 0:u.url)),A=new _n(E,b,c,T,y,I);if(!b||E||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===N.MAIN?"level":"track"}: ${l.level} id: ${l.id}
|
|
17
|
+
discontinuity: ${E}
|
|
18
|
+
trackSwitch: ${T}
|
|
19
|
+
contiguous: ${b}
|
|
20
|
+
accurateTimeOffset: ${c}
|
|
21
|
+
timeOffset: ${y}
|
|
22
|
+
initSegmentChange: ${I}`);let P=new Rn(i,s,t,o,d);this.configureTransmuxer(P)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:A},e instanceof ArrayBuffer?[e]:[]);else if(g){let P=g.push(e,m,l,A);zt(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:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let s=i.flush(e);zt(s)?s.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Oa=100,Dn=class extends qt{constructor(e,t,i){super(e,t,i,"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(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n,trackId:a}){if(i===N.MAIN){let o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:s,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${s/n} (${s}/${n}) 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 i;let s=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&s?.cc===t.cc)return;let n=(s||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),c=Eo(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===D.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=D.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Oa),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,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,i=e?.[t],s=i?.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))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:i,cache:s,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=D.FRAG_LOADING;let o=s.flush().buffer,c={frag:t,part:i,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=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:i,media:s,trackId:n}=this,a=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[n]))return;let o=i[n],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,se.AUDIO,N.AUDIO));let d=this.getFwdBufferInfo(l,N.AUDIO);if(d===null)return;if(!this.switchingTrack&&this._streamEnded(d,c)){t.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=D.ENDED;return}let h=d.len,u=t.maxBufferLength,f=c.fragments,g=f[0].start,y=this.getLoadPosition(),m=this.flushing?y:d.end;if(this.switchingTrack&&s){let T=y;c.PTSKnown&&T<g&&(d.end>g||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=g+.05)}if(h>=u&&!this.switchingTrack&&m<f[f.length-1].start)return;let v=this.getNextFragment(m,c);if(v&&this.isLoopLoading(v,m)&&(v=this.getNextFragmentLoopLoading(v,c,d,N.MAIN,u)),!v){this.bufferFlushed=!0;return}let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&le(v)&&!v.endList&&(!c.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===de.OK&&(this.mainFragLoading=E=null),E&&le(E))){if(v.start>E.end){let S=this.fragmentTracker.getFragAtPos(m,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,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new ft(i))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==D.STOPPED&&(this.setInterval(Oa),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 i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(p.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;let{levels:s}=this,{details:n,id:a,groupId:o,track:c}=t;if(!s){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!==D.STOPPED&&(this.state=D.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=s[a],h=0;if(n.live||(i=d.details)!=null&&i.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||(Oo(n,l),n.alignedSliding||Ni(n,l),h=n.fragmentStart)}d.details=n,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger(p.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===D.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=D.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:s,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 ${i.sn} of level ${i.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(i.start);return}let h=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new Ki(this.hls,N.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){let m=s?s.index:-1,v=m!==-1,E=new Yt(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,v);u.push(n,g,h,"",i,s,d.totalduration,!1,E,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${o}`);let{cache:y}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Bi,complete:!1};y.push(new Uint8Array(n)),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 i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===N.MAIN&&le(t.frag)&&(this.mainFragLoading=t,this.state===D.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:i,part:s}=t;if(i.type!==N.AUDIO){!this.audioOnly&&i.type===N.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(le(i)){this.fragPrevious=i;let n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,ee({},n)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=D.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(N.AUDIO,t);break;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===D.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===z.AUDIO_TRACK&&(this.state=D.IDLE);break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==se.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==se.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===D.ENDED&&(this.state=D.IDLE);let i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,N.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:c,part:l,level:d}=o,{details:h}=d,{audio:u,text:f,id3:g,initSegment:y}=n;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=D.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),y!=null&&y.tracks){let m=c.initSegment||c;if(this.unhandledEncryptionError(y,c))return;this._bufferInitSegment(d,y.tracks,m,a),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:i,tracks:y.tracks})}if(u){let{startPTS:m,endPTS:v,startDTS:E,endDTS:T}=u;l&&(l.elementaryStreams[se.AUDIO]={startPTS:m,endPTS:v,startDTS:E,endDTS:T}),c.setElementaryStreamInfo(se.AUDIO,m,v,E,T),this.bufferFragmentData(u,c,l,a)}if(g!=null&&(t=g.samples)!=null&&t.length){let m=ie({id:i,frag:c,details:h},g);s.trigger(p.FRAG_PARSING_METADATA,m)}if(f){let m=ie({id:i,frag:c,details:h},f);s.trigger(p.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,t,i,s){if(this.state!==D.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=N.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(p.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let c={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(p.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===de.NOT_LOADED||s===de.PARTIAL){var n;if(!le(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=D.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Ni(t.details,a)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;ht({name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o},e,ct)||(Pi(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(p.AUDIO_TRACK_SWITCHED,ee({},e))}},Xt=class extends Le{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,i){let s=t?.renditionReports;if(s){let n=-1;for(let a=0;a<s.length;a++){let o=s[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=s[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=i&&Zr(i);return new Di(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(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){let{details:s,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;s.advancedDateTime=Date.now()-o;let c=this.hls.config.timelineOffset;if(c!==s.appliedTimelineOffset){let d=Math.max(c||0,0);s.appliedTimelineOffset=d,s.fragments.forEach(h=>{h.setStart(h.playlistOffset+d)})}if(s.live||i!=null&&i.live){let d="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){ld(i,s,this);let E=s.playlistParsingError;if(E){this.warn(E);let T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var l;let{networkDetails:S}=t;T.trigger(p.ERROR,{type:K.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:E,reason:E.message,level:t.level||void 0,parent:(l=s.fragments[0])==null?void 0:l.type,networkDetails:S,stats:n});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=n.loading.start);let h=this.hls.mainForwardBufferInfo,u=h?h.end-h.len:0,f=(s.edge-u)*1e3,g=Po(s,f);if(s.requestScheduled+g<a?s.requestScheduled=a:s.requestScheduled+=g,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let y,m,v;if(s.canBlockReload&&s.endSN&&s.advanced){let E=this.hls.config.lowLatencyMode,T=s.lastPartSn,S=s.endSN,x=s.lastPartIndex,_=x!==-1,b=T===S;_?b?(m=S+1,v=E?0:x):(m=T,v=E?x+1:s.maxPartIndex):m=S+1;let R=s.age,I=R+s.ageHeader,A=Math.min(I-s.partTarget,s.targetduration*1.5);if(A>0){if(I>s.targetduration*3)this.log(`Playlist last advanced ${R.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,v=void 0;else if(i!=null&&i.tuneInGoal&&I-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${A} with playlist age: ${s.age}`),A=0;else{let P=Math.floor(A/s.targetduration);if(m+=P,v!==void 0){let M=Math.round(A%s.targetduration/s.partTarget);v+=M}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${A} skip sn ${P} to part ${v}`)}s.tuneInGoal=A}if(y=this.getDeliveryDirectives(s,t.deliveryDirectives,m,v),E||!b){s.requestScheduled=a,this.loadingPlaylist(d,y);return}}else(s.canBlockReload||s.canSkipUntil)&&(y=this.getDeliveryDirectives(s,t.deliveryDirectives,m,v));y&&m!==void 0&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(d,y,s)}else this.clearTimer()}scheduleLoading(e,t,i){let s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=s.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}let o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,s){let n=Zr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=Ei.No),new Di(i,s,n)}checkRetry(e){let t=e.details,i=Ci(e),s=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=s||{},c=!!s&&!!o&&(n===fe.RetryRequest||!s.resolved&&n===fe.SendAlternateToPenaltyBox);if(c){var l;if(a>=o.maxNumRetry)return!1;if(i&&(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=Er(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,s.resolved=!0}return c}};function Jo(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Zt(r[t].attrs,e[t].attrs))return!1;return!0}function Zt(r,e,t){let i=r["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>r[s]!==e[s])}function Pn(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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,s=this.groupIds,n=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(o=>s?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(u=>!i||i.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(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let c=this.hls.config.audioPreference;if(!n&&c){let u=Ve(c,o,ct);if(u>-1)n=o[u];else{let f=Ve(c,this.tracks);n=this.tracks[f]}}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): ${i?.join(",")}`),this.hls.trigger(p.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(p.ERROR,{type:K.MEDIA_ERROR,details:L.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(e,t){t.fatal||!t.context||t.context.type===z.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 i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){let s=this.currentTrack;if(s&&ht(e,s,ct))return s;let n=Ve(e,this.tracksInGroup,ct);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(s){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=Nc(e,t.levels,i,a,ct);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=Ve(e,i);if(a>-1)return i[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 i=this.currentTrack,s=t[e],n=s.details&&!s.details.live;if(e===this.trackId&&s===i&&n||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,ee({},s)),n))return;let a=this.switchParams(s.url,i?.details,s.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||ht(e,s,ct)))return i}if(e){let{name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){let d=t[l];if(ht({name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:c},d,ct))return l}for(let l=0;l<t.length;l++){let d=t[l];if(Zt(e.attrs,d.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){let d=t[l];if(Zt(e.attrs,d.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Pi(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},kn=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;let s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}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 s=t[0];try{s.execute()}catch(n){var i;if(s.onError(n),this.queues===null||this.tracks===null)return;let a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
23
|
+
${this.list("video")}
|
|
24
|
+
${this.list("audio")}
|
|
25
|
+
${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=(t=this.tracks)==null?void 0:t[e],s=i?.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},Fa=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,el="HlsJsTrackRemovedError",wn=class extends Error{constructor(e){super(e),this.name=el}},Mn=class extends Le{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=i=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{let{media:s,mediaSource:n}=this;i&&this.log("Media source opened"),!(!s||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:s,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:i,_objectUrl:s}=this;i!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=Xl(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(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this),e.off(p.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let n=this.isUpdating();n||this.operationQueue.removeBlockers();let a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?ie(i,s.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(i[a]=ie({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:i}}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 i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let s=it(this.appendSource);if(s){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");let c=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||c&&a instanceof c,Na(i),rh(i,o),i.load()}catch{i.src=o}else i.src=o}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,s=t.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
26
|
+
required tracks: ${ne(i,(c,l)=>c==="initSegment"?void 0:l)};
|
|
27
|
+
transfer tracks: ${ne(s,(c,l)=>c==="initSegment"?void 0:l)}}`),!to(s,i)){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(s)}"->"${Object.keys(i)}") start time: ${d} currentTime: ${c}`),this.onMediaDetaching(p.MEDIA_DETACHING,{}),this.onMediaAttaching(p.MEDIA_ATTACHING,t),e.currentTime=d;return}this.transferData=void 0,n.forEach(c=>{let l=c,d=s[l];if(d){let h=d.buffer;if(h){let u=this.fragmentTracker,f=d.id;if(u.hasFragments(f)||u.hasParts(f)){let m=q.getBuffered(h);u.detectEvictedFragments(l,m,f,null,!0)}let g=Bs(l),y=[l,h];this.sourceBuffers[g]=y,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 i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:s,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let 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}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&Na(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(p.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Bs(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new kn(this.tracks)}onBufferCodecs(e,t){var i;let s=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(c=>!s[c]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${n}" SourceBuffers`);return}n.forEach(c=>{var l,d;let h=t[c],{id:u,codec:f,levelCodec:g,container:y,metadata:m,supplemental:v}=h,E=s[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=s[c]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:y,levelCodec:g,metadata:m,id:u});let b=vi(x,_),R=b?.replace(Fa,"$1"),I=vi(f,g),A=(d=I)==null?void 0:d.replace(Fa,"$1");I&&b&&R!==A&&(c.slice(0,5)==="audio"&&(I=Ri(I,this.appendSource)),this.log(`switching codec ${x} to ${I}`),I!==(E.pendingCodec||E.codec)&&(E.pendingCodec=I),E.container=y,this.appendChangeType(c,y,I))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let s=`${t};codecs=${i}`,n={label:`change-type=${s}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),o.changeType(s),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,s=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,N.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o;let c=this.tracks.video;(this.lastVideoAppendEnd>s||c!=null&&c.buffer&&q.isBuffered(c.buffer,s)||((o=this.fragmentTracker.getAppendedFrag(s,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:i}=this,{data:s,type:n,parent:a,frag:o,part:c,chunkMeta:l,offset:d}=t,h=l.buffering[n],{sn:u,cc:f}=o,g=self.performance.now();h.start=g;let y=o.stats.buffering,m=c?c.stats.buffering:null;y.start===0&&(y.start=g),m&&m.start===0&&(m.start=g);let v=i.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=i.video,S=T?.buffer;if(S&&u!=="initSegment"){let b=c||o,R=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){let A=b.start+b.duration*.05,P=S.buffered,M=this.currentOp("video");!P.length&&!M?this.blockAudio(b):!M&&!q.isBuffered(S,A)&&this.lastVideoAppendEnd<A&&this.blockAudio(b)}else if(n==="video"){let I=b.end;if(R){let A=R.frag.start;(I>A||I<this.lastVideoAppendEnd||q.isBuffered(S,A))&&this.unblockAudio()}this.lastVideoAppendEnd=I}}let x=(c||o).start,_={label:`append-${n}`,execute:()=>{var b;h.executeStart=self.performance.now();let R=(b=this.tracks[n])==null?void 0:b.buffer;R&&(E?this.updateTimestampOffset(R,x,.1,n,u,f):d!==void 0&&O(d)&&this.updateTimestampOffset(R,d,1e-6,n,u,f)),this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{let b=self.performance.now();h.executeEnd=h.end=b,y.first===0&&(y.first=b),m&&m.first===0&&(m.first=b);let R={};this.sourceBuffers.forEach(([I,A])=>{I&&(R[I]=q.getBuffered(A))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:n,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:R})},onError:b=>{var R;let I={type:K.MEDIA_ERROR,parent:o.type,details:L.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:c,chunkMeta:l,error:b,err:b,fatal:!1},A=(R=this.media)==null?void 0:R.error;if(b.code===DOMException.QUOTA_EXCEEDED_ERR||b.name=="QuotaExceededError"||"quota"in b)I.details=L.BUFFER_FULL_ERROR;else if(b.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!A)I.errorAction=It(!0);else if(b.name===el&&this.sourceBufferCount===0)I.errorAction=It(!0);else{let P=++this.appendErrors[n];this.warn(`Failed ${P}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${A||"no media error"})`),(P>=this.hls.config.appendErrorMaxRetry||A)&&(I.fatal=!0)}this.hls.trigger(p.ERROR,I)}};this.log(`queuing "${n}" append sn: ${u}${c?" p: "+c.index:""} of ${o.type===N.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(_,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){let{type:i,startOffset:s,endOffset:n}=t;i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,s,n),a)})}onFragParsed(e,t){let{frag:i,part:s}=t,n=[],a=s?s.elementaryStreams:i.elementaryStreams;a[se.AUDIOVIDEO]?n.push("audiovideo"):(a[se.AUDIO]&&n.push("audio"),a[se.VIDEO]&&n.push("video"));let o=()=>{let c=self.performance.now();i.stats.buffering.end=c,s&&(s.stats.buffering.end=c);let l=s?s.stats:i.stats;this.hls.trigger(p.FRAG_BUFFERED,{frag:i,part:s,stats:l,id:i.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.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 i;this.sourceBuffers.forEach(([a])=>{if(a){let o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});let s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?s?(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(p.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(p.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===L.BUFFER_APPEND_ERROR&&t.frag){var i;let s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;O(s)&&s!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;let s=e.config,n=i.currentTime,a=t.levelTargetDuration,o=t.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(O(o)&&o>=0){let l=Math.max(o,a),d=Math.floor(n/a)*a-l;this.flushBackBuffer(n,a,d)}let c=s.frontBufferFlushThreshold;if(O(c)&&c>0){let l=Math.max(s.maxBufferLength,c),d=Math.max(l,a),h=Math.floor(n/a)*a+d;this.flushFrontBuffer(n,a,h)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){let o=q.getBuffered(n);if(o.length>0&&i>o.start(0)){var a;this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:i});let c=this.tracks[s];if((a=this.details)!=null&&a.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(c!=null&&c.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,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(i>c||e>=c&&e<=l)return;this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;let s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let l=Math.max(0,t.fragmentStart),d=Math.max(l,s);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 O(n)?{duration:n}:null;let a=this.media.duration,o=O(i.duration)?i.duration:0;return s>o&&s>a||!O(a)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){let s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==e&&(O(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ne(i)}`),this.tracksReady){var s;let n=(s=this.transferData)==null?void 0:s.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(p.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(p.ERROR,{type:K.MEDIA_ERROR,details:L.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let a=n,o=e[a];if(this.isPending(o)){let 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 d=i.addSourceBuffer(l),h=Bs(a),u=[a,d];t[h]=u,o.buffer=d}catch(d){var s;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(a),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[a],this.hls.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:L.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 i=e.supplemental,s=e.codec;i&&(t==="video"||t==="audiovideo")&&Kt(i,"video")&&(s=vc(s,i));let n=vi(s,e.levelCodec);return n?t.slice(0,5)==="audio"?Ri(n,this.appendSource):n:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;let s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:L.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});let n=this.currentOp(e);n&&n.onError(s)}updateTimestampOffset(e,t,i,s,n,a){let o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){let{media:s,mediaSource:n}=this,a=this.tracks[e],o=a?.buffer;if(!s||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let c=O(s.duration)?s.duration:1/0,l=O(n.duration)?n.duration:1/0,d=Math.max(0,t),h=Math.min(i,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 i=this.tracks[t],s=i?.buffer;if(!s)throw new wn(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.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:i}=this,s=t.map(a=>this.appendBlocker(a));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;let s=(i=this.tracks[t])==null?void 0:i.buffer;!s||s.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let s=this.tracks[e];if(!s)return;let n=s.buffer;if(!n)return;let a=i.bind(this,e);s.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(s=>{i.removeEventListener(s.event,s.listener)}),t.listeners.length=0)}};function Na(r){let e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function rh(r,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function Bs(r){return r==="audio"?1:0}var On=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(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&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,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.clientRect=null,r.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;let s=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let c=e[o];if((c.width>=a||c.height>=a)&&s(c,e[o+1])){n=o;break}}return n}},ah={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},be=ah,oh={HLS:"h"},lh=oh,je=class r{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof r?i:new r(i))),this.value=e,this.params=t}},ch="Dict";function dh(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 hh(r,e,t,i){return new Error(`failed to ${r} "${dh(e)}" as ${t}`,{cause:i})}function He(r,e,t){return hh("serialize",r,e,t)}var Vi=class{constructor(e){this.description=e}},Ba="Bare Item",uh="Boolean";function fh(r){if(typeof r!="boolean")throw He(r,uh);return r?"?1":"?0"}function gh(r){return btoa(String.fromCharCode(...r))}var ph="Byte Sequence";function mh(r){if(ArrayBuffer.isView(r)===!1)throw He(r,ph);return`:${gh(r)}:`}var yh="Integer";function vh(r){return r<-999999999999999||999999999999999<r}function tl(r){if(vh(r))throw He(r,yh);return r.toString()}function Eh(r){return`@${tl(r.getTime()/1e3)}`}function il(r,e){if(r<0)return-il(-r,e);let t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){let s=Math.floor(r*t);return(s%2===0?s:s+1)/t}else return Math.round(r*t)/t}var Th="Decimal";function Sh(r){let e=il(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw He(r,Th);let t=e.toString();return t.includes(".")?t:`${t}.0`}var xh="String",bh=/[\x00-\x1f\x7f]+/;function Ah(r){if(bh.test(r))throw He(r,xh);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Lh(r){return r.description||r.toString().slice(7,-1)}var Ih="Token";function Ua(r){let e=Lh(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw He(e,Ih);return e}function Fn(r){switch(typeof r){case"number":if(!O(r))throw He(r,Ba);return Number.isInteger(r)?tl(r):Sh(r);case"string":return Ah(r);case"symbol":return Ua(r);case"boolean":return fh(r);case"object":if(r instanceof Date)return Eh(r);if(r instanceof Uint8Array)return mh(r);if(r instanceof Vi)return Ua(r);default:throw He(r,Ba)}}var Rh="Key";function Nn(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw He(r,Rh);return r}function _r(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${Nn(e)}`:`;${Nn(e)}=${Fn(t)}`).join("")}function sl(r){return r instanceof je?`${Fn(r.value)}${_r(r.params)}`:Fn(r)}function _h(r){return`(${r.value.map(sl).join(" ")})${_r(r.params)}`}function Dh(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw He(r,ch);let t=r instanceof Map?r.entries():Object.entries(r),i=e?.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof je||(n=new je(n));let a=Nn(s);return n.value===!0?a+=_r(n.params):(a+="=",Array.isArray(n.value)?a+=_h(n):a+=sl(n)),a}).join(`,${i}`)}function nl(r,e){return Dh(r,e)}var $e="CMCD-Object",oe="CMCD-Request",ot="CMCD-Session",Je="CMCD-Status",Ph={br:$e,ab:$e,d:$e,ot:$e,tb:$e,tpb:$e,lb:$e,tab:$e,lab:$e,url:$e,pb:oe,bl:oe,tbl:oe,dl:oe,ltc:oe,mtp:oe,nor:oe,nrr:oe,rc:oe,sn:oe,sta:oe,su:oe,ttfb:oe,ttfbb:oe,ttlb:oe,cmsdd:oe,cmsds:oe,smrt:oe,df:oe,cs:oe,ts:oe,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},Ch={REQUEST:oe};function kh(r){return Object.keys(r).reduce((e,t)=>{var i;return(i=r[t])===null||i===void 0||i.forEach(s=>e[s]=t),e},{})}function wh(r,e){let t={};if(!r)return t;let i=Object.keys(r),s=e?kh(e):{};return i.reduce((n,a)=>{var o;let c=Ph[a]||s[a]||Ch.REQUEST,l=(o=n[c])!==null&&o!==void 0?o:n[c]={};return l[a]=r[a],n},t)}function Mh(r){return["ot","sf","st","e","sta"].includes(r)}function Oh(r){return typeof r=="number"?O(r):r!=null&&r!==""&&r!==!1}var rl="event";function Fh(r,e){let t=new URL(r),i=new URL(e);if(t.origin!==i.origin)return r;let s=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+t.search+t.hash}var xi=r=>Math.round(r),Bn=(r,e)=>Array.isArray(r)?r.map(t=>Bn(t,e)):r instanceof je&&typeof r.value=="string"?new je(Bn(r.value,e),r.params):(e.baseUrl&&(r=Fh(r,e.baseUrl)),e.version===1?encodeURIComponent(r):r),hi=r=>xi(r/100)*100,Nh=(r,e)=>{let t=r;return e.version>=2&&(r instanceof je&&typeof r.value=="string"?t=new je([r]):typeof r=="string"&&(t=[r])),Bn(t,e)},Bh={br:xi,d:xi,bl:hi,dl:hi,mtp:hi,nor:Nh,rtp:hi,tb:xi},al="request",ol="response",Dr=["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"],Uh=["e"],$h=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Ji(r){return $h.test(r)}function Gh(r){return Dr.includes(r)||Uh.includes(r)||Ji(r)}var ll=["d","dl","nor","ot","rtp","su"];function Kh(r){return Dr.includes(r)||ll.includes(r)||Ji(r)}var Vh=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Hh(r){return Dr.includes(r)||ll.includes(r)||Vh.includes(r)||Ji(r)}var Yh=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function qh(r){return Yh.includes(r)||Ji(r)}var Wh={[ol]:Hh,[rl]:Gh,[al]:Kh};function cl(r,e={}){let t={};if(r==null||typeof r!="object")return t;let i=e.version||r.v||1,s=e.reportingMode||al,n=i===1?qh:Wh[s],a=Object.keys(r).filter(n),o=e.filter;typeof o=="function"&&(a=a.filter(o));let c=s===ol||s===rl;c&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");let l=ie({},Bh,e.formatters),d={version:i,reportingMode:s,baseUrl:e.baseUrl};return a.sort().forEach(h=>{let u=r[h],f=l[h];if(typeof f=="function"&&(u=f(u,d)),h==="v"){if(i===1)return;u=i}h=="pr"&&u===1||(c&&h==="ts"&&!O(u)&&(u=Date.now()),Oh(u)&&(Mh(h)&&typeof u=="string"&&(u=new Vi(u)),t[h]=u))}),t}function jh(r,e={}){let t={};if(!r)return t;let i=cl(r,e),s=wh(i,e?.customHeaderMap);return Object.entries(s).reduce((n,[a,o])=>{let c=nl(o,{whitespace:!1});return c&&(n[a]=c),n},t)}function Qh(r,e,t){return ie(r,jh(e,t))}var zh="CMCD";function Xh(r,e={}){return r?nl(cl(r,e),{whitespace:!1}):""}function Zh(r,e={}){if(!r)return"";let t=Xh(r,e);return encodeURIComponent(t)}function Jh(r,e={}){if(!r)return"";let t=Zh(r,e);return`${zh}=${t}`}var $a=/CMCD=[^&#]+/;function eu(r,e,t){let i=Jh(e,t);if(!i)return r;if($a.test(r))return r.replace($a,i);let s=r.includes("?")?"&":"?";return`${r}${s}${i}`}var Un=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=s=>{try{this.apply(s,{ot:be.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{let{frag:n,part:a}=s,o=this.hls.levels[n.level],c=this.getObjectType(n),l={d:(a||n).duration*1e3,ot:c};(c===be.VIDEO||c===be.AUDIO||c==be.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(s,l)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:lh.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 i=t.ot===be.INIT||t.ot===be.VIDEO||t.ot===be.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((a,o)=>(s.includes(o)&&(a[o]=t[o]),a),{}));let n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Qh(e.headers,t,n)):e.url=eu(e.url,t,n)}getNextFrag(e){var t;let i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){let s=e.sn-i.startSN;return i.fragments[s+1]}}getNextPart(e){var t;let{index:i,fragment:s}=e,n=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=s;for(let o=n.length-1;o>=0;o--){let c=n[o];if(c.index===i&&c.fragment.sn===a)return n[o+1]}}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return be.TIMED_TEXT;if(e.sn==="initSegment")return be.INIT;if(t==="audio")return be.AUDIO;if(t==="main")return this.hls.audioTracks.length?be.VIDEO:be.MUXED}getTopBandwidth(e){let t=0,i,s=this.hls;if(e===be.AUDIO)i=s.audioTracks;else{let n=s.maxAutoLevel,a=n>-1?n+1:s.levels.length;i=s.levels.slice(0,a)}return i.forEach(n=>{n.bitrate>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,i=e===be.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:q.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}},tu=3e5,$n=class extends Le{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if(i?.action===fe.SendAlternateToPenaltyBox&&i.flags===Re.MoveAllAlternatesMatchingHost){let s=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:c,type:l}=t.context;o&&s?a=this.getPathwayForGroupId(o,l,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&s&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),t.details===L.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${ne(n)} penalized: ${ne(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>tu&&delete i[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,wo(t),this.hls.trigger(p.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,i){let s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(t===z.AUDIO_TRACK&&s[n].hasAudioGroup(e)||t===z.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(e))return s[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},s={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":c}=n;if(t.some(d=>d.pathwayId===a))return;let l=this.getLevelsForPathway(o).map(d=>{let h=new re(d.attrs);h["PATHWAY-ID"]=a;let u=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;u&&(i[h.AUDIO]=u,h.AUDIO=u),f&&(s[h.SUBTITLES]=f,h.SUBTITLES=f);let g=dl(d.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),y=new ft({attrs:h,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:g,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let m=1;m<d.audioGroups.length;m++)y.addGroupId("audio",`${d.audioGroups[m]}_clone_${a}`);if(d.subtitleGroups)for(let m=1;m<d.subtitleGroups.length;m++)y.addGroupId("text",`${d.subtitleGroups[m]}_clone_${a}`);return y});t.push(...l),Ga(this.audioTracks,i,c,a),Ga(this.subtitleTracks,s,c,a)})}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){let d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+d)}let n={responseType:"json",url:s.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,f)=>{this.log(`Loaded steering manifest: "${s}"`);let g=d.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":y,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":v}=g;if(y)try{this.uri=new self.URL(y,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${y}`);return}this.scheduleRefresh(this.uri||u.url),m&&this.clonePathways(m);let E={steeringManifest:g,url:s.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,E),v&&this.updatePathwayPriority(v)},onError:(d,h,u,f)=>{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 g=this.timeToLoad*1e3;if(d.code===429){let y=this.loader;if(typeof y?.getResponseHeader=="function"){let m=y.getResponseHeader("Retry-After");m&&(g=parseFloat(m)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(d,h,u)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Ga(r,e,t,i){r&&Object.keys(e).forEach(s=>{let n=r.filter(a=>a.groupId===s).map(a=>{let o=ie({},a);return o.details=void 0,o.attrs=new re(o.attrs),o.url=o.attrs.URI=dl(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});r.push(...n)})}function dl(r,e,t,i){let{HOST:s,PARAMS:n,[t]:a}=i,o;e&&(o=a?.[e],o&&(r=o));let c=new self.URL(r);return s&&!o&&(c.host=s),n&&Object.keys(n).sort().forEach(l=>{l&&c.searchParams.set(l,n[l])}),c.href}var Hi=class r extends Le{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:i,initData:s}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.debug(n),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Ft(this.config));let o=a.map(Ps).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o=Ti(a);if(i!=="sinf"||o!==ae.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);return}let c;try{let f=ce(new Uint8Array(s)),g=Sr(JSON.parse(f).sinf),y=co(g);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(y.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}let l=pe(c),{keyIdToKeySessionPromise:d,mediaKeySessions:h}=this,u=d[l];for(let f=0;f<h.length;f++){let g=h[f],y=g.decryptdata;if(!y.keyId)continue;let m=pe(y.keyId);if(Oi(c,y.keyId)||y.uri.replace(/-/g,"").indexOf(l)!==-1){if(u=d[m],!u)continue;if(y.pssh)break;delete d[m],y.pssh=new Uint8Array(s),y.keyId=c,u=d[l]=u.then(()=>this.generateRequestWithPreferredKeySession(g,i,s,"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(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(p.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(p.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t?.[e];if(s)return s.licenseUrl;if(e===ae.WIDEVINE&&i)return i}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,i=t?.[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(a,o,c)=>!!a&&c.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let c=l=>{let d=l.shift();this.getMediaKeysPromise(d,s,n).then(h=>a({keySystem:d,mediaKeys:h})).catch(h=>{l.length?c(l):h instanceof Ee?o(h):o(new Ee({type:K.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};c(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Lo===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){var s;let n=Jc(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(s=a)==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ne(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(f=>f?this.setMediaKeysServerCertificate(u,e,f):u)));return h.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),h})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${pe(e.keyId||[])} keyUri: ${e.uri}`);let s=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),s=ui(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){let i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${pe(e.decryptdata.keyId||[])}
|
|
28
|
+
} (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Ps(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:s})=>{let n=Ps(s);n?t(n):i(new Error(`Unable to find format for key-system "${s}"`))}).catch(i)})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=Ft(this.config),i=e.map(Ti).filter(s=>!!s&&t.indexOf(s)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){let s=iu(e,t[i]);if(s)return s}}loadKey(e){let t=e.keyInfo.decryptdata,i=ui(t),s=this.bannedKeyIds[i];if(s||this.getKeyStatus(t)==="internal-error"){let o=Ka(s||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}let n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let a=this.keyIdToKeySessionPromise[i];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[i]=o,o}return a.catch(o=>{if(o instanceof Ee){let c=ee({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);let l=new Ee(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 Ee){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${pe(i.keyId||[])})`:""}`),this.hls.trigger(p.ERROR,e.data)}else this.error(e.message),this.hls.trigger(p.ERROR,{type:K.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=ui(e),i=this.keyIdToKeySessionPromise[t];if(!i){let s=Ti(e.keyFormat),n=s?[s]:Ft(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Ft(this.config)),e.length===0)throw new Ee({type:K.KEY_SYSTEM_ERROR,details:L.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 i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,s){var n;let a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{let g=a.call(this.hls,t,i,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,i=g.initData?g.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);let o=ui(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${i.byteLength})`);let l=new xr,d=e._onmessage=g=>{let y=e.mediaKeysSession;if(!y){l.emit("error",new Error("invalid state"));return}let{messageType:m,message:v}=g;this.log(`"${m}" message event for session "${y.sessionId}" message size: ${v.byteLength}`),m==="license-request"||m==="license-renewal"?this.renewLicense(e,v).catch(E=>{l.eventNames().length?l.emit("error",E):this.handleError(E)}):m==="license-release"?e.keySystem===ae.FAIRPLAY&&this.updateKeySession(e,un("acknowledged")).then(()=>this.removeSession(e)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${m}"`)},h=(g,y)=>{y.keyStatus=g;let m;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?m=Ka(g,y.decryptdata):g==="expired"?m=new Error(`key expired (keyId: ${o})`):g==="released"?m=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),m&&(l.eventNames().length?l.emit("error",m):this.handleError(m))},u=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}let m=this.getKeyStatuses(e);if(!Object.keys(m).some(S=>m[S]!=="status-pending"))return;if(m[o]==="expired"){this.log(`Expired key ${ne(m)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let E=m[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 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.`),h(x,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} (${ne(m)}).`)}};Te(e.mediaKeysSession,"message",d),Te(e.mediaKeysSession,"keystatuseschange",u);let f=new Promise((g,y)=>{l.on("error",y),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new Ee({type:K.KEY_SYSTEM_ERROR,details:L.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((i,s)=>{if(typeof s=="string"&&typeof i=="object"){let o=s;s=i,i=o}let n="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);if(e.keySystem===ae.PLAYREADY&&n.length===16){let o=pe(n);t[o]=i,bo(n)}let a=pe(n);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=i}),t}fetchServerCertificate(e){let t=this.config,i=t.loader,s=new i(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,f,g,y)=>{a(u.data)},onError:(u,f,g,y)=>{o(new Ee({type:K.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:ee({url:c.url,data:void 0},u)},`"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{o(new Ee({type:K.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(u,f,g)=>{o(new Error("aborted"))}};s.load(c,d,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(a=>{n(new Ee({type:K.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(s=>{throw new Ee({type:K.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:s,fatal:!1},s.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let s=new DOMParser().parseFromString(i,"application/xml"),n=s.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 f=(a=d.querySelector("name"))==null?void 0:a.textContent,g=(o=d.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}let c=s.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return un(atob(l))}setupLicenseXHR(e,t,i,s){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,s)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,s)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((s,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)}s(c)}else{let c=i.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)n(new Ee({type:K.KEY_SYSTEM_ERROR,details:L.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(s,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==ae.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 i=t.media;this.media=i,Te(i,"encrypted",this.onMediaEncrypted),Te(i,"waitingforkey",this.onWaitingForKey);let s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){let e=this.media;e&&(Ae(e,"encrypted",this.onMediaEncrypted),Ae(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 i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ct.clearKeyUriToKeyIdMap();let n=s.length;r.CDMCleanupPromise=Promise.all(s.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:K.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:K.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i,decryptdata:s}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${pe(s?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let 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(td(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(p.ERROR,{type:K.OTHER_ERROR,details:L.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(p.ERROR,{type:K.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}};Hi.CDMCleanupPromise=void 0;function ui(r){if(!r)throw new Error("Could not read keyId of undefined decryptdata");if(r.keyId===null)throw new Error("keyId is null");return pe(r.keyId)}function iu(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 Ee=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 Ka(r,e){let t=r==="output-restricted",i=t?L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:L.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ee({type:K.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}var Gn=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(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){let s=performance.now();if(t){if(this.lastTime){let n=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*a/n,l=this.hls;if(l.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),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(p.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function hl(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 ul(r,e){let t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){te.debug(`[texttrack-utils]: ${i}`);try{let s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,r.addCue(s)}catch(s){te.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(r.mode=t)}function At(r,e){let t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let i=r.cues.length;i--;)e&&r.cues[i].removeEventListener("enter",e),r.removeCue(r.cues[i]);t==="disabled"&&(r.mode=t)}function Kn(r,e,t,i){let s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){let n=nu(r.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&r.removeCue(n[a])}s==="disabled"&&(r.mode=s)}function su(r,e){if(e<=r[0].startTime)return 0;let t=r.length-1;if(e>r[t].endTime)return-1;let i=0,s=t,n;for(;i<=s;)if(n=Math.floor((s+i)/2),e<r[n].startTime)s=n-1;else if(e>r[n].startTime&&i<t)i=n+1;else return n;return r[i].startTime-e<e-r[s].startTime?i:s}function nu(r,e,t){let i=[],s=su(r,e);if(s>-1)for(let n=s,a=r.length;n<a;n++){let o=r[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function bi(r){let e=[];for(let t=0;t<r.length;t++){let i=r[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(r[t])}return e}var Vn=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,i=bi(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")t=i[n];else if(i[n].mode==="showing"){t=i[n];break}let s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},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(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let i=this.media;if(!i)return;let s=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,s)return;bi(i.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:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,s=this.groupIds,n=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(a=>s?.indexOf(a)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(d=>!i||i.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=Ve(o,a);if(d>-1)n=a[d];else{let h=Ve(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 "${i?.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){let n=t[s];if(!(i&&!n.default||!i&&!e)&&(!e||ht(n,e)))return s}if(e){for(let s=0;s<t.length;s++){let n=t[s];if(Zt(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){let n=t[s];if(Zt(e.attrs,n.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let s=t[i];if(Pn(s,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===z.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 i=this.currentTrack;if(i&&ht(e,i))return i;let s=Ve(e,this.tracksInGroup);if(s>-1){let n=this.tracksInGroup[s];return this.setSubtitleTrack(s),n}else{if(i)return null;{let n=Ve(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=bi(e.textTracks),i=this.currentTrack,s;if(i&&(s=t.filter(n=>Pn(i,n))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==s&&(n.mode="disabled")}),s){let n=this.subtitleDisplay?"showing":"hidden";s.mode!==n&&(s.mode=n)}}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 i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}let n=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));let{id:a,groupId:o="",name:c,type:l,url:d}=s;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:c,type:l,url:d});let h=this.switchParams(s.url,i?.details,s.details);this.loadPlaylist(h)}};function ru(){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,s=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?n:n&3|8).toString(16)})}}}function Ut(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}var Dt=.025,Yi=(function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r})({});function au(r,e,t){return`${r.identifier}-${t+1}-${Ut(e)}`}var Hn=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return Us(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,i=Us(t,e);return t-i<.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 Us(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)<Dt))}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"?Yi.Range:Yi.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 ou(this)}};function Us(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<Dt)?e.start:e.start+e.duration}function fl(r,e,t){let i=new self.URL(r,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function $s(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function ou(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function bt(r){let e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var Yn=class{constructor(e,t,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(p.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=i,this.assetItem=s;let a=()=>{this.hasDetails=!0};n.once(p.LEVEL_LOADED,a),n.once(p.AUDIO_TRACK_LOADED,a),n.once(p.SUBTITLE_TRACK_LOADED,a),n.on(p.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(p.BUFFER_APPENDED,()=>{let d=this.bufferedEnd;this.reachedPlayout(d)&&(this._bufferedEosTime=d,n.trigger(p.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=fl(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 i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,n=q.bufferInfo(e,s,0);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(e){let i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=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 i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;(s=this.hls)==null||s.on(e,t)}once(e,t,i){var s;(s=this.hls)==null||s.once(e,t)}off(e,t,i){var s;(s=this.hls)==null||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${bt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},Va=.033,qn=class extends Le{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let s=this.items;if(s)for(s[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=s[i])!=null&&n.event;){var n;i--}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let s=0;s<i.length;s++){let n=i[s];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return s}return-1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){let n=i[s].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return s}return-1}findEventIndex(e){let t=this.items;if(t)for(let s=t.length;s--;){var i;if(((i=t[s].event)==null?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){let i=e.assetList,s=i.length;if(s>1)for(let n=0;n<s;n++){let a=i[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===s-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let i=t.assetList,s=i[i.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){let i=e.main.details,{dateRanges:s}=i,n=this.events,a=this.parseDateRanges(s,{url:i.url},t),o=Object.keys(s),c=n?n.filter(l=>!o.includes(l.identifier)):[];a.length&&a.sort((l,d)=>{let h=l.cue.pre,u=l.cue.post,f=d.cue.pre,g=d.cue.post;if(h&&!f)return-1;if(f&&!h||u&&!g)return 1;if(g&&!u)return-1;if(!h&&!f&&!u&&!g){let y=l.startTime,m=d.startTime;if(y!==m)return y-m}return l.dateRange.tagOrder-d.dateRange.tagOrder}),this.events=a,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],i=!1){let s=this.events||[];if(s.length||t.length||this.length<2){let n=this.items,a=this.parseSchedule(s,e);(i||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,i){let s=[],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 Hn(c,t),this.eventMap[o]=l,i===!1&&(l.appendInPlace=i)),s.push(l)}}return s}parseSchedule(e,t){let i=[],s=t.main.details,n=s.live?1/0:s.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,f=d.cue.post,g=e[h-1]||null,y=d.appendInPlace,m=f?n:d.startOffset,v=d.duration,E=d.timelineOccupancy===Yi.Range?v:0,T=d.resumptionOffset,S=g?.startTime===m,x=m+d.cumulativeDuration,_=y?x+v:m+T;if(u||!f&&m<=0){let R=l;l+=E,d.timelineStart=x;let I=a;a+=v,i.push({event:d,start:x,end:_,playout:{start:I,end:a},integrated:{start:R,end:l}})}else if(m<=n){if(!S){let A=m-c;if(A>Va){let P=c,M=l;l+=A;let B=a;a+=A;let V={previousEvent:e[h-1]||null,nextEvent:d,start:P,end:P+A,playout:{start:B,end:a},integrated:{start:M,end:l}};i.push(V)}else A>0&&g&&(g.cumulativeDuration+=A,i[i.length-1].end=m)}f&&(_=x),d.timelineStart=x;let R=l;l+=E;let I=a;a+=v,i.push({event:d,start:x,end:_,playout:{start:I,end:a},integrated:{start:R,end:l}})}else return;let b=d.resumeTime;f||b>n?c=n:c=b}),c<n){var o;let d=c,h=l,u=n-c;l+=u;let f=a;a+=u,i.push({previousEvent:((o=i[i.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:d+u,playout:{start:f,end:a},integrated:{start:h,end:l}})}this.setDurations(n,a,l)}else i.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 i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){let i=t.main.details,s=i.live?1/0:i.edge,n=0,a=-1;e.forEach((o,c)=>{let l=o.cue.pre,d=o.cue.post,h=l?0:d?s:o.startTime;this.updateAssetDurations(o),a===h?o.cumulativeDuration=n:(n=0,a=h),!d&&o.snapOptions.in&&(o.resumeAnchor=gt(null,i.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<Va&&(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;n+=f})}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(i-s)>Dt?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,c=o.edge;if(i>=c)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${c}`),!1;let l=gt(null,o.fragments,i);if(!l)return this.log(`"${e.identifier}" resumption ${i} 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-i)<Dt+d||Math.abs(l.end-i)<Dt+d?!1:(this.log(`"${e.identifier}" resumption ${i} 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,i=0,s=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],c=t+i;o.startOffset=i,o.timelineStart=c,s||(s=o.duration===null),n||(n=!!o.error);let l=o.error?0:o.duration||0;i+=l}s&&!n?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Oe(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}var Wn=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let i=e.assetListUrl,s;try{s=fl(i,this.hls.sessionId,e.baseUrl)}catch(u){let f=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,u,i);this.hls.trigger(p.ERROR,f);return}t&&s.protocol!=="data:"&&s.searchParams.set("_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),c={responseType:"json",url:s.href},l=n.interstitialAssetListLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,y)=>{let m=u.data,v=m?.ASSETS;if(!Array.isArray(v)){let E=this.assignAssetListError(e,L.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,y);this.hls.trigger(p.ERROR,E);return}e.assetListResponse=m,this.hls.trigger(p.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:y})},onError:(u,f,g,y)=>{let m=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${u.code} ${u.text} (${f.url})`),f.url,y,g);this.hls.trigger(p.ERROR,m)},onTimeout:(u,f,g)=>{let y=this.assignAssetListError(e,L.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,u,g);this.hls.trigger(p.ERROR,y)}};return o.load(c,d,h),this.hls.trigger(p.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,s,n,a){return e.error=i,{type:K.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:a,stats:n}}};function Ha(r){var e;r==null||(e=r.play())==null||e.catch(()=>{})}function fi(r,e){return`[${r}] Advancing timeline position to ${e}`}var jn=class extends Le{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 i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;let s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;let a=s<=-.01;this.timelinePos=i,this.bufferedPos=i;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(!0),this.checkBuffer(),a&&i<o.start||i>=o.end){var c;let f=this.findItemIndex(o),g=this.schedule.findItemIndexAtTime(i);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a&&g>f){let y=this.schedule.findJumpRestrictedIndex(f+1,g);if(y>f){this.setSchedulePosition(y);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(i,f))}return}let d=l.timelineStart,h=l.duration||0;if(a&&i<d||i>=d+h){var u;(u=o.event)!=null&&u.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,l)}},this.onTimeupdate=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;let s=this.playingItem;if(!s||this.playingLastItem)return;if(i>=s.end){this.timelinePos=s.end;let o=this.findItemIndex(s);this.setSchedulePosition(o+1)}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,n)},this.onScheduleUpdate=(i,s)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],c=n.items||[],l=n.durations,d=i.map(y=>y.identifier),h=!!(o.length||d.length);(h||s)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
29
|
+
Schedule: ${c.map(y=>Oe(y))} pos: ${this.timelinePos}`),d.length&&this.log(`Removed events ${d}`);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))),i.forEach(y=>{y.assetList.forEach(m=>{this.clearAssetPlayer(m.identifier,null)})}),this.playerQueue.forEach(y=>{if(y.interstitial.appendInPlace){let m=y.assetItem.timelineStart,v=y.timelineOffset-m;if(v)try{y.timelineOffset=m}catch(E){Math.abs(v)>Dt&&this.warn(`${E} ("${y.assetId}" ${y.timelineOffset}->${m})`)}}}),h||s){if(this.hls.trigger(p.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),g&&f!==u&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Wn(e),this.schedule=new qn(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.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){Ae(e,"play",this.onPlay),Ae(e,"pause",this.onPause),Ae(e,"seeking",this.onSeeking),Ae(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let i=this.media=t.media;Te(i,"seeking",this.onSeeking),Te(i,"timeupdate",this.onTimeupdate),Te(i,"play",this.onPlay),Te(i,"pause",this.onPause)}onMediaAttached(e,t){let i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!s){this.clearScheduleState();let n=this.findItemIndex(i);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,i=h=>h&&e.getAssetPlayer(h.identifier),s=(h,u,f,g,y)=>{if(h){let m=h[u].start,v=h.event;if(v){if(u==="playout"||v.timelineOccupancy!==Yi.Point){let E=i(f);E?.interstitial===v&&(m+=E.assetItem.startOffset+E[y])}}else{let E=g==="bufferedPos"?a():e[g];m+=E-h.start}return m}return 0},n=(h,u)=>{var f;if(h!==0&&u!=="primary"&&(f=e.schedule)!=null&&f.length){var g;let y=e.schedule.findItemIndexAtTime(h),m=(g=e.schedule.items)==null?void 0:g[y];if(m){let v=m[u].start-m.start;return h+v}}return h},a=()=>{let h=e.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var u,f;return(u=e.primaryDetails)!=null&&u.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[h])||0},c=(h,u)=>{var f,g;let y=e.effectivePlayingItem;if(y!=null&&(f=y.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${u}"`);let m=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(h,u),E=(g=e.schedule.items)==null?void 0:g[v],T=e.getBufferingPlayer(),S=T?.interstitial,x=S?.appendInPlace,_=m&&e.itemsMatch(m,E);if(m&&(x||_)){let b=i(e.playingAsset),R=b?.media||e.primaryMedia;if(R){let I=u==="primary"?R.currentTime:s(m,u,e.playingAsset,"timelinePos","currentTime"),A=h-I,P=(x?I:R.currentTime)+A;if(P>=0&&(!b||x||P<=b.duration)){R.currentTime=P;return}}}if(E){let b=h;if(u!=="primary"){let I=E[u].start,A=h-I;b=E.start+A}let R=!e.isInterstitial(E);if((!e.isInterstitial(m)||m.event.appendInPlace)&&(R||E.event.appendInPlace)){let I=e.media||(x?T?.media:null);I&&(I.currentTime=b)}else if(m){let I=e.findItemIndex(m);if(v>I){let P=e.schedule.findJumpRestrictedIndex(I+1,v);if(P>I){e.setSchedulePosition(P);return}}let A=0;if(R)e.timelinePos=b,e.checkBuffer();else{let P=E.event.assetList,M=h-(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){A=B;break}}}e.setSchedulePosition(v,A)}}},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 f;return s(u,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-u.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let h=l(),u=e.effectivePlayingItem;return u&&u===h?s(u,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-u.playout.start:0},set currentTime(h){let u=l(),f=e.effectivePlayingItem;f&&f===u&&c(h+f.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(f=>e.getAssetPlayer(f.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 s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(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 f=e.findItemIndex(h);if(u.appendInPlace){let g=h.playout.start+h.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,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(s=this.primaryMedia);let n=(t=s)==null?void 0:t.currentTime;if(!(n===void 0||!O(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s){this.detachedData={media:s};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ne(n)}`),this.detachedData=n}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,c=o&&e.interstitial.appendInPlace,l=(i=this.detachedData)==null?void 0:i.mediaSource,d;if(a.media)c&&(n=a.transferMedia(),this.detachedData=n),d="Primary";else if(l){let g=this.getBufferingPlayer();g?(n=g.transferMedia(),d=`${g}`):d="detached MediaSource"}else d="detached media";if(!n){if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${ne(n)}`);else if(!this.detachedData||a.media===t){let g=this.playerQueue;g.length>1&&g.forEach(y=>{if(o&&y.interstitial.appendInPlace!==c){let m=y.interstitial;this.clearInterstitial(y.interstitial,null),m.appendInPlace=!1,m.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${m}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let h=n&&"mediaSource"in n&&((s=n.mediaSource)==null?void 0:s.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 f=this.schedule;if(u===n&&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 i=this.timelinePos,s=this.effectivePlayingItem;if(i===-1){let n=this.hls.startPosition;if(this.log(fi("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){let a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){let a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(s&&!this.playingItem){let n=e.findItemIndex(s);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){let i=e.event,s=i.findAssetIndex(t),n=$s(i,s);if(!i.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,i){let s=$s(e,i);if(e.isAssetPastPlayoutLimit(s)){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(fi("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[s];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let s=t.parentIdentifier,n=i.getEvent(s);if(n){let a=i.findEventIndex(s),o=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var i;let s=(i=this.schedule)==null?void 0:i.items;if(!s||this.playbackDisabled)return;let n=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&Oe(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,f=u?this.getAssetPlayer(u):null;if(f&&u&&(!this.eventItemsMatch(a,n)||t!==void 0&&u!==d.assetList[t].identifier)){var c;let g=d.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${d.assetList.length} ${bt(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(p.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:g,event:d,schedule:s.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(d,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(u,n),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${d} ${Oe(a)}`),d.hasPlayed=!0,this.hls.trigger(p.INTERSTITIAL_ENDED,{event:d,schedule:s.slice(0),scheduleIndex:e}),d.cue.once)){var l;this.updateSchedule();let g=(l=this.schedule)==null?void 0:l.items;if(n&&g){let y=this.findItemIndex(n);this.advanceSchedule(y,g,t,a,o)}return}}this.advanceSchedule(e,s,t,a,o)}advanceSchedule(e,t,i,s,n){let a=this.schedule;if(!a)return;let o=t[e]||null,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(i===void 0){i=a.findAssetIndex(d,this.timelinePos);let g=$s(d,i-1);if(d.isAssetPastPlayoutLimit(g)||d.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(d,e,i);return}i=g}let h=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let u=this.preloadAssets(d,i);if(this.eventItemsMatch(o,h||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Oe(o)} ${d.appendInPlace?"append in place":""}`),this.hls.trigger(p.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 f=d.assetList[i];if(!f){this.advanceAfterAssetEnded(d,e,i||0);return}if(u||(u=this.getAssetPlayer(f.identifier)),u===null||u.destroyed){let g=d.assetList.length;this.warn(`asset ${i+1}/${g} player destroyed ${d}`),u=this.createAssetPlayer(d,f,i),u.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(u,i,t,e,c),this.shouldPlay&&Ha(u.media)}else o?(this.resumePrimary(o,e,s),this.shouldPlay&&Ha(this.hls.media)):n&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var s,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Oe(e)}`),!((s=this.detachedData)!=null&&s.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(fi("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!i)return;let a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Oe(e)}`),this.hls.trigger(p.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let i=e.start;if(this.primaryLive){let s=this.primaryDetails;if(t===0)return this.hls.startPosition;if(s&&(i<s.fragmentStart||i>s.edge))return this.hls.liveSyncPosition||-1}return i}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,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let s=this.primaryMedia;if(!s)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(fi("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;let s=this.hls;!s.loadingEnabled||!s.media||Math.abs((((i=s.mainForwardBufferInfo)==null?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.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(p.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(p.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let s=ee(ee({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=ee(ee({},this.altSelection),{},{audio:i});return}let n=ee(ee({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=ee(ee({},this.altSelection),{},{subtitles:i});return}let n=ee(ee({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(e,t){let i=ea(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){let i=ea(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(i)))}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let s=0;s<t.length;s++){let n=t[s];if(n.cue.post){var i;let a=this.schedule.findEventIndex(n.identifier),o=(i=this.schedule.items)==null?void 0:i[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 i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;let s=(i=this.schedule)==null?void 0:i.items;if(e&&s){let n=this.findItemIndex(e,t);return s[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});let i=e.end+.25,s=q.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Oe(e)} (was ${Oe(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;let i=(t=this.schedule)==null?void 0:t.items;if(!i)return;let s=q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,i,e)}updateBufferedPos(e,t,i){let s=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),c=s.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 f=n.event;if(h-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,c>d&&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 i&&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(s=>{let n=this.getAssetPlayer(s.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:s,events:n}=i;if(!s||!n)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Oe(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let l=i.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(p.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;let s=this.detachedData;s?s.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){let i=e.event,s=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(s||!n){let a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let i=e.assetUrl,s=e.assetList.length,n=s===0&&!e.assetListLoader,a=e.cue.once;if(n){let 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}/${i?1:s} ${e}${l?` live-start: ${d} start-offset: ${l}`:""}`),i)return this.createAsset(e,0,0,c,e.duration,i);let h=this.assetListLoader.loadAssetList(e,l);h&&(e.assetListLoader=h)}else if(!a&&s){for(let l=t;l<s;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(s=>{this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:s})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,s,n,a){let o={parentIdentifier:e.identifier,identifier:au(e,a,t),duration:n,startOffset:i,timelineStart:s,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){let s=this.hls,n=s.userConfig,a=n.videoPreference,o=s.loadLevelObj||s.levels[s.currentLevel];(a||o)&&(a=ie({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let c=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack],d=0;if(this.primaryLive||e.appendInPlace){let S=this.timelinePos-t.timelineStart;if(S>1){let x=t.duration;x&&S<x&&(d=S)}}let h=t.identifier,u=ee(ee({},n),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:s.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 f=u.cmcd;f!=null&&f.sessionId&&f.contentId&&(u.cmcd=ie({},f,{contentId:Ut(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);let g=new Yn(this.HlsPlayerClass,u,e,t);this.playerQueue.push(g),e.assetList[i]=t;let y=!0,m=S=>{if(S.live){var x;let R=new Error(`Interstitials MUST be VOD assets ${e}`),I={fatal:!0,type:K.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:R},A=((x=this.schedule)==null?void 0:x.findEventIndex(e.identifier))||-1;this.handleAssetItemError(I,e,A,i,R.message);return}let _=S.edge-S.fragmentStart,b=t.duration;(y||b===null||_>b)&&(y=!1,this.log(`Interstitial asset "${h}" duration change ${b} > ${_}`),t.duration=_,this.updateSchedule())};g.on(p.LEVEL_UPDATED,(S,{details:x})=>m(x)),g.on(p.LEVEL_PTS_UPDATED,(S,{details:x})=>m(x)),g.on(p.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(S,x)=>{let _=this.getAssetPlayer(h);if(_&&x.tracks){_.off(p.BUFFER_CODECS,v),_.tracks=x.tracks;let b=this.primaryMedia;this.bufferingAsset===_.assetItem&&b&&!_.media&&this.bufferAssetPlayer(_,b)}};g.on(p.BUFFER_CODECS,v);let E=()=>{var S;let x=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${x}`),!x||!this.schedule)return;let _=this.schedule.findEventIndex(e.identifier),b=(S=this.schedule.items)==null?void 0:S[_];this.isInterstitial(b)&&this.advanceAssetBuffering(b,t)};g.on(p.BUFFERED_TO_END,E);let T=S=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;let _=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,_,S)};return g.once(p.MEDIA_ENDED,T(i)),g.once(p.PLAYOUT_LIMIT_REACHED,T(1/0)),g.on(p.ERROR,(S,x)=>{if(!this.schedule)return;let _=this.getAssetPlayer(h);if(x.details===L.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),i,`Asset player error ${x.error} ${e}`)}),g.on(p.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;let x=new Error(`Asset player destroyed unexpectedly ${h}`),_={fatal:!0,type:K.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(_,e,this.schedule.findEventIndex(e.identifier),i,x.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${bt(t)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(i!==-1){let s=this.playerQueue[i];this.log(`clear ${s} toSegment: ${t&&Oe(t)}`),this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,n){let{interstitial:a,assetItem:o,assetId:c}=e,l=a.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!d||d.identifier!==c)&&(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${bt(o)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var i,s;if(!this.schedule)return;let{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),c=(i=this.schedule.items)==null?void 0:i[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||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(d&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(h&&!to(h,e.tracks)){let u=new Error(`Asset ${bt(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),f={fatal:!0,type:K.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},g=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,g,u.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let s=i.currentTime,n=t.findAssetIndex(e,s),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let c=o.currentTime||s-a.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${s})`),c&&(l/i.playbackRate<.5||o.bufferedInPlaceToEnd(i))&&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,i,s,n){if(e.details===L.BUFFER_STALLED_ERROR)return;let a=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&bt(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:s,event:t,schedule:d,scheduleIndex:i,player:l});if(this.hls.trigger(p.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;let u=this.playingAsset,f=this.bufferingAsset,g=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(y=>!y.error))t.error=g;else for(let y=s;y<t.assetList.length;y++)this.resetAssetPlayer(t.assetList[y].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):u&&u.identifier===o?this.advanceAfterAssetEnded(t,i,s):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem,s=this.timelinePos;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${s} playing: ${Oe(i)} error: ${e.error}`),s===-1&&(s=this.hls.startPosition);let a=this.updateItem(i,s);this.itemsMatch(i,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(s===-1){this.checkStart();return}if(!this.schedule)return;let n=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(n)}onAssetListLoaded(e,t){var i,s;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;let c=n.timelineStart,l=n.duration,d=0;o.forEach((y,m)=>{let v=parseFloat(y.DURATION);this.createAsset(n,m,d,c+d,v,y.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 f=(s=this.bufferingItem)==null?void 0:s.event;if(u){var g;let y=this.schedule.findEventIndex(a),m=(g=this.schedule.items)==null?void 0:g[y];if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==y){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(m)}this.setSchedulePosition(y)}else if(f?.identifier===a){let y=n.assetList[0];if(y){let m=this.getAssetPlayer(y.identifier);if(f.appendInPlace){let v=this.primaryMedia;m&&v&&this.bufferAssetPlayer(m,v)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case L.ASSET_LIST_PARSING_ERROR:case L.ASSET_LIST_LOAD_ERROR:case L.ASSET_LIST_LOAD_TIMEOUT:{let i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case L.BUFFER_STALLED_ERROR:{let i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Ya=500,Qn=class extends qt{constructor(e,t,i){super(e,t,i,"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(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=D.IDLE,this.setInterval(Ya),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:i,success:s}=t;if(this.fragContextChanged(i)||(le(i)&&(this.fragPrevious=i),this.state=D.IDLE),!s)return;let n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a,o=i.start;for(let l=0;l<n.length;l++)if(o>=n[l].start&&o<=n[l].end){a=n[l];break}let c=i.start+i.duration;a?a.end=c:(a={start:o,end:c},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){let n=s-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,n,N.SUBTITLE)}}onError(e,t){let i=t.frag;i?.type===N.SUBTITLE&&(t.details===L.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==D.STOPPED&&(this.state=D.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Jo(this.levels,t)){this.levels=t.map(i=>new ft(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{let s=new ft(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,N.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}let s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==D.STOPPED&&this.setInterval(Ya)}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:s,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let 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||(i=c.details)!=null&&i.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?(Ni(a,h),l=a.fragmentStart):u&&(l=u.start,gn(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,gn(a,l))}h&&!this.startFragRequested&&this.setStartPosition(h,l)}c.details=a,this.levelLastLoaded=c,o===s&&(this.hls.trigger(p.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:i}=e,s=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&s!=null&&s.key&&s.iv&&Rt(s.method)){let a=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Tr(s.method)).catch(o=>{throw n.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{let c=performance.now();n.trigger(p.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,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;let{config:s}=this,n=this.getLoadPosition(),a=q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:c}=a,l=i.details,d=this.hls.maxBufferLength+l.levelTargetDuration;if(c>d)return;let h=l.fragments,u=h.length,f=l.edge,g=null,y=this.fragPrevious;if(o<f){let E=s.maxFragLookUpTolerance,T=o>f-E?0:E;g=gt(y,h,Math.max(h[0].start,o),T),!g&&y&&y.start<h[0].start&&(g=h[0])}else g=h[u-1];if(g=this.filterReplacedPrimary(g,i.details),!g)return;let m=g.sn-l.startSN,v=h[m-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,i,o)}}}loadFragment(e,t,i){le(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new zn(this.tracksBuffered[this.currentTrackId]||[])}},zn=class{constructor(e){this.buffered=void 0;let t=(i,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}},lu={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},gl=r=>String.fromCharCode(lu[r]||r),Fe=15,qe=100,cu={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},du={17:2,18:4,21:6,22:8,23:10,19:13,20:15},hu={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},uu={25:2,26:4,29:6,30:8,31:10,27:13,28:15},fu=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Xn=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i=typeof t=="function"?t():t;te.log(`${this.time} [${e}] ${i}`)}}},lt=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},qi=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 i=0;i<t.length;i++){let s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}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}},Zn=class{constructor(){this.uchar=" ",this.penState=new qi}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()}},Jn=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new qi,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<qe;t++)this.chars.push(new Zn);this.logger=e}equals(e){for(let t=0;t<qe;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<qe;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<qe;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>qe&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=qe)}moveCursor(e){let t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=gl(e);if(this.pos>=qe){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<qe;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<qe;i++){let s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},$t=class{constructor(e){this.rows=[],this.currRow=Fe-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Fe;t++)this.rows.push(new Jn(e));this.logger=e}reset(){for(let e=0;e<Fe;e++)this.rows[e].clear();this.currRow=Fe-1}equals(e){let t=!0;for(let i=0;i<Fe;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<Fe;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Fe;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<Fe;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 i=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}let s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+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=[],i="",s=-1;for(let n=0;n<Fe;n++){let a=this.rows[n].getTextString();a&&(s=n+1,e?t.push("Row "+s+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
|
|
30
|
+
`)),i}getTextAndFormat(){return this.rows}},Wi=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new $t(i),this.nonDisplayedMemory=new $t(i),this.lastOutputScreen=new $t(i),this.currRollUpRow=this.displayedMemory.rows[Fe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Fe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{let i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+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))}},ji=class{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=pu(),this.logger=void 0;let s=this.logger=new Xn;this.channels=[null,new Wi(e,t,s),new Wi(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){let s=t[i]&127,n=t[i+1]&127,a=!1,o=null;if(s===0&&n===0)continue;this.logger.log(3,()=>"["+lt([t[i],t[i+1]])+"] -> ("+lt([s,n])+")");let c=this.cmdHistory;if(s>=16&&s<=31){if(gu(s,n,c)){gi(null,null,c),this.logger.log(3,()=>"Repeated command ("+lt([s,n])+") is dropped");continue}gi(s,n,this.cmdHistory),a=this.parseCmd(s,n),a||(a=this.parseMidrow(s,n)),a||(a=this.parsePAC(s,n)),a||(a=this.parseBackgroundAttributes(s,n))}else gi(null,null,c);if(!a&&(o=this.parseChars(s,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 "+lt([s,n])+" orig: "+lt([t[i],t[i+1]]))}}parseCmd(e,t){let i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=33&&t<=35;if(!(i||s))return!1;let n=e===20||e===21||e===23?1:2,a=this.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 i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+lt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i,s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(s||n))return!1;let a=e<=23?1:2;t>=64&&t<=95?i=a===1?cu[e]:hu[e]:i=a===1?du[e]:uu[e];let o=this.channels[a];return o?(o.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let i,s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+gl(a)+"' in channel "+i),s=[a]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+lt(s).join(",")),s}parseBackgroundAttributes(e,t){let i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=fu[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()}gi(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}};function gi(r,e,t){t.a=r,t.b=e}function gu(r,e,t){return t.a===r&&t.b===e}function pu(){return{a:null,b:null}}var Pr=(function(){if(Fi!=null&&Fi.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 i(o){return t(r,o)}function s(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="",f=!1,g=o,y=c,m=l,v=null,E="",T=!0,S="auto",x="start",_=50,b="middle",R=50,I="middle";Object.defineProperty(d,"id",n({},h,{get:function(){return u},set:function(A){u=""+A}})),Object.defineProperty(d,"pauseOnExit",n({},h,{get:function(){return f},set:function(A){f=!!A}})),Object.defineProperty(d,"startTime",n({},h,{get:function(){return g},set:function(A){if(typeof A!="number")throw new TypeError("Start time must be set to a number.");g=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",n({},h,{get:function(){return y},set:function(A){if(typeof A!="number")throw new TypeError("End time must be set to a number.");y=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",n({},h,{get:function(){return m},set:function(A){m=""+A,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",n({},h,{get:function(){return v},set:function(A){v=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",n({},h,{get:function(){return E},set:function(A){let P=i(A);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",n({},h,{get:function(){return T},set:function(A){T=!!A,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",n({},h,{get:function(){return S},set:function(A){if(typeof A!="number"&&A!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",n({},h,{get:function(){return x},set:function(A){let P=s(A);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");x=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",n({},h,{get:function(){return _},set:function(A){if(A<0||A>100)throw new Error("Position must be between 0 and 100.");_=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",n({},h,{get:function(){return b},set:function(A){let P=s(A);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");b=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",n({},h,{get:function(){return R},set:function(A){if(A<0||A>100)throw new Error("Size must be between 0 and 100.");R=A,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",n({},h,{get:function(){return I},set:function(A){let P=s(A);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");I=P,this.hasBeenReset=!0}})),d.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})(),er=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function pl(r){function e(i,s,n,a){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(a||0)}let t=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var tr=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}};function ml(r,e,t,i){let s=i?r.split(i):[r];for(let n in s){if(typeof s[n]!="string")continue;let a=s[n].split(t);if(a.length!==2)continue;let o=a[0],c=a[1];e(o,c)}}var ir=new Pr(0,0,""),pi=ir.align==="middle"?"middle":"center";function mu(r,e,t){let i=r;function s(){let o=pl(r);if(o===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,c){let l=new tr;ml(o,function(u,f){let g;switch(u){case"region":for(let y=t.length-1;y>=0;y--)if(t[y].id===f){l.set(u,t[y].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",pi,"end"]);break;case"position":g=f.split(","),l.percent(u,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",pi,"end","line-left","line-right","auto"]);break;case"size":l.percent(u,f);break;case"align":l.alt(u,f,["start",pi,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let d=l.get("line","auto");d==="auto"&&ir.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",pi);let h=l.get("position","auto");h==="auto"&&ir.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=s(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),a(),e.endTime=s(),a(),n(r,e)}function yl(r){return r.replace(/<br(?: \/)?>/gi,`
|
|
31
|
+
`)}var sr=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new er,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,a=0;for(n=yl(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 s(n){ml(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();let o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=i(),t.state){case"HEADER":/:/.test(n)?s(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new Pr(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{mu(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}},yu=/\r\n|\n\r|\n|\r/g,Gs=function(e,t,i=0){return e.slice(i,i+t.length)===t},vu=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!O(t)||!O(i)||!O(s)||!O(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=3600*1e3*n,t};function Cr(r,e,t){return Ut(r.toString())+Ut(e.toString())+Ut(t)}var Eu=function(e,t,i){let s=e[t],n=e[s.prevCC];if(!n||!n.new&&s.new){e.ccOffset=e.presentationOffset=s.start,s.new=!1;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=s.start-n.start,s.new=!1,s=n,n=e[s.prevCC]}e.presentationOffset=i};function Tu(r,e,t,i,s,n,a){let o=new sr,c=Pe(new Uint8Array(r)).trim().replace(yu,`
|
|
37
|
+
`).split(`
|
|
38
|
+
`),l=[],d=e?Xd(e.baseTime,e.timescale):0,h="00:00.000",u=0,f=0,g,y=!0;o.oncue=function(m){let v=t[i],E=t.ccOffset,T=(u-d)/9e4;if(v!=null&&v.new&&(f!==void 0?E=t.ccOffset=v.start:Eu(t,i,T)),T){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}E=T-t.presentationOffset}let S=m.endTime-m.startTime,x=_e((m.startTime+E-f)*9e4,s*9e4)/9e4;m.startTime=Math.max(x,0),m.endTime=Math.max(x+S,0);let _=m.text.trim();m.text=decodeURIComponent(encodeURIComponent(_)),m.id||(m.id=Cr(m.startTime,m.endTime,_)),m.endTime>0&&l.push(m)},o.onparsingerror=function(m){g=m},o.onflush=function(){if(g){a(g);return}n(l)},c.forEach(m=>{if(y)if(Gs(m,"X-TIMESTAMP-MAP=")){y=!1,m.slice(16).split(",").forEach(v=>{Gs(v,"LOCAL:")?h=v.slice(6):Gs(v,"MPEGTS:")&&(u=parseInt(v.slice(7)))});try{f=vu(h)/1e3}catch(v){g=v}return}else m===""&&(y=!1);o.parse(m+`
|
|
39
|
+
`)}),o.flush()}var Ks="stpp.ttml.im1t",vl=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,El=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Su={left:"start",center:"center",right:"end",start:"start",end:"end"};function qa(r,e,t,i){let s=Q(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let n=s.map(o=>Pe(o)),a=zd(e.baseTime,1,e.timescale);try{n.forEach(o=>t(xu(o,a)))}catch(o){i(o)}}function xu(r,e){let s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((h,u)=>(h[u]=s.getAttribute(`ttp:${u}`)||n[u],h),{}),o=s.getAttribute("xml:space")!=="preserve",c=Wa(Vs(s,"styling","style")),l=Wa(Vs(s,"layout","region")),d=Vs(s,"body","[begin]");return[].map.call(d,h=>{let u=Tl(h,o);if(!u||!h.hasAttribute("begin"))return null;let f=Ys(h.getAttribute("begin"),a),g=Ys(h.getAttribute("dur"),a),y=Ys(h.getAttribute("end"),a);if(f===null)throw ja(h);if(y===null){if(g===null)throw ja(h);y=f+g}let m=new Pr(f-e,y-e,u);m.id=Cr(m.startTime,m.endTime,m.text);let v=l[h.getAttribute("region")],E=c[h.getAttribute("style")],T=bu(v,E,c),{textAlign:S}=T;if(S){let x=Su[S];x&&(m.lineAlign=x),m.align=S}return ie(m,T),m}).filter(h=>h!==null)}function Vs(r,e,t){let i=r.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Wa(r){return r.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Tl(r,e){return[].slice.call(r.childNodes).reduce((t,i,s)=>{var n;return i.nodeName==="br"&&s?t+`
|
|
40
|
+
`:(n=i.childNodes)!=null&&n.length?Tl(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function bu(r,e,t){let i="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,c)=>{let l=Hs(e,i,c)||Hs(r,i,c)||Hs(s,i,c);return l&&(o[c]=l),o},{})}function Hs(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function ja(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Ys(r,e){if(!r)return null;let t=pl(r);return t===null&&(vl.test(r)?t=Au(r,e):El.test(r)&&(t=Lu(r,e))),t}function Au(r,e){let t=vl.exec(r),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function Lu(r,e){let t=El.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}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,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},nr=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=za(),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(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.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"),i=new Lt(this,"textTrack3"),s=new Lt(this,"textTrack4");this.cea608Parser1=new ji(1,e,t),this.cea608Parser2=new ji(3,i,s)}addCues(e,t,i,s,n){let a=!1;for(let o=n.length;o--;){let c=n[o],l=Iu(c[0],c[1],t,i);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),a=!0,l/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,i,s)}else{let o=this.Cues.newCue(null,t,i,s);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n,trackId:a}){let{unparsedVttFrags:o}=this;i===N.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(p.FRAG_LOADED,c):this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){let n=i.textTracks[s];if(Qa(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:i,media:s}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,At(i[e]),hl(i[e],s);else{let c=this.createTextTrack("captions",n,a);c&&(c[e]=!0,i[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){let s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,i)return;let{captionsTracks:s}=this;Object.keys(s).forEach(n=>{At(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=za(),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 i=0;i<t.length;i++)At(t[i])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===Ks);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Jo(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let a=this.media,o=a?bi(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]&&Qa(o[u],c)){h=o[u],o[u]=null;break}h&&(d=h)}if(d)At(d);else{let h=Sl(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(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;let n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===N.MAIN){var i,s;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:l}=t.frag,d=(i=(s=t.part)==null?void 0:s.index)!=null?i:-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:i,payload:s}=t;if(i.type===N.SUBTITLE)if(s.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],c=this.vttCCs;c[i.cc]||(c[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===Ks?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;qa(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{i.logger.log(`Failed to parse IMSC1: ${s}`),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;let{frag:i,payload:s}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}let c=this.hls,l=(t=i.initSegment)!=null&&t.data?we(i.initSegment.data,new Uint8Array(s)).buffer:s;Tu(l,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,d=>{this._appendCues(d,i.level),c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},d=>{let h=d.message==="Missing initPTS for VTT MPEGTS";h?a.push(e):this._fallbackToIMSC1(i,s),c.logger.log(`Failed to parse VTT cue: ${d}`),!(h&&o>i.cc)&&c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:d})})}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||qa(t,this.initPTS[e.cc],()=>{i.textCodec=Ks,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>ul(s,n))}else{let s=this.tracks[t];if(!s)return;let n=s.default?"default":"subtitles"+t;i.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===N.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:s}=t;if(!(i.type===N.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<s.length;n++){let a=s[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(s[n].pts,o[0]),this.cea608Parser2.addData(s[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:n}){let{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(c=>Kn(o[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(c=>Kn(o[c],t,s))}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,s=2;for(let n=0;n<i;n++){let a=e[s++],o=127&e[s++],c=127&e[s++];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 Sl(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function Qa(r,e){return!!r&&r.kind===Sl(e)&&Pn(e,r)}function Iu(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function za(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var Ru=/\s/,_u={newCue(r,e,t,i){let s=[],n,a,o,c,l,d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,c=0,l="",!n.isEmpty()){var h;for(let y=0;y<n.chars.length;y++)Ru.test(n.chars[y].uchar)&&o?c++:(l+=n.chars[y].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;let f=yl(l.trim()),g=Cr(e,t,f);r!=null&&(h=r.cues)!=null&&h.getCueById(g)||(a=new d(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),s.push(a))}return r&&s.length&&(s.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),s.forEach(u=>ul(r,u))),s}};function Du(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Pu=/(\d+)-(\d+)\/(\d+)/,Qi=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||Mu,this.controller=new self.AbortController,this.stats=new Gt}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,i){let s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();let n=Cu(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=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&O(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,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 f=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(f-s.loading.start)),!h.ok){let{status:y,statusText:m}=h;throw new rr(m||"fetch, bad network response",y,h)}s.loading.first=f,s.total=wu(h.headers)||s.total;let g=(u=this.callbacks)==null?void 0:u.onProgress;return g&&O(t.highWaterMark)?this.loadProgressively(h,s,e,t.highWaterMark,g):a?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var u,f;let g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);let y=h[o];y&&(s.loaded=s.total=y);let m={url:g.url,data:h,code:g.status},v=(u=this.callbacks)==null?void 0:u.onProgress;v&&!O(t.highWaterMark)&&v(s,e,h,g),(f=this.callbacks)==null||f.onSuccess(m,s,e,g)}).catch(h=>{var u;if(self.clearTimeout(this.requestTimeout),s.aborted)return;let f=h&&h.code||0,g=h?h.message:null;(u=this.callbacks)==null||u.onError({code:f,text:g},e,h?h.details:null,s)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,n){let a=new Bi,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let d=l.value,h=d.length;return t.loaded+=h,h<s||a.dataLength?(a.push(d),a.dataLength>=s&&n(t,i,a.flush().buffer,e)):n(t,i,d.buffer,e),c()}).catch(()=>Promise.reject());return c()}};function Cu(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 ku(r){let e=Pu.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function wu(r){let e=r.get("Content-Range");if(e){let i=ku(e);if(O(i))return i}let t=r.get("Content-Length");if(t)return parseInt(t)}function Mu(r,e){return new self.Request(r.url,e)}var rr=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Ou=/^age:\s*[\d.]+\s*$/im,zi=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 Gt,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,i){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=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(let o in s)e.setRequestHeader(o,s[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&O(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let s=t.readyState,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let l=t.status,d=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){let g=d??t.response;if(g!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);let y=t.responseType==="arraybuffer"?g.byteLength:g.length;i.loaded=i.total=y,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);let m=(a=this.callbacks)==null?void 0:a.onProgress;m&&m(i,e,g,t);let v={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(v,i,e,t);return}}let h=n.loadPolicy.errorRetry,u=i.retry,f={url:e.url,data:void 0,code:l};if(ki(h,u,!1,f))this.retry(h);else{var c;te.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ki(e,t,!0))this.retry(e);else{var i;te.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Er(e,i.retry),i.retry++,te.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Ou.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}},Fu={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Nu=ee(ee({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:zi,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:tn,bufferController:Mn,capLevelController:On,errorController:nn,fpsController:Gn,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:Lo,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:Fu},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},Bu()),{},{subtitleStreamController:Qn,subtitleTrackController:Vn,timelineController:nr,audioStreamController:Dn,audioTrackController:Cn,emeController:Hi,cmcdController:Un,contentSteeringController:$n,interstitialsController:jn});function Bu(){return{cueHandler:_u,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 Uu(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 i=ar(r),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.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 f=i[o].default;switch(e[o]={default:f},d){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])}`)}),ee(ee({},i),e)}function ar(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(ar):Object.keys(r).reduce((e,t)=>(e[t]=ar(r[t]),e),{}):r}function $u(r,e){let t=r.loader;t!==Qi&&t!==zi?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Du()&&(r.loader=Qi,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Ai=2,Gu=.1,Ku=.05,Vu=100,or=class extends wi{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 i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.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(Vu),this.mediaSource=t.mediaSource;let i=this.media=t.media;Te(i,"playing",this.onMediaPlaying),Te(i,"waiting",this.onMediaWaiting),Te(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(Ae(i,"playing",this.onMediaPlaying),Ae(i,"waiting",this.onMediaWaiting),Ae(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((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 i,s;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,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(p.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,f=this.fragmentTracker;if(o&&f&&this.hls){let _=Xa(this.hls.inFlightFragments,e),b=h.len>Ai,R=!u||_||u-e>Ai&&!f.getPartialFragment(e);if(b||R)return;this.moved=!1}let g=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!u)return;let b=Math.max(u,h.start||0)-e,I=!!(g!=null&&g.live)?g.targetduration*2:Ai,A=mi(e,f);if(b>0&&(b<=I||A)){a.paused||this._trySkipBufferHole(A);return}}let y=n.detectStallWithCurrentTimeMs,m=self.performance.now(),v=this.waiting,E=this.stalled;if(E===null)if(v>0&&m-v<y)E=this.stalled=v;else{this.stalled=m;return}let T=m-E;if(!o&&(T>=y||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(p.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}let x=q.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(x,T,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(p.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;let s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){let n=q.bufferedInfo(q.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=q.timeRangesToArray(s),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=mi(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(p.ERROR,{type:K.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:u,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,i){var s,n;let{fragmentTracker:a,media:o}=this,c=(s=this.hls)==null?void 0:s.config;if(!o||!a||!c)return;let l=(n=this.hls)==null?void 0:n.latestLevelDetails,d=mi(i,a);if((d||l!=null&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;let h=e.buffered,u=this.adjacentTraversal(e,i);(h&&h.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-i<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 i=this.fragmentTracker,s=e.nextStart;if(i&&s){let n=i.getFragAtPos(t,N.MAIN),a=i.getFragAtPos(s,N.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ne(e)})`);this.warn(a.message),t.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;let{fragmentTracker:i,media:s}=this,n=(t=this.hls)==null?void 0:t.config;if(!s||!i||!n)return 0;let a=s.currentTime,o=q.bufferInfo(s,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&&s.readyState<3,u=c-a;if(u>0&&(d||h)){if(u>n.maxBufferHole){let g=!1;if(a===0){let y=i.getAppendedFrag(0,N.MAIN);y&&c<y.end&&(g=!0)}if(!g&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Xa(this.hls.inFlightFragments,c))return 0;let m=!1,v=e.end;for(;v<c;){let E=mi(v,i);if(E)v+=E.duration;else{m=!0;break}}if(m)return 0}}let f=Math.max(c+Ku,a+Gu);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,s.currentTime=f,!(e!=null&&e.gap)){let g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),y={type:K.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?y.part=e:y.frag=e),this.hls.trigger(p.ERROR,y)}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:s}=this,n=t?.config;if(!i||!n)return 0;let a=i.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){let o=a+(s+1)*n.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(c.message),i.currentTime=o,t.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:L.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(p.ERROR,{type:K.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Xa(r,e){let t=Za(r.main);if(t&&t.start<=e)return t;let i=Za(r.audio);return i&&i.start<=e?i:null}function Za(r){if(!r)return null;switch(r.state){case D.IDLE:case D.STOPPED:case D.ENDED:case D.ERROR:return null}return r.frag}function mi(r,e){return e.getAppendedFrag(r,N.MAIN)||e.getPartialFragment(r)}var Hu=.25;function lr(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function qs(r,e,t,i,s){let n=new r(e,t,"");try{n.value=i,s&&(n.type=s)}catch{n=new r(e,t,ne(s?ee({type:s},i):i))}return n}var yi=(()=>{let r=lr();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),cr=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(p.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(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.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 i=e[t];if(i.kind==="metadata"&&i.label==="id3")return hl(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=lr();if(a)for(let o=0;o<n.length;o++){let c=n[o].type;if(c===De.emsg&&!i||!s)continue;let l=Ko(n[o].data),d=n[o].pts,h=d+n[o].duration;h>yi&&(h=yi),h-d<=0&&(h=d+Hu);for(let f=0;f<l.length;f++){let g=l[f];if(!Vo(g)){this.updateId3CueEnds(d,c);let y=qs(a,d,h,g,c);y&&this.id3Track.addCue(y)}}}}updateId3CueEnds(e,t){var i;let s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let n=s.length;n--;){let a=s[n];a.type===t&&a.startTime<e&&a.endTime===yi&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=a;if(n&&(o||c)){let l;s==="audio"?l=d=>d.type===De.audioId3&&c:s==="video"?l=d=>d.type===De.emsg&&o:l=d=>d.type===De.audioId3&&c||d.type===De.emsg&&o,Kn(n,t,i,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:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=lr();if(i&&s&&!a){let{fragmentStart:y,fragmentEnd:m}=e,v=this.assetCue;v?(v.startTime=y,v.endTime=m):o&&(v=this.assetCue=qs(o,y,m,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=i,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 y=Object.keys(h).filter(m=>!d.includes(m));for(let m=y.length;m--;){var f;let v=y[m],E=(f=h[v])==null?void 0:f.cues;delete h[v],E&&Object.keys(E).forEach(T=>{let S=E[T];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(S)}catch{}}})}}else h=this.dateRangeCuesAppended={}}let g=e.fragments[e.fragments.length-1];if(!(d.length===0||!O(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let y=0;y<d.length;y++){let m=d[y],v=l[m],E=v.startTime,T=h[m],S=T?.cues||{},x=T?.durationKnown||!1,_=yi,{duration:b,endDate:R}=v;if(R&&b!==null)_=E+b,x=!0;else if(v.endOnNext&&!x){let A=d.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);A&&(_=A.startTime,x=!0)}let I=Object.keys(v.attr);for(let A=0;A<I.length;A++){let P=I[A];if(!Qc(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];zc(P)&&(B=io(B));let U=qs(o,E,_,{key:P,data:B},De.dateRange);U&&(U.id=m,this.id3Track.addCue(U),S[P]=U,a&&(P==="X-ASSET-LIST"||P==="X-ASSET-URL")&&U.addEventListener("enter",this.onEventCueEnter))}}h[m]={cues:S,dateRange:v,durationKnown:x}}}}},dr=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,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;let s=this.computeLatency();if(s===null)return;this._latency=s;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!i.live)return;let o=this.targetLatency;if(o===null)return;let c=s-o,l=Math.min(this.maxLatency,o+i.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,f=Math.min(h,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:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,c=this.hls.userConfig,l=o&&i||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=n!==void 0?n:a*s);let d=s;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 i=this.levelDetails;if(i===null)return null;let s=i.edge,n=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)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 i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===L.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},hr=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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.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 i=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,c=!1,l=!1;t.levels.forEach(d=>{let h=d.attrs,{audioCodec:u,videoCodec:f}=d;u&&(d.audioCodec=u=Ri(u,i)||void 0),f&&(f=d.videoCodec=Ec(f));let{width:g,height:y,unknownCodecs:m}=d,v=m?.length||0;if(o||(o=!!(g&&y)),c||(c=!!f),l||(l=!!u),v||u&&!this.isAudioSupported(u)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}let{CODECS:E,"FRAME-RATE":T,"HDCP-LEVEL":S,"PATHWAY-ID":x,RESOLUTION:_,"VIDEO-RANGE":b}=h,I=`${`${x||"."}-`}${d.bitrate}-${_}-${T}-${E}-${b}-${S}`;if(n[I])if(n[I].uri!==d.url&&!d.attrs["PATHWAY-ID"]){let A=a[I]+=1;d.attrs["PATHWAY-ID"]=new Array(A+1).join(".");let P=this.createLevel(d);n[I]=P,s.push(P)}else n[I].addGroupId("audio",h.AUDIO),n[I].addGroupId("text",h.SUBTITLES);else{let A=this.createLevel(d);n[I]=A,a[I]=1,s.push(A)}}),this.filterAndSortMediaOptions(s,t,o,c,l)}createLevel(e){let t=new ft(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=go(s,[])}return t}isAudioSupported(e){return Kt(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Kt(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,n){var a;let o=[],c=[],l=e,d=((a=t.stats)==null?void 0:a.parsing)||{};if((i||s)&&n&&(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,_,b)=>b.indexOf(x)===_))}`,this.warn(T),E+=` (${T})`);let S=new Error(E);this.hls.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:L.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:T})}}),d.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(E=>!E.audioCodec||this.isAudioSupported(E.audioCodec)),Ja(o)),t.subtitles&&(c=t.subtitles,Ja(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(i&&E.height!==T.height)return E.height-T.height;if(E.frameRate!==T.frameRate)return E.frameRate-T.frameRate;if(E.videoRange!==T.videoRange)return _i.indexOf(E.videoRange)-_i.indexOf(T.videoRange);if(E.videoCodec!==T.videoCodec){let S=Qr(E.videoCodec),x=Qr(T.videoCodec);if(S!==x)return x-S}if(E.uri===T.uri&&E.codecSet!==T.codecSet){let S=Ii(E.codecSet),x=Ii(T.codecSet);if(S!==x)return x-S}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 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=n&&!s,y=this.hls.config,m=!!(y.audioStreamController&&y.audioTrackController),v={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:m&&!g&&o.some(E=>!!E.url)};d.end=performance.now(),this.hls.trigger(p.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(p.ERROR,{type:K.OTHER_ERROR,details:L.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:d,reason:d.message}),h)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&s&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let 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(p.LEVEL_SWITCHING,c);let l=a.details;if(!l||l.live){let d=this.switchParams(a.uri,s?.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(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===z.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===N.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;let{level:s,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(s,t,c)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(p.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let i=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));wo(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(p.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function Ja(r){let e={};r.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function xl(){return self.SourceBuffer||self.WebKitSourceBuffer}function bl(){if(!it())return!1;let e=xl();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Yu(){if(!bl())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(Vt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(Vt(e,"audio"))))}function qu(){var r;let e=xl();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}var Wu=100,ur=class extends qt{constructor(e,t,i){super(e,t,i,"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 s=this.media,n=s?s.currentTime:null;if(n===null||!O(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(s,n,N.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(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(Wu),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),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,i=e?.[t],s=i?.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))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:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){let y={};this.altAudio===2&&(y.type="video"),this.hls.trigger(p.BUFFER_EOS,y),this.state=D.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===D.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=D.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,f=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&le(f)&&this.fragmentTracker.getState(f)!==de.OK){var g;let m=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,v=l.fragments[m-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 m=this.audioOnly&&!this.altAudio?se.AUDIO:se.VIDEO,v=(m===se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,m,N.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,N.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,u))}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);s===de.NOT_LOADED||s===de.PARTIAL?le(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,N.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.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?i=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:i=0}else i=0;let a=this.getBufferedFrag(t.currentTime+i);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 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 i=t.media;Te(i,"playing",this.onMediaPlaying),Te(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(Ae(i,"playing",this.onMediaPlaying),Ae(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!qu(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==D.IDLE)return;let s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=D.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,c=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);let l=t.levelInfo,d=this.fragCurrent;d&&(this.state===D.FRAG_LOADING||this.state===D.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let h=0;if(o.live||(i=l.details)!=null&&i.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(p.LEVEL_UPDATED,{details:o,level:a}),this.state===D.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=D.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let s=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,c=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!c)){let d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&i.readyState<4||n<o-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;let h=q.bufferInfo(i,s,0);if(!((l=h.buffered)!=null&&l.length)){i.currentTime=s;return}if(h.start<=n){i.currentTime=s;return}let{nextStart:f}=q.bufferedInfo(h.buffered,n,0);f&&(i.currentTime=f)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}let c=o.details;if(!c){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let l=o.videoCodec,d=c.PTSKnown||!c.live,h=(t=i.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Ki(this.hls,N.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,y=g!==-1,m=new Yt(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,y),v=this.initPTS[i.cc];f.push(n,h,u,l,i,s,c.totalduration,d,m,v)}onAudioTrackSwitching(e,t){let i=this.hls,s=this.altAudio!==0;if(Pi(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(p.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(p.AUDIO_TRACK_SWITCHED,t)}),i.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=Pi(t.url,this.hls);if(i){let s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){let i=t.tracks,s,n,a=!1;for(let o in i){let c=i[o];if(c.id==="main"){if(n=o,s=c,o==="video"){let l=i[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:s}=t,n=i.type===N.MAIN;if(n){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===D.PARSED&&(this.state=D.IDLE);return}let o=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),le(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}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 i;if(t.fatal){this.state=D.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(N.MAIN,t);break;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===D.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===z.LEVEL&&(this.state=D.IDLE);break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=D.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==se.AUDIO||!this.altAudio){let i=(t===se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,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,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let s=this.timelineOffset;s&&i&&(i+=s);let n=this.getLevelDetails(),a=q.getBuffered(e),o=a.length?a.start(0):0,c=o-i,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`),i+=c,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{let{hls:s}=this,n=i?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=D.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(p.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===D.STOPPED||this.state===D.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:c,level:l}=a,{video:d,text:h,id3:u,initSegment:f}=s,{details:g}=l,y=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=D.PARSING,f){let m=f.tracks;if(m){let S=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,m,S,n),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:m})}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},i.trigger(p.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:E,trackId:S})}}if(d&&g){y&&d.type==="audiovideo"&&this.logMuxedErr(o);let m=g.fragments[o.sn-1-g.startSN],v=o.sn===g.startSN,E=!m||o.cc>m.cc;if(s.independent!==!1){let{startPTS:T,endPTS:S,startDTS:x,endDTS:_}=d;if(c)c.elementaryStreams[d.type]={startPTS:T,endPTS:S,startDTS:x,endDTS:_};else if(d.firstKeyFrame&&d.independent&&n.id===1&&!E&&(this.couldBacktrack=!0),d.dropped&&d.independent){let b=this.getMainFwdBufferInfo(),R=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,I=d.firstKeyFramePTS?d.firstKeyFramePTS:T;if(!v&&R<I-this.config.maxBufferHole&&!E){this.backtrack(o);return}else E&&(o.gap=!0);o.setElementaryStreamInfo(d.type,o.start,S,o.start,_,!0)}else v&&T-(g.appliedTimelineOffset||0)>Ai&&(o.gap=!0);o.setElementaryStreamInfo(d.type,T,S,x,_),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(y){let{startPTS:m,endPTS:v,startDTS:E,endDTS:T}=y;c&&(c.elementaryStreams[se.AUDIO]={startPTS:m,endPTS:v,startDTS:E,endDTS:T}),o.setElementaryStreamInfo(se.AUDIO,m,v,E,T),this.bufferFragmentData(y,o,c,n)}if(g&&u!=null&&u.samples.length){let m={id:t,frag:o,details:g,samples:u.samples};i.trigger(p.FRAG_PARSING_METADATA,m)}if(g&&h){let m={id:t,frag:o,details:g,samples:h.samples};i.trigger(p.FRAG_PARSING_USERDATA,m)}}logMuxedErr(e){this.warn(`${le(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==D.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec,d=vi(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=N.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=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(p.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{let h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:h,frag:i,part:null,chunkMeta:s,parent:i.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,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=D.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(q.isBuffered(e,i)?t=this.getAppendedFrag(i):q.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(p.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 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 i=this.getLevelDetails(),s=this.currentFrag||(i?gt(null,i.fragments,t):null);if(s){let n=s.programDateTime;if(n!==null){let a=n+(t-s.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},fr=class extends Le{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyIdToKeyInfo){let s=this.keyIdToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.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=L.KEY_LOAD_ERROR,i,s,n){return new Ne({type:K.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,n=t.length;s<n;s++){let a=t[s];if(e.cc<=a.cc&&(!le(e)||!le(a)||e.sn<a.sn)||!i&&s==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let c=Ti(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){let s=Ft(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;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,L.KEY_LOAD_ERROR,l))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=Ws(n),c=this.keyIdToKeyInfo[o];if((i=c)!=null&&i.decryptdata.key)return n.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(s=c)!=null&&s.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: "+pe(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,L.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&(s=t.initSegment)!=null&&s.data){let a=oc(t.initSegment.data);if(a.length){let o=a[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${pe(o)}`),Ct.setKeyIdForUri(e.decryptdata.uri,o)):(o=Ct.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${pe(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!le(t))return Promise.resolve(i);let n=this.emeController.loadKey(i);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,s=i.loader,n=new s(i);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=i.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,y)=>{let{frag:m,keyInfo:v}=g,E=Ws(v.decryptdata);if(!m.decryptdata||v!==this.keyIdToKeyInfo[E])return o(this.createKeyLoadError(m,L.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),y));v.decryptdata.key=m.decryptdata.key=new Uint8Array(u.data),m.keyLoader=null,v.loader=null,a({frag:m,keyInfo:v})},onError:(u,f,g,y)=>{this.resetLoader(f),o(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),g,ee({url:c.url,data:void 0},u)))},onTimeout:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,L.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,L.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};n.load(c,d,h)})}resetLoader(e){let{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);let a=Ws(i.decryptdata)||s;delete this.keyIdToKeyInfo[a],n&&n.destroy()}};function Ws(r){if(r.keyFormat!==me.FAIRPLAY){let e=r.keyId;if(e)return pe(e)}return r.uri}function eo(r){let{type:e}=r;switch(e){case z.AUDIO_TRACK:return N.AUDIO;case z.SUBTITLE_TRACK:return N.SUBTITLE;default:return N.MAIN}}function js(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var gr=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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:z.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:c}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:z.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){let{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:z.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:z.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let i=this.loaders[z.LEVEL];if(i){let s=i.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[z.LEVEL])}}load(e){var t;let i=this.hls.config,s=this.getInternalLoader(e);if(s){let l=this.hls.logger,d=s.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}`),s.abort()}let n;if(e.type===z.MANIFEST?n=i.manifestLoadPolicy.default:n=ie({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),O((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===z.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===z.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===z.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 f=this.getInternalLoader(h);this.resetInternalLoader(h.type);let g=l.data;d.parsing.start=performance.now(),dt.isMediaPlaylist(g)||h.type!==z.MANIFEST?this.handleTrackOrLevelPlaylist(l,d,h,u||null,f):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)}};s.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){let n=this.hls,a=e.data,o=js(e,i),c=dt.parseMasterPlaylist(a,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,c.playlistParsingError,s,t);return}let{contentSteering:l,levels:d,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g}=c;this.variableList=g,d.forEach(E=>{let{unknownCodecs:T}=E;if(T){let{preferManagedMediaSource:S}=this.hls.config,{audioCodec:x,videoCodec:_}=E;for(let b=T.length;b--;){let R=T[b];Kt(R,"audio",S)?(E.audioCodec=x=x?`${x},${R}`:R,Pt.audio[x.substring(0,4)]=2,T.splice(b,1)):Kt(R,"video",S)&&(E.videoCodec=_=_?`${_},${R}`:R,Pt.video[_.substring(0,4)]=2,T.splice(b,1))}}});let{AUDIO:y=[],SUBTITLES:m,"CLOSED-CAPTIONS":v}=dt.parseMasterPlaylistMedia(a,o,c);y.length&&!y.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"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new re({}),bitrate:0,url:""})),n.trigger(p.MANIFEST_LOADED,{levels:d,audioTracks:y,subtitles:m,captions:v,contentSteering:l,url:o,stats:t,networkDetails:s,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,s,n){let a=this.hls,{id:o,level:c,type:l}=i,d=js(e,i),h=O(c)?c:O(o)?o:0,u=eo(i),f=dt.parseLevelPlaylist(e.data,d,h,u,0,this.variableList);if(l===z.MANIFEST){let g={attrs:new re({}),bitrate:0,details:f,name:"",url:d};f.requestScheduled=t.loading.start+Po(f,0),a.trigger(p.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(p.ERROR,{type:K.NETWORK_ERROR,details:L.MANIFEST_PARSING_ERROR,fatal:t.type===z.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===z.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===z.AUDIO_TRACK||e.type===z.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=L.UNKNOWN,l=!1,d=this.getInternalLoader(e);switch(e.type){case z.MANIFEST:c=i?L.MANIFEST_LOAD_TIMEOUT:L.MANIFEST_LOAD_ERROR,l=!0;break;case z.LEVEL:c=i?L.LEVEL_LOAD_TIMEOUT:L.LEVEL_LOAD_ERROR,l=!1;break;case z.AUDIO_TRACK:c=i?L.AUDIO_TRACK_LOAD_TIMEOUT:L.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case z.SUBTITLE_TRACK:c=i?L.SUBTITLE_TRACK_LOAD_TIMEOUT:L.SUBTITLE_LOAD_ERROR,l=!1;break}d&&this.resetInternalLoader(e.type);let h={type:K.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:d,context:e,error:o,networkDetails:t,stats:n};if(s){let u=t?.url||e.url;h.response=ee({url:u,data:void 0},s)}this.hls.trigger(p.ERROR,h)}handlePlaylistLoaded(e,t,i,s,n,a){let o=this.hls,{type:c,level:l,levelOrTrack:d,id:h,groupId:u,deliveryDirectives:f}=s,g=js(t,s),y=eo(s),m=typeof s.level=="number"&&y===N.MAIN?l:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(p.ERROR,{type:K.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:v,reason:v.message,response:t,context:s,level:m,parent:y,networkDetails:n,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){let E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(p.ERROR,{type:K.NETWORK_ERROR,details:L.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:s,level:m,parent:y,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case z.MANIFEST:case z.LEVEL:if(m){if(!d)m=0;else if(d!==o.levels[m]){let E=o.levels.indexOf(d);E>-1&&(m=E)}}o.trigger(p.LEVEL_LOADED,{details:e,levelInfo:d||o.levels[0],level:m||0,id:h||0,stats:i,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:c===z.MANIFEST});break;case z.AUDIO_TRACK:o.trigger(p.AUDIO_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:f});break;case z.SUBTITLE_TRACK:o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:f});break}}},Ie=class r{static get version(){return Wt}static isMSESupported(){return bl()}static isSupported(){return Yu()}static getMediaSource(){return it()}static get Events(){return p}static get MetadataSchema(){return De}static get ErrorTypes(){return K}static get ErrorDetails(){return L}static get DefaultConfig(){return r.defaultConfig?r.defaultConfig:Nu}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 xr,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=zl(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=Uu(r.DefaultConfig,e,t);this.userConfig=e,i.progressive&&$u(i,t);let{abrController:s,bufferController:n,capLevelController:a,errorController:o,fpsController:c}=i,l=new o(this),d=this.abrController=new s(this),h=new rn(this),u=i.interstitialsController,f=u?this.interstitialsController=new u(this,r):null,g=this.bufferController=new n(this,h),y=this.capLevelController=new a(this),m=new c(this),v=new gr(this),E=i.contentSteeringController,T=E?new E(this):null,S=this.levelController=new hr(this,T),x=new cr(this),_=new fr(this.config,this.logger),b=this.streamController=new ur(this,h,_),R=this.gapController=new or(this,h);y.setStreamController(b),m.setStreamController(b);let I=[v,S,b];f&&I.splice(1,0,f),T&&I.splice(1,0,T),this.networkControllers=I;let A=[d,g,R,y,m,x,h];this.audioTrackController=this.createController(i.audioTrackController,I);let P=i.audioStreamController;P&&I.push(this.audioStreamController=new P(this,h,_)),this.subtitleTrackController=this.createController(i.subtitleTrackController,I);let M=i.subtitleStreamController;M&&I.push(this.subtititleStreamController=new M(this,h,_)),this.createController(i.timelineController,A),_.emeController=this.emeController=this.createController(i.emeController,A),this.cmcdController=this.createController(i.cmcdController,A),this.latencyController=this.createController(dr,A),this.coreComponents=A,I.push(l);let B=l.onErrorOut;typeof B=="function"&&this.on(p.ERROR,B,l),this.on(p.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;let s=e===p.ERROR;this.trigger(p.ERROR,{type:K.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(p.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(p.ERROR,{type:K.OTHER_ERROR,details:L.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(p.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(p.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,i=this._url,s=this._url=pr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}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=ru()),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){_c(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get 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 i=yo(t);return po(e,i,navigator.mediaCapabilities)}};Ie.defaultConfig=void 0;var es=class{constructor(e,t){this.hls=null;this.video=null;this.levels=[];this.listeners=new Map;this.statsTimer=null;this.apiKey=e?.apiKey,this.embedToken=e?.embedToken,this.hlsConfigOverrides=t}load(e,t){this.destroy(),this.video=t;let i=null;try{i=new URL(e,window.location.href).origin}catch{}let s={...Kr,...this.hlsConfigOverrides};if(this.apiKey||this.embedToken){let n=this.apiKey,a=this.embedToken;s.xhrSetup=(o,c)=>{try{let l=new URL(c,e),d=i!==null&&l.origin===i;n&&d?o.setRequestHeader("X-API-Key",n):a&&d&&(l.searchParams.set("token",a),o.open("GET",l.toString(),!0))}catch{}}}this.hls=new Ie(s),this.hls.on(Ie.Events.MANIFEST_PARSED,(n,a)=>{this.levels=a.levels.map((o,c)=>({index:c,height:o.height,width:o.width,bitrate:o.bitrate,label:`${o.height}p`,active:c===this.hls.currentLevel})),this.fire("qualitylevels",this.levels)}),this.hls.on(Ie.Events.LEVEL_SWITCHED,(n,a)=>{this.levels=this.levels.map(c=>({...c,active:c.index===a.level}));let o=this.levels[a.level];o&&this.fire("qualitychange",o),this.fireStats({kind:"level_switch",level:a.level,bandwidthEstimate:this.hls?.bandwidthEstimate})}),this.hls.on(Ie.Events.ERROR,(n,a)=>{if(this.fireStats({kind:"hls_error",fatal:a.fatal,errorType:a.type,errorDetails:a.details,bandwidthEstimate:this.hls?.bandwidthEstimate}),a.fatal)switch(a.type){case Ie.ErrorTypes.NETWORK_ERROR:this.hls.startLoad();break;case Ie.ErrorTypes.MEDIA_ERROR:this.hls.recoverMediaError();break;default:this.fire("error",{code:a.type,message:a.details||"Fatal playback error"});break}}),this.hls.on(Ie.Events.FRAG_BUFFERED,(n,a)=>{this.fire("buffering",!1);let o=a??{},c=o.stats?.loading?.start??0,l=o.stats?.loading?.end??0;this.fireStats({kind:"fragment",bandwidthEstimate:this.hls?.bandwidthEstimate,fragmentDuration:o.frag?.duration,fragmentSizeBytes:o.stats?.total,fragmentLoadMs:l>c?l-c:void 0})}),this.hls.on(Ie.Events.FRAG_LOADED,(n,a)=>{let o=a.networkDetails;o&&typeof o.getResponseHeader=="function"&&this.fireStats({kind:"fragment",cdnNode:o.getResponseHeader("X-Amz-Cf-Pop")||o.getResponseHeader("X-Edge-Location")||void 0,cdnCacheStatus:o.getResponseHeader("X-Cache")||void 0,cdnRequestID:o.getResponseHeader("X-Amz-Cf-Id")||void 0,bandwidthEstimate:this.hls?.bandwidthEstimate})}),this.hls.loadSource(e),this.hls.attachMedia(t),this.statsTimer=setInterval(()=>{if(!this.video)return;let n=this.video;if(typeof n.getVideoPlaybackQuality=="function"){let a=n.getVideoPlaybackQuality();this.fireStats({kind:"periodic",droppedFrames:a.droppedVideoFrames,totalFrames:a.totalVideoFrames,bandwidthEstimate:this.hls?.bandwidthEstimate})}else typeof n.webkitDroppedFrameCount=="number"&&this.fireStats({kind:"periodic",droppedFrames:n.webkitDroppedFrameCount,bandwidthEstimate:this.hls?.bandwidthEstimate})},1e4)}destroy(){this.statsTimer&&(clearInterval(this.statsTimer),this.statsTimer=null),this.hls&&(this.hls.destroy(),this.hls=null),this.video=null,this.levels=[]}getQualityLevels(){return this.levels}setQualityLevel(e){this.hls&&(this.hls.currentLevel=e)}getCurrentQuality(){return this.hls?.currentLevel??-1}isAutoQuality(){return this.hls?.autoLevelEnabled??!0}setAutoQuality(){this.hls&&(this.hls.currentLevel=-1)}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}fire(e,...t){let i=this.listeners.get(e);if(i)for(let s of i)s(...t)}fireStats(e){this.fire("stats",{...e,statsSource:"hlsjs"})}};var ts=class{constructor(){this.video=null;this.listeners=new Map;this.statsTimer=null;this.lastResourceIndex=0;this.sourceHost=null}load(e,t){this.destroy(),this.video=t;try{let i=new URL(e,window.location.href);this.sourceHost=i.host}catch{this.sourceHost=null}t.src=e,t.addEventListener("loadedmetadata",()=>{this.fire("qualitylevels",[])}),t.addEventListener("error",()=>{let i=t.error;this.fire("error",{code:`MEDIA_ERR_${i?.code??0}`,message:i?.message??"Native playback error"})}),this.statsTimer=setInterval(()=>{this.scavengeStats()},1e4)}destroy(){this.statsTimer&&(clearInterval(this.statsTimer),this.statsTimer=null),this.video&&(this.video.removeAttribute("src"),this.video.load(),this.video=null)}scavengeStats(){if(!this.video)return;let e=this.video,t,i;if(typeof e.getVideoPlaybackQuality=="function"){let s=e.getVideoPlaybackQuality();t=s.droppedVideoFrames,i=s.totalVideoFrames}else typeof e.webkitDroppedFrameCount=="number"&&(t=e.webkitDroppedFrameCount);if(typeof performance<"u"&&typeof performance.getEntriesByType=="function"){let s=performance.getEntriesByType("resource");for(let n=this.lastResourceIndex;n<s.length;n++){let a=s[n];if(!this.isVideoFragment(a.name))continue;let c=!(this.sourceHost!==null&&!a.name.includes(window.location.host))||a.transferSize>0||a.responseStart>0;this.fire("stats",{kind:"fragment",statsSource:"native_resource_timing",fragmentLoadMs:Math.round(a.duration),fragmentSizeBytes:c&&a.transferSize>0?a.transferSize:void 0,bandwidthEstimate:c&&a.transferSize>0&&a.duration>0?Math.round(a.transferSize*8/(a.duration/1e3)):void 0,taoAvailable:c})}this.lastResourceIndex=s.length}this.fire("stats",{kind:"periodic",statsSource:"native_resource_timing",droppedFrames:t,totalFrames:i})}isVideoFragment(e){if(this.sourceHost)try{if(new URL(e,window.location.href).host!==this.sourceHost)return!1}catch{return!1}let t=e.split("?")[0];return t.endsWith(".ts")||t.endsWith(".m4s")||t.endsWith(".m4v")||t.includes("/seg-")||t.includes("/segment")}getQualityLevels(){return[]}setQualityLevel(e){}getCurrentQuality(){return-1}isAutoQuality(){return!0}setAutoQuality(){}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}fire(e,...t){let i=this.listeners.get(e);if(i)for(let s of i)s(...t)}};function Al(){return typeof document>"u"?!1:document.createElement("video").canPlayType("application/vnd.apple.mpegurl")!==""}function Ll(){if(typeof document>"u")return!1;let r=document.documentElement;return!!(r.requestFullscreen||r.webkitRequestFullscreen)}function Il(r,e){let t=typeof r=="string"?{apiKey:r}:r??{};if(Ie.isSupported())return new es(t,e);if(Al())return new ts;throw new Error("HLS playback is not supported in this browser")}var is=class{constructor(e,t){typeof e=="string"?(this.apiKey=e,this.baseUrl=(t??Xe.apiBaseUrl).replace(/\/$/,"")):(this.apiKey=e.apiKey,this.embedToken=e.embedToken,this.baseUrl=(e.baseUrl??Xe.apiBaseUrl).replace(/\/$/,""))}buildUrl(e){let t=new URL(`${this.baseUrl}${e}`);return this.embedToken&&t.searchParams.set("token",this.embedToken),t.toString()}getHeaders(){let e={Accept:"application/json"};return this.apiKey&&(e["X-API-Key"]=this.apiKey),e}async getVideoMetadata(e){let t=this.embedToken?`/v1/videos/embed/${e}/metadata`:`/v1/videos/${e}`,i=await fetch(this.buildUrl(t),{headers:this.getHeaders()});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`Failed to load video ${e}: ${i.status} ${n}`)}let s=await i.json();return{id:s.id,title:s.title??"",duration:s.duration??0,poster:s.poster_url??s.thumbnail_url,playlistUrl:s.playlist_url,qualities:(s.qualities??[]).map((n,a)=>({index:a,height:n.height,width:n.width,bitrate:n.bitrate,label:`${n.height}p`,active:!1}))}}async trackPlayback(e,t,i){let s=this.embedToken?`/v1/videos/embed/${e}/track`:`/v1/videos/${e}/track`,n=await fetch(this.buildUrl(s),{method:"POST",headers:{...this.getHeaders(),"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:i?.keepalive??!1});if(!n.ok){let a=await n.text().catch(()=>"");throw new Error(`Failed to track playback for ${e}: ${n.status} ${a}`)}}};var Qe=r=>`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">${r}</svg>`,Rl=r=>`<svg viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${r}</svg>`,Se={play:Rl('<path d="M6.906 4.537A.6.6 0 0 0 6 5.053v13.894a.6.6 0 0 0 .906.516l11.723-6.947a.6.6 0 0 0 0-1.032L6.906 4.537Z"/>'),pause:Rl('<rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/>'),volumeHigh:Qe('<path d="M11 5L6 9H2v6h4l5 4V5z"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>'),volumeLow:Qe('<path d="M11 5L6 9H2v6h4l5 4V5z"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>'),volumeMuted:Qe('<path d="M11 5L6 9H2v6h4l5 4V5z"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/>'),fullscreen:Qe('<path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/>'),fullscreenExit:Qe('<path d="M8 3v3a2 2 0 0 1-2 2H3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/><path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M16 21v-3a2 2 0 0 1 2-2h3"/>'),settings:Qe('<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>'),replay:Qe('<polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>'),chevronLeft:Qe('<polyline points="15 18 9 12 15 6"/>'),check:Qe('<polyline points="20 6 9 17 4 12"/>')};function kr(r,e,t){let i=document.createElement(r);if(e)for(let[s,n]of Object.entries(e))i.setAttribute(s,n);if(t)for(let s of t)typeof s=="string"?i.appendChild(document.createTextNode(s)):i.appendChild(s);return i}function xe(r,e){let t=document.createElement("span");return t.className=e?`gallop-icon ${e}`:"gallop-icon",t.innerHTML=r,t.setAttribute("aria-hidden","true"),t}var ss=class{constructor(e){this.dragging=!1;this.onMouseDown=e=>{e.preventDefault(),this.dragging=!0,this.seekToPosition(e.clientX);let t=s=>this.seekToPosition(s.clientX),i=()=>{this.dragging=!1,document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",t),document.addEventListener("mouseup",i)};this.onTouchStart=e=>{e.preventDefault(),this.dragging=!0;let t=e.touches[0];this.seekToPosition(t.clientX);let i=n=>this.seekToPosition(n.touches[0].clientX),s=()=>{this.dragging=!1,document.removeEventListener("touchmove",i),document.removeEventListener("touchend",s)};document.addEventListener("touchmove",i),document.addEventListener("touchend",s)};this.player=e,this.element=document.createElement("div"),this.element.className="gallop-progress-container",this.bar=document.createElement("div"),this.bar.className="gallop-progress-bar",this.buffered=document.createElement("div"),this.buffered.className="gallop-progress-buffered",this.played=document.createElement("div"),this.played.className="gallop-progress-played",this.thumb=document.createElement("div"),this.thumb.className="gallop-progress-thumb",this.bar.appendChild(this.buffered),this.bar.appendChild(this.played),this.bar.appendChild(this.thumb),this.element.appendChild(this.bar),this.element.addEventListener("mousedown",this.onMouseDown),this.element.addEventListener("touchstart",this.onTouchStart,{passive:!1})}update(e,t,i){if(this.dragging||!t)return;let s=e/t*100;if(this.played.style.width=`${s}%`,this.thumb.style.left=`${s}%`,i.length>0){let n=i.end(i.length-1);this.buffered.style.width=`${n/t*100}%`}}seekToPosition(e){let t=this.bar.getBoundingClientRect(),i=Math.max(0,Math.min(1,(e-t.left)/t.width)),s=i*this.player.duration;this.player.seek(s),this.played.style.width=`${i*100}%`,this.thumb.style.left=`${i*100}%`}destroy(){this.element.removeEventListener("mousedown",this.onMouseDown),this.element.removeEventListener("touchstart",this.onTouchStart)}};var ns=class{constructor(e){this.onSliderMouseDown=e=>{e.preventDefault(),e.stopPropagation(),this.setVolumeFromX(e.clientX);let t=s=>this.setVolumeFromX(s.clientX),i=()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",t),document.addEventListener("mouseup",i)};this.player=e,this.element=document.createElement("div"),this.element.className="gallop-volume",this.muteBtn=document.createElement("button"),this.muteBtn.className="gallop-btn",this.muteBtn.setAttribute("aria-label","Mute"),this.iconHigh=xe(Se.volumeHigh),this.iconLow=xe(Se.volumeLow),this.iconMuted=xe(Se.volumeMuted),this.muteBtn.appendChild(this.iconHigh),this.muteBtn.addEventListener("click",t=>{t.stopPropagation(),e.toggleMute()}),this.sliderWrap=document.createElement("div"),this.sliderWrap.className="gallop-volume-slider-wrap",this.slider=document.createElement("div"),this.slider.className="gallop-volume-slider",this.fill=document.createElement("div"),this.fill.className="gallop-volume-fill",this.fill.style.width=`${e.volume*100}%`,this.slider.appendChild(this.fill),this.sliderWrap.appendChild(this.slider),this.element.appendChild(this.muteBtn),this.element.appendChild(this.sliderWrap),this.slider.addEventListener("mousedown",this.onSliderMouseDown)}update(e,t){let i=t?0:e;this.fill.style.width=`${i*100}%`,this.muteBtn.innerHTML="",t||e===0?this.muteBtn.appendChild(this.iconMuted.cloneNode(!0)):e<.5?this.muteBtn.appendChild(this.iconLow.cloneNode(!0)):this.muteBtn.appendChild(this.iconHigh.cloneNode(!0))}setVolumeFromX(e){let t=this.slider.getBoundingClientRect(),i=Math.max(0,Math.min(1,(e-t.left)/t.width));this.player.volume=i,this.player.muted&&i>0&&(this.player.muted=!1)}destroy(){this.slider.removeEventListener("mousedown",this.onSliderMouseDown)}};function wr(r){if(!isFinite(r)||r<0)return"0:00";let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return e>0?`${e}:${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`:`${t}:${i.toString().padStart(2,"0")}`}function Mr(r,e,t){return Math.min(Math.max(r,e),t)}var rs=class{constructor(){this.currentTime=0;this.duration=0;this.element=document.createElement("span"),this.element.className="gallop-time",this.render()}update(e,t){this.currentTime=e,this.duration=t,this.render()}render(){this.element.textContent=`${wr(this.currentTime)} / ${wr(this.duration)}`}};var as=class{constructor(e){this.currentView="main";this.qualityLevels=[];this.player=e,this.button=document.createElement("button"),this.button.className="gallop-btn",this.button.setAttribute("aria-label","Settings"),this.button.appendChild(xe(Se.settings)),this.button.addEventListener("click",t=>{t.stopPropagation(),this.toggle()}),this.element=document.createElement("div"),this.element.className="gallop-settings-menu",this.element.hidden=!0,this.element.addEventListener("click",t=>t.stopPropagation()),this.renderMain()}setQualityLevels(e){this.qualityLevels=e,this.currentView==="quality"?this.renderQuality():this.currentView==="main"&&this.renderMain()}toggle(){this.element.hidden?(this.currentView="main",this.renderMain(),this.element.hidden=!1):this.element.hidden=!0}close(){this.element.hidden=!0,this.currentView="main"}renderMain(){this.element.innerHTML="";let e=this.createItem("Quality",this.getQualityLabel());e.addEventListener("click",()=>{this.currentView="quality",this.renderQuality()});let t=this.createItem("Speed",this.getSpeedLabel());t.addEventListener("click",()=>{this.currentView="speed",this.renderSpeed()}),this.element.appendChild(e),this.element.appendChild(t)}renderQuality(){this.element.innerHTML="";let e=this.createHeader("Quality");this.element.appendChild(e);let t=this.createSelectItem("Auto",this.player.isAutoQuality());t.addEventListener("click",()=>{this.player.setAutoQuality(),this.close()}),this.element.appendChild(t);let i=[...this.qualityLevels].sort((s,n)=>n.height-s.height);for(let s of i){let n=this.createSelectItem(s.label,!this.player.isAutoQuality()&&s.index===this.player.getCurrentQuality());n.addEventListener("click",()=>{this.player.setQualityLevel(s.index),this.close()}),this.element.appendChild(n)}}renderSpeed(){this.element.innerHTML="";let e=this.createHeader("Speed");this.element.appendChild(e);for(let t of ti){let i=t===1?"Normal":`${t}x`,s=this.createSelectItem(i,this.player.playbackRate===t);s.addEventListener("click",()=>{this.player.playbackRate=t,this.close()}),this.element.appendChild(s)}}createItem(e,t){let i=document.createElement("div");i.className="gallop-settings-item";let s=document.createElement("span");s.textContent=e;let n=document.createElement("span");return n.className="gallop-settings-value",n.textContent=t,i.appendChild(s),i.appendChild(n),i}createSelectItem(e,t){let i=document.createElement("div");if(i.className="gallop-settings-item"+(t?" gallop-settings-item-active":""),t)i.appendChild(xe(Se.check));else{let n=document.createElement("span");n.className="gallop-icon",i.appendChild(n)}let s=document.createElement("span");return s.textContent=e,i.appendChild(s),i}createHeader(e){let t=document.createElement("div");t.className="gallop-settings-header",t.appendChild(xe(Se.chevronLeft));let i=document.createElement("span");return i.textContent=e,t.appendChild(i),t.addEventListener("click",()=>{this.currentView="main",this.renderMain()}),t}getQualityLabel(){if(this.player.isAutoQuality()){let i=this.player.getCurrentQuality(),s=this.qualityLevels.find(n=>n.index===i);return s?`Auto (${s.height}p)`:"Auto"}let e=this.player.getCurrentQuality();return this.qualityLevels.find(i=>i.index===e)?.label??"Auto"}getSpeedLabel(){let e=this.player.playbackRate;return e===1?"Normal":`${e}x`}};var os=class{constructor(e,t){this.fullscreenBtn=null;this.hideTimer=null;this.onActivity=()=>{this.showControls(),this.startHideTimer()};this.player=e,this.wrapper=t,this.element=document.createElement("div"),this.element.className="gallop-controls",this.playIcon=xe(Se.play),this.pauseIcon=xe(Se.pause),this.fsEnterIcon=xe(Se.fullscreen),this.fsExitIcon=xe(Se.fullscreenExit),this.progressBar=new ss(e);let i=document.createElement("div");i.className="gallop-controls-row",this.playPauseBtn=document.createElement("button"),this.playPauseBtn.className="gallop-btn",this.playPauseBtn.setAttribute("aria-label","Play"),this.playPauseBtn.appendChild(this.playIcon.cloneNode(!0)),this.playPauseBtn.addEventListener("click",n=>{n.stopPropagation(),e.togglePlay()}),i.appendChild(this.playPauseBtn),this.timeDisplay=new rs,i.appendChild(this.timeDisplay.element),i.appendChild(this.progressBar.element),this.volumeControl=new ns(e),i.appendChild(this.volumeControl.element),this.settingsMenu=new as(e);let s=document.createElement("div");s.style.position="relative",s.appendChild(this.settingsMenu.element),s.appendChild(this.settingsMenu.button),i.appendChild(s),Ll()&&(this.fullscreenBtn=document.createElement("button"),this.fullscreenBtn.className="gallop-btn",this.fullscreenBtn.setAttribute("aria-label","Fullscreen"),this.fullscreenBtn.appendChild(this.fsEnterIcon.cloneNode(!0)),this.fullscreenBtn.addEventListener("click",n=>{n.stopPropagation(),e.toggleFullscreen()}),i.appendChild(this.fullscreenBtn)),this.element.appendChild(i),this.bindEvents(),this.startHideTimer()}bindEvents(){this.player.on("timeupdate",({currentTime:e,duration:t})=>{this.timeDisplay.update(e,t),this.progressBar.update(e,t,this.player.buffered)}),this.player.on("volumechange",({volume:e,muted:t})=>{this.volumeControl.update(e,t)}),this.player.on("play",()=>this.updatePlayPause(!0)),this.player.on("pause",()=>this.updatePlayPause(!1)),this.player.on("ended",()=>this.updatePlayPause(!1)),this.player.on("qualitylevels",({levels:e})=>{this.settingsMenu.setQualityLevels(e)}),this.player.on("fullscreenchange",({isFullscreen:e})=>{this.fullscreenBtn&&(this.fullscreenBtn.innerHTML="",this.fullscreenBtn.appendChild(e?this.fsExitIcon.cloneNode(!0):this.fsEnterIcon.cloneNode(!0)))}),this.wrapper.addEventListener("mousemove",this.onActivity),this.wrapper.addEventListener("mouseenter",this.onActivity),this.wrapper.addEventListener("mouseleave",()=>this.hideControls()),this.wrapper.addEventListener("click",e=>{(e.target===this.player.getVideoElement()||e.target===this.wrapper)&&(this.player.togglePlay(),this.settingsMenu.close())})}updatePlayPause(e){this.playPauseBtn.innerHTML="",this.playPauseBtn.appendChild(e?this.pauseIcon.cloneNode(!0):this.playIcon.cloneNode(!0)),this.playPauseBtn.setAttribute("aria-label",e?"Pause":"Play")}showControls(){this.element.classList.remove("gallop-controls-hidden"),this.wrapper.style.cursor=""}hideControls(){this.hideTimer&&(clearTimeout(this.hideTimer),this.hideTimer=null),this.element.classList.add("gallop-controls-hidden"),this.wrapper.style.cursor="none"}startHideTimer(){this.hideTimer&&clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>this.hideControls(),Gr)}destroy(){this.hideTimer&&clearTimeout(this.hideTimer),this.progressBar.destroy(),this.volumeControl.destroy(),this.wrapper.removeEventListener("mousemove",this.onActivity)}};var ls=class{constructor(e){this.element=document.createElement("button"),this.element.className="gallop-big-play",this.element.setAttribute("aria-label","Play"),this.element.appendChild(xe(Se.play)),this.element.addEventListener("click",t=>{t.stopPropagation(),e()})}setVisible(e){this.element.hidden=!e}};var cs=class{constructor(){this.element=document.createElement("div"),this.element.className="gallop-spinner",this.element.hidden=!0,this.element.setAttribute("role","status"),this.element.setAttribute("aria-label","Loading");let e=document.createElement("div");e.className="gallop-spinner-ring",this.element.appendChild(e)}setVisible(e){this.element.hidden=!e}};var ds=class{constructor(e){this.element=document.createElement("div"),this.element.className="gallop-error",this.element.hidden=!0,this.messageEl=document.createElement("div"),this.messageEl.className="gallop-error-message",this.messageEl.textContent="An error occurred during playback.",this.element.appendChild(this.messageEl);let t=document.createElement("button");t.className="gallop-error-retry",t.textContent="Retry",t.addEventListener("click",i=>{i.stopPropagation(),e()}),this.element.appendChild(t)}setVisible(e){this.element.hidden=!e}setMessage(e){this.messageEl.textContent=e}};var hs=class{constructor(){this.element=document.createElement("div"),this.element.className="gallop-poster",this.element.hidden=!0}show(e){this.element.style.backgroundImage=`url("${e.replace(/"/g,'\\"')}")`,this.element.hidden=!1}hide(){this.element.hidden=!0}};var us=class{constructor(e,t){this.wrapper=e;this.onHide=null;this.handleContextMenu=e=>{e.preventDefault(),e.stopPropagation();let t=this.wrapper.getBoundingClientRect(),i=e.clientX-t.left,s=e.clientY-t.top;this.element.hidden=!1;let n=this.element.getBoundingClientRect();i+n.width>t.width&&(i=t.width-n.width-4),s+n.height>t.height&&(s=t.height-n.height-4),this.element.style.left=`${Math.max(4,i)}px`,this.element.style.top=`${Math.max(4,s)}px`};this.handleDocumentClick=()=>{this.hide()};this.handleDocumentContext=e=>{this.wrapper.contains(e.target)||this.hide()};let i=t||window.location.href;this.items=[{label:"About ScaleMule Gallop",action:()=>{window.open("https://www.scalemule.com/gallop","_blank","noopener")}},{label:"Report a problem",action:()=>{let s=encodeURIComponent(i);window.open(`https://www.scalemule.com/gallop/report?url=${s}`,"_blank","noopener")}},{label:"Copy link",action:()=>{navigator.clipboard?.writeText(i).catch(()=>{let s=document.createElement("input");s.value=i,document.body.appendChild(s),s.select(),document.execCommand("copy"),document.body.removeChild(s)})}}],this.element=kr("div",{class:"gallop-context-menu"}),this.element.hidden=!0;for(let s of this.items){let n=kr("div",{class:"gallop-context-menu-item"});n.textContent=s.label,n.addEventListener("click",a=>{a.stopPropagation(),s.action(),this.hide()}),this.element.appendChild(n)}this.wrapper.addEventListener("contextmenu",this.handleContextMenu),document.addEventListener("click",this.handleDocumentClick),document.addEventListener("contextmenu",this.handleDocumentContext)}hide(){this.element.hidden=!0}destroy(){this.wrapper.removeEventListener("contextmenu",this.handleContextMenu),document.removeEventListener("click",this.handleDocumentClick),document.removeEventListener("contextmenu",this.handleDocumentContext),this.element.remove()}};var ju={colorPrimary:"--gallop-color-primary",colorSecondary:"--gallop-color-secondary",colorText:"--gallop-color-text",colorBackground:"--gallop-color-background",colorBuffered:"--gallop-color-buffered",colorProgress:"--gallop-color-progress",controlBarBackground:"--gallop-control-bar-bg",controlBarHeight:"--gallop-control-bar-height",borderRadius:"--gallop-border-radius",fontFamily:"--gallop-font-family",fontSize:"--gallop-font-size",iconSize:"--gallop-icon-size"},fs=class{constructor(e){this.theme=e}apply(e){for(let[t,i]of Object.entries(ju)){let s=this.theme[t];s&&e.style.setProperty(i,s)}}update(e,t){this.theme={...this.theme,...e},this.apply(t)}};var gs=class{constructor(e){this.player=e,this.handler=t=>{let i=e.getWrapperElement();if(!i.contains(document.activeElement)&&document.activeElement!==i)return;let s=t.target?.tagName;if(!(s==="INPUT"||s==="TEXTAREA"||s==="SELECT"))switch(t.key){case" ":case"k":t.preventDefault(),e.togglePlay();break;case"ArrowLeft":t.preventDefault(),e.seekBackward(As);break;case"ArrowRight":t.preventDefault(),e.seekForward(As);break;case"j":t.preventDefault(),e.seekBackward(vt);break;case"l":t.preventDefault(),e.seekForward(vt);break;case"ArrowUp":t.preventDefault(),e.volume=Math.min(1,e.volume+Ls);break;case"ArrowDown":t.preventDefault(),e.volume=Math.max(0,e.volume-Ls);break;case"m":t.preventDefault(),e.toggleMute();break;case"f":t.preventDefault(),e.toggleFullscreen();break;case"0":case"Home":t.preventDefault(),e.seek(0);break;case"End":t.preventDefault(),e.seek(e.duration);break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{t.preventDefault();let n=parseInt(t.key)/10;e.seek(e.duration*n);break}case"<":t.preventDefault(),this.cycleSpeed(-1);break;case">":t.preventDefault(),this.cycleSpeed(1);break}},document.addEventListener("keydown",this.handler)}cycleSpeed(e){let t=[.25,.5,.75,1,1.25,1.5,1.75,2],i=this.player.playbackRate,n=t.indexOf(i)+e;n>=0&&n<t.length&&(this.player.playbackRate=t[n])}destroy(){document.removeEventListener("keydown",this.handler)}};var ps=class{constructor(e,t){this.lastTapTime=0;this.lastTapX=0;this.tapTimeout=null;this.player=e,this.wrapper=t,this.handler=i=>{let s=i.target;if(s.closest(".gallop-controls")||s.closest(".gallop-big-play"))return;let n=i.changedTouches[0],a=Date.now();if(a-this.lastTapTime<Is){this.tapTimeout&&(clearTimeout(this.tapTimeout),this.tapTimeout=null);let c=t.getBoundingClientRect(),l=n.clientX-c.left,d=c.width/2;l<d?e.seekBackward(vt):e.seekForward(vt)}else this.tapTimeout=setTimeout(()=>{e.togglePlay(),this.tapTimeout=null},Is);this.lastTapTime=a,this.lastTapX=n.clientX},t.addEventListener("touchend",this.handler)}destroy(){this.wrapper.removeEventListener("touchend",this.handler),this.tapTimeout&&clearTimeout(this.tapTimeout)}};var _l=`
|
|
41
|
+
/* ===== Gallop Player \u2014 ScaleMule Video Player ===== */
|
|
42
|
+
|
|
43
|
+
/* --- Foundation --- */
|
|
44
|
+
.gallop-player {
|
|
45
|
+
position: relative;
|
|
46
|
+
width: 100%;
|
|
47
|
+
max-width: 100%;
|
|
48
|
+
background: #000;
|
|
49
|
+
overflow: hidden;
|
|
50
|
+
border-radius: var(--gallop-border-radius, 8px);
|
|
51
|
+
font-family: var(--gallop-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif);
|
|
52
|
+
font-size: var(--gallop-font-size, 13px);
|
|
53
|
+
color: #fff;
|
|
54
|
+
user-select: none;
|
|
55
|
+
-webkit-user-select: none;
|
|
56
|
+
outline: none;
|
|
57
|
+
line-height: 1.4;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
.gallop-player * {
|
|
61
|
+
box-sizing: border-box;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
.gallop-player.gallop-fullscreen {
|
|
65
|
+
border-radius: 0;
|
|
66
|
+
width: 100vw;
|
|
67
|
+
height: 100vh;
|
|
68
|
+
max-width: none;
|
|
69
|
+
aspect-ratio: auto !important;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
.gallop-video {
|
|
73
|
+
display: block;
|
|
74
|
+
width: 100%;
|
|
75
|
+
height: 100%;
|
|
76
|
+
object-fit: contain;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/* --- Icon base --- */
|
|
80
|
+
.gallop-icon {
|
|
81
|
+
display: inline-flex;
|
|
82
|
+
align-items: center;
|
|
83
|
+
justify-content: center;
|
|
84
|
+
width: var(--gallop-icon-size, 22px);
|
|
85
|
+
height: var(--gallop-icon-size, 22px);
|
|
86
|
+
flex-shrink: 0;
|
|
87
|
+
}
|
|
88
|
+
.gallop-icon svg {
|
|
89
|
+
width: 100%;
|
|
90
|
+
height: 100%;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/* ===================================================
|
|
94
|
+
BIG PLAY BUTTON \u2014 Signature rounded-rect with gradient
|
|
95
|
+
=================================================== */
|
|
96
|
+
.gallop-big-play {
|
|
97
|
+
position: absolute;
|
|
98
|
+
top: 50%;
|
|
99
|
+
left: 50%;
|
|
100
|
+
transform: translate(-50%, -50%);
|
|
101
|
+
width: 104px;
|
|
102
|
+
height: 72px;
|
|
103
|
+
background: var(--gallop-color-primary, #635bff);
|
|
104
|
+
border: none;
|
|
105
|
+
border-radius: 18px;
|
|
106
|
+
cursor: pointer;
|
|
107
|
+
display: flex;
|
|
108
|
+
align-items: center;
|
|
109
|
+
justify-content: center;
|
|
110
|
+
color: #fff;
|
|
111
|
+
opacity: 0.92;
|
|
112
|
+
transition: opacity 0.25s, transform 0.25s, box-shadow 0.25s;
|
|
113
|
+
z-index: 4;
|
|
114
|
+
padding: 0;
|
|
115
|
+
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
.gallop-big-play:hover {
|
|
119
|
+
opacity: 1;
|
|
120
|
+
transform: translate(-50%, -50%) scale(1.06);
|
|
121
|
+
box-shadow: 0 6px 28px rgba(0, 0, 0, 0.4);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
.gallop-big-play .gallop-icon {
|
|
125
|
+
width: 40px;
|
|
126
|
+
height: 40px;
|
|
127
|
+
margin-left: 4px;
|
|
128
|
+
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.15));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
.gallop-big-play[hidden] {
|
|
132
|
+
display: none;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/* When controls are visible during pause, dim the big play button slightly */
|
|
136
|
+
.gallop-player[data-status="paused"] .gallop-big-play {
|
|
137
|
+
opacity: 0.85;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/* ===================================================
|
|
141
|
+
LOADING SPINNER \u2014 Brand-colored ring
|
|
142
|
+
=================================================== */
|
|
143
|
+
.gallop-spinner {
|
|
144
|
+
position: absolute;
|
|
145
|
+
top: 50%;
|
|
146
|
+
left: 50%;
|
|
147
|
+
transform: translate(-50%, -50%);
|
|
148
|
+
width: 48px;
|
|
149
|
+
height: 48px;
|
|
150
|
+
z-index: 3;
|
|
151
|
+
}
|
|
152
|
+
.gallop-spinner[hidden] { display: none; }
|
|
153
|
+
|
|
154
|
+
.gallop-spinner-ring {
|
|
155
|
+
width: 100%;
|
|
156
|
+
height: 100%;
|
|
157
|
+
border: 3px solid rgba(255, 255, 255, 0.15);
|
|
158
|
+
border-top-color: var(--gallop-color-primary, #635bff);
|
|
159
|
+
border-radius: 50%;
|
|
160
|
+
animation: gallop-spin 0.8s linear infinite;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
@keyframes gallop-spin {
|
|
164
|
+
to { transform: rotate(360deg); }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/* ===================================================
|
|
168
|
+
POSTER IMAGE
|
|
169
|
+
=================================================== */
|
|
170
|
+
.gallop-poster {
|
|
171
|
+
position: absolute;
|
|
172
|
+
inset: 0;
|
|
173
|
+
z-index: 2;
|
|
174
|
+
background-size: cover;
|
|
175
|
+
background-position: center;
|
|
176
|
+
background-repeat: no-repeat;
|
|
177
|
+
transition: opacity 0.4s ease;
|
|
178
|
+
}
|
|
179
|
+
.gallop-poster[hidden] { display: none; }
|
|
180
|
+
|
|
181
|
+
/* ===================================================
|
|
182
|
+
ERROR OVERLAY
|
|
183
|
+
=================================================== */
|
|
184
|
+
.gallop-error {
|
|
185
|
+
position: absolute;
|
|
186
|
+
inset: 0;
|
|
187
|
+
z-index: 5;
|
|
188
|
+
background: rgba(0, 0, 0, 0.88);
|
|
189
|
+
display: flex;
|
|
190
|
+
flex-direction: column;
|
|
191
|
+
align-items: center;
|
|
192
|
+
justify-content: center;
|
|
193
|
+
gap: 16px;
|
|
194
|
+
}
|
|
195
|
+
.gallop-error[hidden] { display: none; }
|
|
196
|
+
|
|
197
|
+
.gallop-error-message {
|
|
198
|
+
font-size: 15px;
|
|
199
|
+
color: rgba(255, 255, 255, 0.75);
|
|
200
|
+
text-align: center;
|
|
201
|
+
max-width: 80%;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
.gallop-error-retry {
|
|
205
|
+
padding: 10px 28px;
|
|
206
|
+
background: var(--gallop-color-primary, #635bff);
|
|
207
|
+
color: #fff;
|
|
208
|
+
border: none;
|
|
209
|
+
border-radius: 10px;
|
|
210
|
+
font-size: 14px;
|
|
211
|
+
font-weight: 500;
|
|
212
|
+
cursor: pointer;
|
|
213
|
+
transition: transform 0.2s, box-shadow 0.2s;
|
|
214
|
+
}
|
|
215
|
+
.gallop-error-retry:hover {
|
|
216
|
+
transform: scale(1.04);
|
|
217
|
+
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/* ===================================================
|
|
221
|
+
CONTROL BAR \u2014 Floating rounded pill
|
|
222
|
+
=================================================== */
|
|
223
|
+
.gallop-controls {
|
|
224
|
+
position: absolute;
|
|
225
|
+
bottom: 10px;
|
|
226
|
+
left: 10px;
|
|
227
|
+
right: 10px;
|
|
228
|
+
z-index: 10;
|
|
229
|
+
background: var(--gallop-control-bar-bg, rgba(0, 0, 0, 0.65));
|
|
230
|
+
border-radius: 22px;
|
|
231
|
+
padding: 0;
|
|
232
|
+
opacity: 1;
|
|
233
|
+
transition: opacity 0.35s ease;
|
|
234
|
+
backdrop-filter: blur(12px);
|
|
235
|
+
-webkit-backdrop-filter: blur(12px);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/* Hide controls during active playback (not paused/idle/ready/ended) */
|
|
239
|
+
.gallop-player:not(:hover):not(:focus-within):not([data-status="paused"]):not([data-status="idle"]):not([data-status="ready"]):not([data-status="ended"]) .gallop-controls.gallop-controls-hidden {
|
|
240
|
+
opacity: 0;
|
|
241
|
+
pointer-events: none;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/* Also hide big play button during active playback when controls hidden */
|
|
245
|
+
.gallop-player:not(:hover):not(:focus-within)[data-status="playing"] .gallop-big-play {
|
|
246
|
+
opacity: 0;
|
|
247
|
+
pointer-events: none;
|
|
248
|
+
transition: opacity 0.35s ease;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
.gallop-controls-row {
|
|
252
|
+
display: flex;
|
|
253
|
+
align-items: center;
|
|
254
|
+
gap: 6px;
|
|
255
|
+
height: var(--gallop-control-bar-height, 44px);
|
|
256
|
+
padding: 0 6px 0 8px;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/* --- Control Buttons --- */
|
|
260
|
+
.gallop-btn {
|
|
261
|
+
background: none;
|
|
262
|
+
border: none;
|
|
263
|
+
color: rgba(255, 255, 255, 0.9);
|
|
264
|
+
cursor: pointer;
|
|
265
|
+
padding: 6px;
|
|
266
|
+
border-radius: 6px;
|
|
267
|
+
display: flex;
|
|
268
|
+
align-items: center;
|
|
269
|
+
justify-content: center;
|
|
270
|
+
transition: background 0.15s, color 0.15s, transform 0.15s;
|
|
271
|
+
position: relative;
|
|
272
|
+
}
|
|
273
|
+
.gallop-btn:hover {
|
|
274
|
+
background: rgba(255, 255, 255, 0.12);
|
|
275
|
+
color: #fff;
|
|
276
|
+
transform: scale(1.05);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/* ===================================================
|
|
280
|
+
PROGRESS BAR \u2014 Thick, bold, TikTok-inspired
|
|
281
|
+
=================================================== */
|
|
282
|
+
.gallop-progress-container {
|
|
283
|
+
flex: 1;
|
|
284
|
+
min-width: 0;
|
|
285
|
+
padding: 0;
|
|
286
|
+
cursor: pointer;
|
|
287
|
+
display: flex;
|
|
288
|
+
align-items: center;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
.gallop-progress-bar {
|
|
292
|
+
position: relative;
|
|
293
|
+
width: 100%;
|
|
294
|
+
height: 4px;
|
|
295
|
+
background: rgba(255, 255, 255, 0.2);
|
|
296
|
+
border-radius: 2px;
|
|
297
|
+
transition: height 0.15s ease;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
.gallop-progress-container:hover .gallop-progress-bar {
|
|
301
|
+
height: 6px;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
.gallop-progress-buffered {
|
|
305
|
+
position: absolute;
|
|
306
|
+
left: 0;
|
|
307
|
+
top: 0;
|
|
308
|
+
height: 100%;
|
|
309
|
+
background: rgba(255, 255, 255, 0.22);
|
|
310
|
+
border-radius: 2px;
|
|
311
|
+
pointer-events: none;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
.gallop-progress-played {
|
|
315
|
+
position: absolute;
|
|
316
|
+
left: 0;
|
|
317
|
+
top: 0;
|
|
318
|
+
height: 100%;
|
|
319
|
+
background: var(--gallop-color-progress, var(--gallop-color-primary, #635bff));
|
|
320
|
+
border-radius: 2px;
|
|
321
|
+
pointer-events: none;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
.gallop-progress-thumb {
|
|
325
|
+
position: absolute;
|
|
326
|
+
top: 50%;
|
|
327
|
+
width: 12px;
|
|
328
|
+
height: 12px;
|
|
329
|
+
background: #fff;
|
|
330
|
+
border: 2px solid var(--gallop-color-primary, #635bff);
|
|
331
|
+
border-radius: 50%;
|
|
332
|
+
transform: translate(-50%, -50%);
|
|
333
|
+
opacity: 0;
|
|
334
|
+
transition: opacity 0.15s, transform 0.15s;
|
|
335
|
+
pointer-events: none;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
.gallop-progress-container:hover .gallop-progress-thumb {
|
|
339
|
+
opacity: 1;
|
|
340
|
+
transform: translate(-50%, -50%) scale(1.1);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/* ===================================================
|
|
344
|
+
VOLUME
|
|
345
|
+
=================================================== */
|
|
346
|
+
.gallop-volume {
|
|
347
|
+
display: flex;
|
|
348
|
+
align-items: center;
|
|
349
|
+
gap: 4px;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
.gallop-volume-slider-wrap {
|
|
353
|
+
width: 0;
|
|
354
|
+
overflow: hidden;
|
|
355
|
+
transition: width 0.2s ease;
|
|
356
|
+
}
|
|
357
|
+
.gallop-volume:hover .gallop-volume-slider-wrap,
|
|
358
|
+
.gallop-volume-slider-wrap.gallop-volume-expanded {
|
|
359
|
+
width: 64px;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
.gallop-volume-slider {
|
|
363
|
+
width: 64px;
|
|
364
|
+
height: 4px;
|
|
365
|
+
background: rgba(255, 255, 255, 0.18);
|
|
366
|
+
border-radius: 2px;
|
|
367
|
+
position: relative;
|
|
368
|
+
cursor: pointer;
|
|
369
|
+
}
|
|
370
|
+
.gallop-volume-fill {
|
|
371
|
+
position: absolute;
|
|
372
|
+
left: 0;
|
|
373
|
+
top: 0;
|
|
374
|
+
height: 100%;
|
|
375
|
+
background: rgba(255, 255, 255, 0.85);
|
|
376
|
+
border-radius: 2px;
|
|
377
|
+
pointer-events: none;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/* ===================================================
|
|
381
|
+
TIME DISPLAY
|
|
382
|
+
=================================================== */
|
|
383
|
+
.gallop-time {
|
|
384
|
+
font-size: 12px;
|
|
385
|
+
color: rgba(255, 255, 255, 0.85);
|
|
386
|
+
white-space: nowrap;
|
|
387
|
+
font-variant-numeric: tabular-nums;
|
|
388
|
+
min-width: 40px;
|
|
389
|
+
letter-spacing: 0.02em;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/* Spacer */
|
|
393
|
+
.gallop-spacer { flex: 1; }
|
|
394
|
+
|
|
395
|
+
/* ===================================================
|
|
396
|
+
SETTINGS MENU
|
|
397
|
+
=================================================== */
|
|
398
|
+
.gallop-settings-menu {
|
|
399
|
+
position: absolute;
|
|
400
|
+
bottom: 100%;
|
|
401
|
+
right: 0;
|
|
402
|
+
margin-bottom: 8px;
|
|
403
|
+
min-width: 200px;
|
|
404
|
+
background: var(--gallop-color-background, rgba(24, 24, 32, 0.92));
|
|
405
|
+
border-radius: 12px;
|
|
406
|
+
padding: 6px 0;
|
|
407
|
+
backdrop-filter: blur(16px);
|
|
408
|
+
-webkit-backdrop-filter: blur(16px);
|
|
409
|
+
z-index: 20;
|
|
410
|
+
max-height: 300px;
|
|
411
|
+
overflow-y: auto;
|
|
412
|
+
border: 1px solid rgba(255, 255, 255, 0.08);
|
|
413
|
+
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
|
414
|
+
}
|
|
415
|
+
.gallop-settings-menu[hidden] { display: none; }
|
|
416
|
+
|
|
417
|
+
.gallop-settings-header {
|
|
418
|
+
display: flex;
|
|
419
|
+
align-items: center;
|
|
420
|
+
gap: 8px;
|
|
421
|
+
padding: 8px 14px;
|
|
422
|
+
font-size: 13px;
|
|
423
|
+
font-weight: 600;
|
|
424
|
+
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
|
425
|
+
cursor: pointer;
|
|
426
|
+
color: rgba(255, 255, 255, 0.9);
|
|
427
|
+
}
|
|
428
|
+
.gallop-settings-header .gallop-icon {
|
|
429
|
+
width: 18px;
|
|
430
|
+
height: 18px;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
.gallop-settings-item {
|
|
434
|
+
display: flex;
|
|
435
|
+
align-items: center;
|
|
436
|
+
justify-content: space-between;
|
|
437
|
+
padding: 8px 16px;
|
|
438
|
+
cursor: pointer;
|
|
439
|
+
transition: background 0.12s;
|
|
440
|
+
font-size: 13px;
|
|
441
|
+
gap: 12px;
|
|
442
|
+
color: rgba(255, 255, 255, 0.8);
|
|
443
|
+
}
|
|
444
|
+
.gallop-settings-item:hover {
|
|
445
|
+
background: rgba(255, 255, 255, 0.08);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
.gallop-settings-item-active .gallop-icon {
|
|
449
|
+
color: var(--gallop-color-primary, #635bff);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
.gallop-settings-value {
|
|
453
|
+
color: rgba(255, 255, 255, 0.5);
|
|
454
|
+
font-size: 12px;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/* ===================================================
|
|
458
|
+
CONTEXT MENU
|
|
459
|
+
=================================================== */
|
|
460
|
+
.gallop-context-menu {
|
|
461
|
+
position: absolute;
|
|
462
|
+
z-index: 30;
|
|
463
|
+
min-width: 180px;
|
|
464
|
+
background: var(--gallop-color-background, rgba(24, 24, 32, 0.94));
|
|
465
|
+
border-radius: 10px;
|
|
466
|
+
padding: 4px 0;
|
|
467
|
+
backdrop-filter: blur(16px);
|
|
468
|
+
-webkit-backdrop-filter: blur(16px);
|
|
469
|
+
border: 1px solid rgba(255, 255, 255, 0.08);
|
|
470
|
+
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.45);
|
|
471
|
+
}
|
|
472
|
+
.gallop-context-menu[hidden] { display: none; }
|
|
473
|
+
|
|
474
|
+
.gallop-context-menu-item {
|
|
475
|
+
padding: 9px 14px;
|
|
476
|
+
font-size: 13px;
|
|
477
|
+
color: rgba(255, 255, 255, 0.85);
|
|
478
|
+
cursor: pointer;
|
|
479
|
+
transition: background 0.12s;
|
|
480
|
+
white-space: nowrap;
|
|
481
|
+
}
|
|
482
|
+
.gallop-context-menu-item:hover {
|
|
483
|
+
background: rgba(255, 255, 255, 0.08);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/* ===================================================
|
|
487
|
+
GALLOP BRANDING WATERMARK
|
|
488
|
+
=================================================== */
|
|
489
|
+
.gallop-brand {
|
|
490
|
+
position: absolute;
|
|
491
|
+
top: 12px;
|
|
492
|
+
right: 12px;
|
|
493
|
+
z-index: 6;
|
|
494
|
+
display: flex;
|
|
495
|
+
align-items: center;
|
|
496
|
+
gap: 5px;
|
|
497
|
+
padding: 4px 10px;
|
|
498
|
+
background: rgba(0, 0, 0, 0.35);
|
|
499
|
+
border-radius: 6px;
|
|
500
|
+
backdrop-filter: blur(8px);
|
|
501
|
+
-webkit-backdrop-filter: blur(8px);
|
|
502
|
+
opacity: 0;
|
|
503
|
+
transition: opacity 0.35s ease;
|
|
504
|
+
pointer-events: none;
|
|
505
|
+
font-size: 11px;
|
|
506
|
+
font-weight: 600;
|
|
507
|
+
letter-spacing: 0.04em;
|
|
508
|
+
color: rgba(255, 255, 255, 0.7);
|
|
509
|
+
text-transform: uppercase;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
.gallop-brand-dot {
|
|
513
|
+
width: 6px;
|
|
514
|
+
height: 6px;
|
|
515
|
+
border-radius: 50%;
|
|
516
|
+
background: var(--gallop-color-primary, #635bff);
|
|
517
|
+
flex-shrink: 0;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/* Show branding on hover */
|
|
521
|
+
.gallop-player:hover .gallop-brand,
|
|
522
|
+
.gallop-player:focus-within .gallop-brand,
|
|
523
|
+
.gallop-player[data-status="paused"] .gallop-brand,
|
|
524
|
+
.gallop-player[data-status="idle"] .gallop-brand,
|
|
525
|
+
.gallop-player[data-status="ready"] .gallop-brand,
|
|
526
|
+
.gallop-player[data-status="ended"] .gallop-brand {
|
|
527
|
+
opacity: 1;
|
|
528
|
+
pointer-events: auto;
|
|
529
|
+
}
|
|
530
|
+
`;var ms={flushIntervalMs:3e3,maxBatchSize:20,maxQueueSize:300,progressIntervalSeconds:10},vs=class{constructor(e){this.queue=[];this.flushTimer=null;this.flushing=!1;this.destroyed=!1;this.playRequestedAtMs=null;this.ttffMs=null;this.firstFrameSeen=!1;this.lastProgressPosition=0;this.maxPositionSeen=0;this.watchedSeconds=0;this.lastHeartbeatPosition=0;this.bufferStartedAtMs=null;this.totalBufferMs=0;this.startupQuality=null;this.qualitySwitches=0;this.lastQuality=null;this.lastEngineStats=null;this.cdnNode=null;this.cdnCacheStatus=null;this.cdnRequestID=null;this.initialDroppedFrames=null;this.droppedFrames=0;this.isVisible=!0;this.observer=null;this.onPlay=()=>this.handlePlay();this.onPause=()=>this.handlePause();this.onEnded=()=>this.handleEnded();this.onSeeked=({time:e})=>this.handleSeeked(e);this.onTimeUpdate=({currentTime:e})=>this.handleTimeUpdate(e);this.onBuffering=({isBuffering:e})=>this.handleBuffering(e);this.onQualityChange=({level:e})=>this.handleQualityChange(e);this.onError=({code:e,message:t})=>this.handleError(e,t);this.onVisibilityChange=()=>{document.visibilityState==="hidden"&&(this.enqueue("pause",this.player.currentTime,{event_subtype:"document_hidden"},!0),this.flush(!0))};this.onPageHide=()=>{this.enqueue("pause",this.player.currentTime,{event_subtype:"pagehide"},!0),this.flush(!0)};this.client=e.client,this.player=e.player,this.videoId=e.videoId,this.config=e.config??{},this.sessionId=this.config.sessionId??Xu(),this.bind(),this.start(),this.initVisibilityTracking()}setVideoId(e){this.videoId=e}onEngineStats(e){this.lastEngineStats=e,e.cdnNode&&(this.cdnNode=e.cdnNode),e.cdnCacheStatus&&(this.cdnCacheStatus=e.cdnCacheStatus),e.cdnRequestID&&(this.cdnRequestID=e.cdnRequestID),e.kind==="periodic"&&e.droppedFrames!==void 0&&(this.initialDroppedFrames===null?this.initialDroppedFrames=e.droppedFrames:this.droppedFrames=e.droppedFrames-this.initialDroppedFrames)}trackEvent(e,t,i={},s=!1){this.enqueue(e,t,i,s)}async destroy(){if(!this.destroyed){if(this.observer&&(this.observer.disconnect(),this.observer=null),this.unbind(),this.bufferStartedAtMs!==null){let e=Date.now()-this.bufferStartedAtMs;this.totalBufferMs+=Math.max(0,e),this.bufferStartedAtMs=null}this.enqueue("pause",this.player.currentTime,{event_subtype:"destroy"},!0),await this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.destroyed=!0}}bind(){this.player.on("play",this.onPlay),this.player.on("pause",this.onPause),this.player.on("ended",this.onEnded),this.player.on("seeked",this.onSeeked),this.player.on("timeupdate",this.onTimeUpdate),this.player.on("buffering",this.onBuffering),this.player.on("qualitychange",this.onQualityChange),this.player.on("error",this.onError),typeof document<"u"&&document.addEventListener("visibilitychange",this.onVisibilityChange),typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide)}unbind(){this.player.off("play",this.onPlay),this.player.off("pause",this.onPause),this.player.off("ended",this.onEnded),this.player.off("seeked",this.onSeeked),this.player.off("timeupdate",this.onTimeUpdate),this.player.off("buffering",this.onBuffering),this.player.off("qualitychange",this.onQualityChange),this.player.off("error",this.onError),typeof document<"u"&&document.removeEventListener("visibilitychange",this.onVisibilityChange),typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide)}start(){this.flushTimer=setInterval(()=>{this.flush(!1)},this.config.flushIntervalMs??ms.flushIntervalMs)}handlePlay(){this.playRequestedAtMs=Date.now(),this.enqueue("play",this.player.currentTime)}handlePause(){this.enqueue("pause",this.player.currentTime),this.flush(!1)}handleEnded(){this.enqueue("complete",this.player.currentTime,{completion_ratio:ys(this.player.currentTime,this.player.duration)},!0),this.flush(!1)}handleSeeked(e){this.lastProgressPosition=e,this.maxPositionSeen=Math.max(this.maxPositionSeen,e),this.enqueue("seek",e)}handleTimeUpdate(e){if(!Number.isFinite(e))return;if(!this.firstFrameSeen&&this.playRequestedAtMs!==null&&(this.firstFrameSeen=!0,this.ttffMs=Math.max(0,Date.now()-this.playRequestedAtMs)),this.lastProgressPosition>0){let i=e-this.lastProgressPosition;i>0&&i<5&&(this.watchedSeconds+=i)}this.lastProgressPosition=e,this.maxPositionSeen=Math.max(this.maxPositionSeen,e);let t=this.config.progressIntervalSeconds??ms.progressIntervalSeconds;Math.abs(e-this.lastHeartbeatPosition)>=t&&(this.lastHeartbeatPosition=e,this.enqueue("play",e,{event_subtype:"heartbeat"}))}initVisibilityTracking(){if(this.config.trackVisibility===!1||typeof IntersectionObserver>"u")return;this.observer=new IntersectionObserver(t=>{let i=t[0];if(i){let s=this.isVisible;this.isVisible=i.isIntersecting,s!==this.isVisible&&this.enqueue("play",this.player.currentTime,{event_subtype:"visibility_change",is_visible:this.isVisible,intersection_ratio:ze(i.intersectionRatio,3)})}},{threshold:[0,.25,.5,.75,1]});let e=this.player.getWrapperElement();e&&this.observer.observe(e)}handleBuffering(e){if(e){if(this.bufferStartedAtMs!==null)return;this.bufferStartedAtMs=Date.now(),this.enqueue("buffer",this.player.currentTime,{buffering_state:"start"});return}if(this.bufferStartedAtMs===null)return;let t=Math.max(0,Date.now()-this.bufferStartedAtMs);this.totalBufferMs+=t,this.bufferStartedAtMs=null,this.enqueue("buffer",this.player.currentTime,{buffering_state:"end",buffering_duration_ms:Math.round(t)})}handleQualityChange(e){let t=e.label||`${e.height}p`;this.startupQuality||(this.startupQuality=t),this.lastQuality&&this.lastQuality!==t&&(this.qualitySwitches+=1),this.lastQuality=t,this.enqueue("play",this.player.currentTime,{event_subtype:"quality_change",quality_label:t,quality_bitrate:e.bitrate,quality_height:e.height,quality_width:e.width})}handleError(e,t){this.enqueue("error",this.player.currentTime,{error_code:e,error_message:t,error_classification:zu(e,this.lastEngineStats)},!0),this.flush(!1)}enqueue(e,t,i={},s=!1){if(!this.videoId)return;let n=this.resolveQuality(),a={session_id:this.sessionId,event_type:e,timestamp_seconds:Number.isFinite(t)?ze(t,3):void 0,quality:n??void 0,metadata:this.buildMetadata(i)};this.queue.push(a);let o=this.config.maxQueueSize??ms.maxQueueSize;this.queue.length>o&&this.queue.splice(0,this.queue.length-o),this.config.debug&&console.debug("[Gallop analytics] queued event",a),s&&this.flush(!1)}async flush(e){if(this.flushing||this.queue.length===0)return;this.flushing=!0;let t=this.config.maxBatchSize??ms.maxBatchSize;try{for(;this.queue.length>0;){let i=this.queue.splice(0,t);for(let s=0;s<i.length;s++)try{await this.client.trackPlayback(this.videoId,i[s],{keepalive:e})}catch(n){this.config.debug&&console.warn("[Gallop analytics] failed to send event",{event:i[s],err:n}),this.queue.unshift(...i.slice(s));return}}}finally{this.flushing=!1}}buildMetadata(e){let t=ze(this.watchedSeconds,3),i=ze(this.player.currentTime,3),s=ze(this.player.duration,3),n=ys(this.totalBufferMs/1e3,this.watchedSeconds),a=this.player.buffered,o=0;for(let l=0;l<a.length;l++)if(i>=a.start(l)&&i<=a.end(l)){o=a.end(l)-i;break}let c={...this.config.metadata??{},...e,current_time_seconds:i,duration_seconds:s,watched_seconds:t,max_position_seconds:ze(this.maxPositionSeen,3),watch_through_ratio:ys(this.maxPositionSeen,this.player.duration),completion_ratio:ys(this.player.currentTime,this.player.duration),ttff_ms:this.ttffMs,total_buffer_ms:Math.round(this.totalBufferMs),rebuffer_ratio:n,buffer_depth_seconds:ze(o,3),quality_switches:this.qualitySwitches,startup_quality:this.startupQuality,dropped_frames:this.droppedFrames,is_visible:this.isVisible,cdn_node:this.cdnNode,cdn_cache_status:this.cdnCacheStatus,cdn_request_id:this.cdnRequestID,playback_rate:this.player.playbackRate,muted:this.player.muted,volume:ze(this.player.volume,3),status:this.player.status,viewport_width:typeof window<"u"?window.innerWidth:void 0,viewport_height:typeof window<"u"?window.innerHeight:void 0,device_pixel_ratio:typeof window<"u"?window.devicePixelRatio:void 0,hls_bandwidth_estimate_bps:this.lastEngineStats?.bandwidthEstimate,hls_stats_kind:this.lastEngineStats?.kind,hls_level:this.lastEngineStats?.level,hls_fragment_duration:this.lastEngineStats?.fragmentDuration,hls_fragment_size_bytes:this.lastEngineStats?.fragmentSizeBytes,hls_fragment_load_ms:this.lastEngineStats?.fragmentLoadMs,hls_error_type:this.lastEngineStats?.errorType,hls_error_details:this.lastEngineStats?.errorDetails,hls_error_fatal:this.lastEngineStats?.fatal,stats_source:this.lastEngineStats?.statsSource,tao_available:this.lastEngineStats?.taoAvailable};if(this.config.includeNetworkInfo??!0){let l=Qu();c.connection_effective_type=l.effectiveType,c.connection_downlink_mbps=l.downlink,c.connection_rtt_ms=l.rtt,c.connection_save_data=l.saveData}return(this.config.includeDeviceInfo??!0)&&(c.user_agent=typeof navigator<"u"?navigator.userAgent:void 0,c.language=typeof navigator<"u"?navigator.language:void 0,c.platform=typeof navigator<"u"?navigator.platform:void 0,c.device_memory_gb=typeof navigator<"u"?navigator.deviceMemory:void 0,c.hardware_concurrency=typeof navigator<"u"?navigator.hardwareConcurrency:void 0,c.screen_width=typeof screen<"u"?screen.width:void 0,c.screen_height=typeof screen<"u"?screen.height:void 0),Zu(c)}resolveQuality(){let e=this.player.getQualityLevels().find(i=>i.active);if(e)return e.label||`${e.height}p`;if(this.lastQuality)return this.lastQuality;let t=this.player.getCurrentQuality();return t>=0?`level_${t}`:null}};function Qu(){if(typeof navigator>"u")return{};let r=navigator.connection;return r?{effectiveType:r.effectiveType,downlink:r.downlink,rtt:r.rtt,saveData:r.saveData}:{}}function zu(r,e){let t=r.toLowerCase();return t.includes("network")||e?.errorType?.toLowerCase().includes("network")?"network":t.includes("media")||e?.errorType?.toLowerCase().includes("media")?"media":"unknown"}function Xu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sess_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function ze(r,e){if(!Number.isFinite(r))return 0;let t=10**e;return Math.round(r*t)/t}function ys(r,e){return!Number.isFinite(r)||!Number.isFinite(e)||e<=0?0:ze(r/e,4)}function Zu(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}function Dl(r){if(r)return r;if(typeof document<"u"&&document.currentScript instanceof HTMLScriptElement&&document.currentScript.nonce)return document.currentScript.nonce;if(typeof document<"u"){let e=document.querySelector("script[nonce], style[nonce]");if(e)return e.nonce||e.getAttribute("nonce")||void 0}}function Pl(r,e){if(typeof document>"u")return;let t=s=>{(s.blockedURI==="inline"||s.violatedDirective.startsWith("style-src"))&&(e(`CSP blocked style injection: ${s.violatedDirective}`),i())};document.addEventListener("securitypolicyviolation",t),requestAnimationFrame(()=>{let s=r.parentElement?.querySelector(".gallop-player");s&&getComputedStyle(s).position==="static"&&(e("CSP may have blocked style injection (computed style mismatch)"),i())}),setTimeout(()=>{r.sheet||(e("Style sheet not applied (sheet is null)"),i())},100);let i=()=>{document.removeEventListener("securitypolicyviolation",t)};setTimeout(i,2e3)}var Es=class{constructor(e,t,i){this.parent=e;this.config=t;this.getDiagnostics=i;this.isExpanded=!1;this.container=document.createElement("div"),this.container.className="gallop-debug-overlay",this.container.setAttribute("aria-hidden","true"),this.container.style.cssText=`
|
|
531
|
+
position: absolute;
|
|
532
|
+
top: 10px;
|
|
533
|
+
right: 10px;
|
|
534
|
+
z-index: 9999;
|
|
535
|
+
background: rgba(0, 0, 0, 0.8);
|
|
536
|
+
color: #00ff00;
|
|
537
|
+
font-family: monospace;
|
|
538
|
+
font-size: 10px;
|
|
539
|
+
padding: 5px;
|
|
540
|
+
border-radius: 3px;
|
|
541
|
+
pointer-events: auto;
|
|
542
|
+
max-width: 300px;
|
|
543
|
+
max-height: 80%;
|
|
544
|
+
overflow-y: auto;
|
|
545
|
+
border: 1px solid #333;
|
|
546
|
+
`,this.contentEl=document.createElement("div"),this.container.appendChild(this.contentEl);let s=document.createElement("div");s.textContent="[DEBUG]",s.style.cursor="pointer",s.onclick=()=>this.toggle(),this.container.insertBefore(s,this.contentEl),this.parent.appendChild(this.container),this.update(),setInterval(()=>this.update(),1e3)}toggle(){this.isExpanded=!this.isExpanded,this.container.setAttribute("aria-hidden",(!this.isExpanded).toString()),this.isExpanded?this.container.setAttribute("role","log"):this.container.removeAttribute("role"),this.update()}update(){if(!this.isExpanded){this.contentEl.innerHTML="",this.container.style.width="auto";return}let e=this.getDiagnostics(),t=`
|
|
547
|
+
<div style="margin-top: 5px; border-top: 1px solid #444; padding-top: 5px;">
|
|
548
|
+
<strong>System</strong><br>
|
|
549
|
+
v: ${this.config.version}<br>
|
|
550
|
+
mode: ${this.config.mode}<br>
|
|
551
|
+
engine: ${this.config.engineType}<br>
|
|
552
|
+
nonce: ${this.config.nonceStatus}<br>
|
|
553
|
+
csp: ${this.config.cspStatus}<br>
|
|
554
|
+
conn: ${this.config.connectionState||"n/a"}<br>
|
|
555
|
+
</div>
|
|
556
|
+
<div style="margin-top: 5px; border-top: 1px solid #444; padding-top: 5px;">
|
|
557
|
+
<strong>Performance</strong><br>
|
|
558
|
+
bitrate: ${(e.bitrate/1e6).toFixed(2)} Mbps<br>
|
|
559
|
+
buffer: ${e.bufferLength.toFixed(1)}s<br>
|
|
560
|
+
fps: ${e.fps}<br>
|
|
561
|
+
dropped: ${e.droppedFrames}<br>
|
|
562
|
+
</div>
|
|
563
|
+
<div style="margin-top: 5px; border-top: 1px solid #444; padding-top: 5px;">
|
|
564
|
+
<button onclick="navigator.clipboard.writeText(JSON.stringify(window.GallopDiagnostics))" style="font-size: 9px; cursor: pointer;">
|
|
565
|
+
Copy JSON Diagnostics
|
|
566
|
+
</button>
|
|
567
|
+
</div>
|
|
568
|
+
`;this.contentEl.innerHTML=t,window.GallopDiagnostics=e}destroy(){this.container.remove()}};var Ts=class extends ii{constructor(t,i={}){super();this.engine=null;this.client=null;this.controls=null;this.bigPlayButton=null;this.loadingSpinner=null;this.errorOverlay=null;this.posterImage=null;this.contextMenu=null;this.keyboardManager=null;this.touchManager=null;this.analyticsCollector=null;this.styleEl=null;this.debugOverlay=null;this.cspStatus="pending";this.nonceStatus="none";this.destroyed=!1;this.engineStats=null;this.container=t,this.config=i,this.state=new si(s=>{this.emit("statuschange",{status:s}),this.updateUIState()}),this.themeManager=new fs({...$r,...i.theme}),(i.apiKey||i.embedToken)&&(this.client=new is({apiKey:i.apiKey,embedToken:i.embedToken,baseUrl:i.apiBaseUrl})),this.createDOM(),this.bindVideoEvents(),i.controls!==!1&&this.mountUI(),i.keyboard!==!1&&(this.keyboardManager=new gs(this)),i.touch!==!1&&(this.touchManager=new ps(this,this.wrapper)),this.initializeAnalytics(),this.config.debug&&this.initializeDebugOverlay(),i.videoId&&this.client?this.loadVideoById(i.videoId):i.src&&this.loadSource(i.src)}createDOM(){this.styleEl=document.createElement("style");let t=Dl(this.config.nonce);t&&(this.styleEl.nonce=t,this.nonceStatus=this.config.nonce?"explicit":"auto"),this.styleEl.textContent=_l,this.container.appendChild(this.styleEl),Pl(this.styleEl,a=>{this.cspStatus="blocked",this.emit("error",{code:"CSP_BLOCKED",message:a})}),this.cspStatus==="pending"&&(this.cspStatus="applied"),this.wrapper=document.createElement("div"),this.wrapper.className="gallop-player",this.wrapper.setAttribute("tabindex","0"),this.themeManager.apply(this.wrapper);let i=this.config.aspectRatio??Xe.aspectRatio,[s,n]=i.split(":").map(Number);s&&n&&(this.wrapper.style.aspectRatio=`${s} / ${n}`),this.video=document.createElement("video"),this.video.className="gallop-video",this.video.playsInline=!0,this.video.preload="metadata",(this.config.muted??Xe.muted)&&(this.video.muted=!0),(this.config.loop??Xe.loop)&&(this.video.loop=!0),this.wrapper.appendChild(this.video),this.container.appendChild(this.wrapper)}mountUI(){this.posterImage=new hs,this.wrapper.appendChild(this.posterImage.element),this.bigPlayButton=new ls(()=>this.togglePlay()),this.wrapper.appendChild(this.bigPlayButton.element),this.loadingSpinner=new cs,this.wrapper.appendChild(this.loadingSpinner.element),this.errorOverlay=new ds(()=>this.retry()),this.wrapper.appendChild(this.errorOverlay.element),this.controls=new os(this,this.wrapper),this.wrapper.appendChild(this.controls.element),this.contextMenu=new us(this.wrapper,this.config.pageUrl),this.wrapper.appendChild(this.contextMenu.element);let t=document.createElement("div");t.className="gallop-brand";let i=document.createElement("span");i.className="gallop-brand-dot",t.appendChild(i),t.appendChild(document.createTextNode("Gallop")),this.wrapper.appendChild(t),this.config.poster&&this.posterImage.show(this.config.poster)}bindVideoEvents(){let t=this.video;t.addEventListener("play",()=>{this.state.transition("playing"),this.emit("play")}),t.addEventListener("pause",()=>{this.state.isEnded||(this.state.transition("paused"),this.emit("pause"))}),t.addEventListener("ended",()=>{this.state.transition("ended"),this.emit("ended")}),t.addEventListener("timeupdate",()=>{this.emit("timeupdate",{currentTime:t.currentTime,duration:t.duration})}),t.addEventListener("volumechange",()=>{this.emit("volumechange",{volume:t.volume,muted:t.muted})}),t.addEventListener("waiting",()=>{this.state.transition("buffering"),this.emit("buffering",{isBuffering:!0})}),t.addEventListener("playing",()=>{this.state.transition("playing"),this.emit("buffering",{isBuffering:!1})}),t.addEventListener("canplay",()=>{this.state.status==="loading"&&(this.state.transition("ready"),this.emit("ready"),(this.config.autoplay??Xe.autoplay)&&this.play())}),t.addEventListener("error",()=>{let i=t.error;this.state.transition("error"),this.emit("error",{code:`MEDIA_ERR_${i?.code??0}`,message:i?.message??"Playback error"})}),t.addEventListener("ratechange",()=>{this.emit("ratechange",{rate:t.playbackRate})})}async loadVideoById(t){if(!this.client){this.emit("error",{code:"NO_API_KEY",message:"API key required to load video by ID"});return}this.state.transition("loading"),this.analyticsCollector?.setVideoId(t);try{let i=await this.client.getVideoMetadata(t);i.poster&&this.posterImage&&this.posterImage.show(i.poster),this.loadSource(i.playlistUrl)}catch(i){this.state.transition("error"),this.emit("error",{code:"API_ERROR",message:i instanceof Error?i.message:"Failed to load video"})}}loadSource(t){this.state.transition("loading");try{return this.engine?.destroy(),this.engine=Il({apiKey:this.config.apiKey,embedToken:this.config.embedToken},this.config.hlsConfig),this.engine.on("qualitylevels",i=>{this.emit("qualitylevels",{levels:i})}),this.engine.on("qualitychange",i=>{this.emit("qualitychange",{level:i})}),this.engine.on("error",i=>{let s=i;this.state.transition("error"),this.emit("error",s)}),this.engine.on("stats",i=>{let s=i;this.engineStats=s,this.analyticsCollector?.onEngineStats(s),this.emit("enginestats",{stats:s})}),this.engine.load(t,this.video),this.config.startTime&&(this.video.currentTime=this.config.startTime),Promise.resolve()}catch(i){return this.state.transition("error"),this.emit("error",{code:"ENGINE_ERROR",message:i instanceof Error?i.message:"Failed to initialize player"}),Promise.reject(i)}}getDiagnostics(){return{version:mt,mode:"inline",engineType:this.engine?.constructor.name||"none",bitrate:this.engineStats?.bandwidthEstimate||0,bufferLength:this.getBufferLength(),fps:this.engineStats?.totalFrames||0,droppedFrames:this.engineStats?.droppedFrames||0,totalFrames:this.engineStats?.totalFrames||0,status:this.state.status,isMuted:this.video.muted,volume:this.video.volume,playbackRate:this.video.playbackRate,currentTime:this.video.currentTime,duration:this.video.duration,nonceStatus:this.nonceStatus,cspStatus:this.cspStatus}}getBufferLength(){let t=this.video.currentTime,i=this.video.buffered;for(let s=0;s<i.length;s++)if(t>=i.start(s)&&t<=i.end(s))return i.end(s)-t;return 0}async query(t){switch(t){case"currentTime":return this.video.currentTime;case"duration":return this.video.duration;case"volume":return this.video.volume;case"muted":return this.video.muted;case"playbackRate":return this.video.playbackRate;case"status":return this.state.status;case"isFullscreen":return this.isFullscreen;case"currentQuality":return this.getCurrentQuality();case"qualityLevels":return this.getQualityLevels();case"diagnostics":return this.getDiagnostics();default:return Promise.reject(new Error(`Unknown query key: ${t}`))}}initializeDebugOverlay(){let t=this.getDiagnostics();this.debugOverlay=new Es(this.wrapper,{version:t.version,mode:t.mode,engineType:t.engineType,nonceStatus:t.nonceStatus,cspStatus:t.cspStatus},()=>this.getDiagnostics())}retry(){this.config.videoId&&this.client?this.loadVideoById(this.config.videoId):this.config.src&&this.loadSource(this.config.src)}async play(){try{this.posterImage?.hide(),await this.video.play()}catch(t){t instanceof Error&&(t.name==="NotAllowedError"&&this.analyticsCollector?.trackEvent("error",this.currentTime,{event_subtype:"autoplay_blocked",error_code:"AUTOPLAY_BLOCKED",error_message:t.message}),t.name!=="AbortError"&&this.emit("error",{code:"PLAY_FAILED",message:t.message}))}}pause(){return this.video.pause(),Promise.resolve()}togglePlay(){return this.video.paused||this.video.ended?this.play():this.pause()}seek(t){let i=Mr(t,0,this.duration);return this.video.currentTime=i,this.emit("seeked",{time:i}),Promise.resolve()}seekForward(t=5){this.seek(this.currentTime+t)}seekBackward(t=5){this.seek(this.currentTime-t)}get volume(){return this.video.volume}set volume(t){this.video.volume=Mr(t,0,1)}get muted(){return this.video.muted}set muted(t){this.video.muted=t}toggleMute(){this.video.muted=!this.video.muted}get currentTime(){return this.video.currentTime}get duration(){return this.video.duration||0}get paused(){return this.video.paused}get buffered(){return this.video.buffered}getQualityLevels(){return this.engine?.getQualityLevels()??[]}setQualityLevel(t){return this.engine?.setQualityLevel(t),Promise.resolve()}setAutoQuality(){return this.engine?.setAutoQuality(),Promise.resolve()}isAutoQuality(){return this.engine?.isAutoQuality()??!0}getCurrentQuality(){return this.engine?.getCurrentQuality()??-1}get playbackRate(){return this.video.playbackRate}set playbackRate(t){ti.includes(t)&&(this.video.playbackRate=t)}async toggleFullscreen(){document.fullscreenElement??document.webkitFullscreenElement?await this.exitFullscreen():await this.enterFullscreen()}async enterFullscreen(){let t=this.wrapper;try{t.requestFullscreen?await t.requestFullscreen():t.webkitRequestFullscreen&&await t.webkitRequestFullscreen(),this.wrapper.classList.add("gallop-fullscreen"),this.emit("fullscreenchange",{isFullscreen:!0})}catch{}}async exitFullscreen(){let t=document;try{document.exitFullscreen?await document.exitFullscreen():t.webkitExitFullscreen&&await t.webkitExitFullscreen(),this.wrapper.classList.remove("gallop-fullscreen"),this.emit("fullscreenchange",{isFullscreen:!1})}catch{}}get isFullscreen(){return(document.fullscreenElement??document.webkitFullscreenElement)===this.wrapper}get status(){return this.state.status}getVideoElement(){return this.video}getWrapperElement(){return this.wrapper}updateUIState(){let t=this.state.status;this.bigPlayButton?.setVisible(t==="idle"||t==="ready"||t==="paused"||t==="ended"),this.loadingSpinner?.setVisible(t==="loading"||t==="buffering"),this.errorOverlay?.setVisible(t==="error"),t==="playing"&&this.posterImage?.hide(),this.wrapper.setAttribute("data-status",t)}destroy(){this.destroyed||(this.destroyed=!0,this.keyboardManager?.destroy(),this.touchManager?.destroy(),this.contextMenu?.destroy(),this.controls?.destroy(),this.analyticsCollector?.destroy(),this.engine?.destroy(),this.state.reset(),this.emit("destroy"),this.removeAllListeners(),this.wrapper.remove(),this.styleEl?.remove())}initializeAnalytics(){let t=this.config.analytics;if(!(t?.enabled??!0)||!this.client)return;let s=t?.videoId??this.config.videoId;if(!s){t?.debug&&console.warn("[Gallop analytics] disabled: no videoId available");return}this.analyticsCollector=new vs({client:this.client,player:this,videoId:s,config:t})}};var Ju=new Set(["autoplay","muted","loop","controls","startTime","preferredQuality","aspectRatio","theme","debug","doNotTrack","analytics","pageUrl"]),ef=4096;function tf(r){if(!r.startsWith("config="))return{config:{}};let e=r.slice(7);if(e.length>ef)return{config:{},error:"CONFIG_TOO_LARGE"};let t;try{t=atob(e.replace(/-/g,"+").replace(/_/g,"/"))}catch{return{config:{},error:"CONFIG_PARSE_ERROR"}}let i;try{if(i=JSON.parse(t),typeof i!="object"||i===null||Array.isArray(i))return{config:{},error:"CONFIG_PARSE_ERROR"}}catch{return{config:{},error:"CONFIG_PARSE_ERROR"}}let s={};for(let n of Object.keys(i))Ju.has(n)&&(s[n]=i[n]);return{config:s}}function Jt(){let r=null;try{let e=new URL(window.location.href),t=e.pathname.split("/"),i=t[t.length-1],s=e.searchParams.get("token")||void 0,n=window.location.hash.slice(1),{config:a,error:o}=tf(n),c={...a,videoId:i,embedToken:s},l=document.getElementById("player-container")||document.body,d=new Ts(l,c);r=new yt(d),o&&d.on("ready",()=>{setTimeout(()=>{d.emit?.("error",{code:o,message:`Hash config error: ${o}`})},0)}),console.log("[Gallop] Embed initialized",{videoId:i,version:mt})}catch(e){console.error("[Gallop] Critical embed failure",e);try{window.parent.postMessage({type:"gallop:error",code:"EMBED_LOAD_FAILED",message:e instanceof Error?e.message:"Critical embed failure",version:1},"*")}catch{}}}typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Jt):Jt());return Bl(sf);})();
|