hx-player 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,120 +1,2 @@
1
- (function(Qe,q){typeof exports=="object"&&typeof module<"u"?q(exports):typeof define=="function"&&define.amd?define(["exports"],q):(Qe=typeof globalThis<"u"?globalThis:Qe||self,q(Qe.HxPlayer={}))})(this,(function(Qe){"use strict";var WT=Object.defineProperty;var jT=(Qe,q,pi)=>q in Qe?WT(Qe,q,{enumerable:!0,configurable:!0,writable:!0,value:pi}):Qe[q]=pi;var vt=(Qe,q,pi)=>jT(Qe,typeof q!="symbol"?q+"":q,pi);const q=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},pi=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=Of},Of=Number.MAX_SAFE_INTEGER||9007199254740991;let se=(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})({}),D=(function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.ASSET_LIST_LOAD_ERROR="assetListLoadError",r.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",r.ASSET_LIST_PARSING_ERROR="assetListParsingError",r.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.ATTACH_MEDIA_ERROR="attachMediaError",r.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",r.UNKNOWN="unknown",r})({}),v=(function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.MEDIA_ENDED="hlsMediaEnded",r.STALL_RESOLVED="hlsStallResolved",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFERED_TO_END="hlsBufferedToEnd",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r.ASSET_LIST_LOADING="hlsAssetListLoading",r.ASSET_LIST_LOADED="hlsAssetListLoaded",r.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",r.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",r.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",r.INTERSTITIAL_STARTED="hlsInterstitialStarted",r.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",r.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",r.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",r.INTERSTITIAL_ENDED="hlsInterstitialEnded",r.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",r.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",r.EVENT_CUE_ENTER="hlsEventCueEnter",r})({});function Ff(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Rr={exports:{}},wo;function Mf(){return wo||(wo=1,(function(r,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,u){if(u=u||{},l=l.trim(),c=c.trim(),!c){if(!u.alwaysNormalize)return l;var h=o.parseURL(l);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return u.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;var g=o.parseURL(l);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=s.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var p={scheme:g.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=g.netLoc,d.path[0]!=="/"))if(!d.path)p.path=g.path,d.params||(p.params=g.params,d.query||(p.query=g.query));else{var m=g.path,y=m.substring(0,m.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(y)}return p.path===null&&(p.path=u.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(l){var c=i.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};r.exports=o})()})(Rr)),Rr.exports}var Lr=Mf();class _r{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}}}let pe=(function(r){return r.MANIFEST="manifest",r.LEVEL="level",r.AUDIO_TRACK="audioTrack",r.SUBTITLE_TRACK="subtitleTrack",r.MEDIA_FRAGMENT="media-fragment",r.KEY="key",r.STEERING_MANIFEST="steering-manifest",r.SERVER_CERTIFICATE="server-certificate",r.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",r})({}),te=(function(r){return r.MAIN="main",r.AUDIO="audio",r.SUBTITLE="subtitle",r})({});var _e={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Co{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,Bf(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let s;i.length===1?s=(t==null?void 0: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={[_e.AUDIO]:null,[_e.VIDEO]:null,[_e.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 _r),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=Lr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[_e.AUDIO]=null,e[_e.VIDEO]=null,e[_e.AUDIOVIDEO]=null,this.url=null}}function Ne(r){return r.sn!=="initSegment"}function Fi(r,e){return r.sn===(e==null?void 0:e.sn)&&r.level===e.level}function Pr(r,e){return r.sn===(e==null?void 0:e.sn)&&r.level===e.level&&r.cc===e.cc}class ys extends Co{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){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(q(e)&&q(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;const{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)){const i=Object.keys(t);if(i.length===1){const 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;const e=q(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;const 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(!q(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ne(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){const t=this.levelkeys;if(t){var i;const 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){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,n)}}class Nf extends Co{constructor(e,t,i,s,n){super(i),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const 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(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===te.SUBTITLE&&this.stats.loading.end>0)}}function ko(r,e){const t=Object.getPrototypeOf(r);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||ko(t,e)}}function Bf(r,e){const t=ko(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}function Uf(r,e,t){return(e=Vf(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function Re(){return Re=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},Re.apply(null,arguments)}function Oo(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 re(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Oo(Object(t),!0).forEach(function(i){Uf(r,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Oo(Object(t)).forEach(function(i){Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(t,i))})}return r}function vs(r,e){if(r==null)return{};var t,i,s=$f(r,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);for(i=0;i<n.length;i++)t=n[i],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(r,t)&&(s[t]=r[t])}return s}function $f(r,e){if(r==null)return{};var t={};for(var i in r)if({}.hasOwnProperty.call(r,i)){if(e.indexOf(i)!==-1)continue;t[i]=r[i]}return t}function Gf(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 Vf(r){var e=Gf(r,"string");return typeof e=="symbol"?e:e+""}function Es(r){switch(r.details){case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_TIMEOUT:case D.LEVEL_LOAD_TIMEOUT:case D.MANIFEST_LOAD_TIMEOUT:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:case D.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function Fo(r){return r.details.startsWith("key")}function Mo(r){return Fo(r)&&!!r.frag&&!r.frag.decryptdata}function No(r,e){const t=Es(e);return r.default[`${t?"timeout":"error"}Retry`]}function Dr(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function Bo(r){return re(re({},r),{errorRetry:null,timeoutRetry:null})}function Mi(r,e,t,i){if(!r)return!1;const s=i==null?void 0:i.code,n=e<r.maxNumRetry&&(Hf(s)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,i,n):n}function Hf(r){return Ni(r)||!!r&&(r<400||r>499)}function Ni(r){return r===0&&navigator.onLine===!1}function Uo(r,e){return e>0&&r.loadError>0&&r.loadErrorTime!==0&&self.performance.now()-r.loadErrorTime>e}class mi{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){const 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_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Kf{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 mi(e),this.fast_=new mi(t),this.defaultTTFB_=s,this.ttfb_=new mi(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new mi(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new mi(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new mi(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){if(t<=0)return;const i=Math.min(this.minDelayMs_,t/1e5),s=8*t,n=Math.max(e,i)/1e3,a=s/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}sampleTTFB(e){const 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(){}}let dt=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;const i=`[${e}]:`;this.trace=Kt,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)}};const Kt=function(){},qf={trace:Kt,debug:Kt,log:Kt,warn:Kt,info:Kt,error:Kt};function wr(){return Re({},qf)}function Wf(r,e){const t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):Kt}function $o(r,e,t){return e[r]?e[r].bind(e):Wf(r,t)}const Cr=wr();function jf(r,e,t){const i=wr();if(typeof console=="object"&&r===!0||typeof r=="object"){const s=["debug","log","info","warn","error"];s.forEach(n=>{i[n]=$o(n,r,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.7.3`)}catch{return wr()}s.forEach(n=>{Cr[n]=$o(n,r)})}else Re(Cr,i);return i}const be=Cr;function qt(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Yf(r){return typeof self<"u"&&r===self.ManagedMediaSource}function Go(r,e){const 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 zf(r){return btoa(String.fromCharCode(...r))}function Ss(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}const Xf="utf-16",kr="utf-16be",Vo="utf-16le",Ts="utf-8";function Qf(r,e={}){let t;Ss(r)?t=new DataView(r):t=new DataView(r.buffer,r.byteOffset,r.byteLength);let i=0,{encoding:s}=e;if(!s){const c=t.getUint8(0),u=t.getUint8(1);c==239&&u==187&&t.getUint8(2)==191?(s=Ts,i=3):c==254&&u==255?(s=kr,i=2):c==255&&u==254?(s=Vo,i=2):s=Ts}if(typeof TextDecoder<"u")return new TextDecoder(s).decode(t);const{byteLength:n}=t,a=s!==kr;let o="",l;for(;i<n;){switch(s){case Ts:if(l=t.getUint8(i),l<128)i++;else if(l>=194&&l<=223)if(i+1<n){const c=t.getUint8(i+1);c>=128&&c<=191?(l=(l&31)<<6|c&63,i+=2):i++}else i++;else if(l>=224&&l<=239)if(i+2<=n-1){const c=t.getUint8(i+1),u=t.getUint8(i+2);c>=128&&c<=191&&u>=128&&u<=191?(l=(l&15)<<12|(c&63)<<6|u&63,i+=3):i++}else i++;else if(l>=240&&l<=244)if(i+3<=n-1){const c=t.getUint8(i+1),u=t.getUint8(i+2),h=t.getUint8(i+3);c>=128&&c<=191&&u>=128&&u<=191&&h>=128&&h<=191?(l=(l&7)<<18|(c&63)<<12|(u&63)<<6|h&63,i+=4):i++}else i++;else i++;break;case kr:case Xf:case Vo:l=t.getUint16(i,a),i+=2;break}o+=String.fromCodePoint(l)}return o}function Jf(r){const e=typeof r=="string"?new URL(r):r;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function Ho(r,e){if(r<0)return-Ho(-r,e);const t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){const i=Math.floor(r*t);return(i%2===0?i:i+1)/t}else return Math.round(r*t)/t}function Zf(r,e){let t;try{t=new URL(r)}catch{return r}const i=new URL(e);if(t.origin!==i.origin)return r;const s=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1),a=Math.min(s.length,n.length);for(let o=0;o<a&&s[o]===n[o];o++)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+t.search+t.hash}function Ko(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const s=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?s:s&3|8).toString(16)})}}}function Or(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 bs(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 eg(r,e){return Or(r,e)&&bs(r,e+6)+10<=r.length-e}function qo(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 Bi(r,e){const t=e;let i=0;for(;Or(r,e);){i+=10;const s=bs(r,e+6);i+=s,qo(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)}function tg(r){return Ss(r)?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function Fr(r,e=0,t=1/0){return ig(r,e,t,Uint8Array)}function ig(r,e,t,i){const s=sg(r);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const a=rg(r)?r.byteOffset:0,o=(a+r.byteLength)/n,l=(a+e)/n,c=Math.floor(Math.max(0,Math.min(l,o)));return new i(s,c,Math.floor(Math.min(c+Math.max(t,0),o))-c)}function sg(r){return Ss(r)?r:r.buffer}function rg(r){return r&&Ss(r.buffer)&&r.byteLength!==void 0&&r.byteOffset!==void 0}function ft(r,e=!1){const t=e?r.indexOf(0):r.length,i=Qf(new DataView(r.buffer,r.byteOffset,t),{encoding:Ts});return e?i:i.replace(/\0/g,"")}function ng(r){const 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}const i=r.data.subarray(1).indexOf(0);if(i===-1)return;const s=ft(Fr(r.data,1,i)),n=r.data[2+i],a=r.data.subarray(3+i).indexOf(0);if(a===-1)return;const o=ft(Fr(r.data,3+i,a));let l;return s==="-->"?l=ft(Fr(r.data,4+i+a)):l=tg(r.data.subarray(4+i+a)),e.mimeType=s,e.pictureType=n,e.description=o,e.data=l,e}function ag(r){if(r.size<2)return;const e=ft(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function og(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const{data:i}=r,s=ft(i.subarray(t),!0);t+=s.length+1;const n=ft(i.subarray(t));return{key:r.type,info:s,data:n}}const e=ft(r.data.subarray(1));return{key:r.type,info:"",data:e}}function lg(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const i=ft(r.data.subarray(t),!0);t+=i.length+1;const s=ft(r.data.subarray(t));return{key:r.type,info:i,data:s}}const e=ft(r.data);return{key:r.type,info:"",data:e}}function cg(r){return r.type==="PRIV"?ag(r):r.type[0]==="W"?lg(r):r.type==="APIC"?ng(r):og(r)}function ug(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=bs(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}}const As=10,hg=10;function Wo(r){let e=0;const t=[];for(;Or(r,e);){const i=bs(r,e+6);r[e+5]>>6&1&&(e+=As),e+=As;const s=e+i;for(;e+hg<s;){const n=ug(r.subarray(e)),a=cg(n);a&&t.push(a),e+=n.size+As}qo(r,e)&&(e+=As)}return t}function jo(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function dg(r){if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Mr(r){const e=Wo(r);for(const t of e)if(jo(t))return dg(t)}function Ge(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 Yo(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Nr(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function bt(r){return String.fromCharCode.apply(null,r)}const Dt=Math.pow(2,32)-1,he={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},zo={video:1,audio:2,id3:3,text:4};function Xo(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function Z(r,e){const t=r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3];return t<0?4294967296+t:t}function Qo(r,e){let t=Z(r,e);return t*=Math.pow(2,32),t+=Z(r,e+4),t}function xs(r,e){let t="";for(let i=e;i<r.length;i++)if(t+=String.fromCharCode(r[i]),r[i]===0)return t;return null}function Br(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Be(r,e,t){r[e]=t>>24,r[e+1]=t>>16&255,r[e+2]=t>>8&255,r[e+3]=t&255}function Jo(r,e,t){const i=e.byteOffset-r.byteOffset-8,s=8+t,n=e.byteLength+8-s;n<8||(Be(r,i,s),Be(r,i+s,n),Be(r,i+s+4,he.free))}function Ur(r,e){return[r.byteOffset-e-8,r.byteOffset-e+r.byteLength]}function Zo(r,e){e.sort((o,l)=>o[0]-l[0]);const t=e.reduce((o,[l,c])=>o+c-l,0),i=new Uint8Array(r.byteLength-t);let s=0,n=0;for(let o=0;o<e.length;o++){const[l,c]=e[o];i.set(r.subarray(s,l),n),n+=l-s,s=c}return i.set(r.subarray(s),n),{result:i,dropped:t,droppedBefore:o=>e.reduce((l,[c,u])=>u<=o?l+u-c:l,0)}}function fg(r){const e=fe(r,["moov"]);if(e.length!==1||fe(r,["moof"]).length)return null;const t=r.byteOffset,i=[],s=[];let n=!1;const a=fe(e[0],["trak"]);for(let g=0;g<a.length;g++){const f=a[g],p=fe(f,["mdia","hdlr"])[0];if((p?bt(p.subarray(8,12)):"")==="vide"){n=!0;continue}const y=fe(f,["tkhd"])[0];if(!y)return null;const E=y[0];s.push(Z(y,E===0?12:20)),i.push(Ur(f,t))}if(!n||!i.length)return null;const o=fe(e[0],["mvex"])[0];let l=0;if(o){const g=fe(o,["trex"]);for(let f=0;f<g.length;f++){const p=g[f];s.indexOf(Z(p,4))!==-1&&(i.push(Ur(p,t)),l+=p.byteLength+8)}}const{result:c,dropped:u,droppedBefore:h}=Zo(r,i),d=e[0].byteOffset-t-8;if(Be(c,d,e[0].byteLength+8-u),o&&l){const g=o.byteOffset-t-8;Be(c,g-h(g),o.byteLength+8-l)}return c}function gg(r,e,t,i,s){if(t<1)return null;const n=fe(r,["moof"]);if(n.length!==1)return null;const a=n[0],o=r.byteOffset,l=[],c=[],u=fe(a,["traf"]);let h=!0;for(let p=0;p<u.length;p++){const m=u[p],y=fe(m,["tfhd"])[0];if(!y)return null;Z(y,4)===e?(l.push(m),Z(y,0)&131072||(h=!1)):c.push(Ur(m,o))}if(!l.length||c.length&&!h)return null;if(i!==void 0){let p=t;for(let y=0;y<l.length;y++){const E=l[y];let S=0;const T=fe(E,["trun"]);for(let I=0;I<T.length;I++){const L=T[I],A=Math.min(p,Z(L,4));if(A){Be(r,L.byteOffset-o+4,A);const x=Z(L,0)&16777215,_=(x&256?4:0)+(x&512?4:0)+(x&1024?4:0)+(x&2048?4:0);Jo(r,L,8+(x&1?4:0)+(x&4?4:0)+A*_)}else Be(r,L.byteOffset-o-4,he.free);p-=A,S+=A}const b=fe(E,["senc"])[0];b&&Be(r,b.byteOffset-o+4,S);const R=fe(E,["saiz"])[0];if(R){const I=R[1]<<16|R[2]<<8|R[3];let L=4;I&1&&(L+=8);const A=R[L];L+=1,Be(r,R.byteOffset-o+L,S),Jo(r,R,L+4+(A===0?S:0))}}const m=fe(r,["mdat"]);if(m.length===1){const y=m[0].byteOffset-o-8;Be(r,y,i-y)}}let d=r,g=0,f=()=>0;if(c.length){({result:d,dropped:g,droppedBefore:f}=Zo(r,c)),Be(d,a.byteOffset-o-8,a.byteLength+8-g);for(let p=0;p<l.length;p++){const m=l[p],y=f(m.byteOffset-o),E=fe(m,["trun"]);for(let S=0;S<E.length;S++){const T=E[S];Z(T,0)&1&&Be(d,T.byteOffset-o-y+8,Z(T,8)-g)}if(y){const S=fe(m,["saio"]);for(let T=0;T<S.length;T++){const b=S[T],R=b[0]===0?4:8;let I=Z(b,0)&1?12:4,L=Z(b,I);for(I+=4;L--;I+=R){const A=I+R-4;Be(d,b.byteOffset-o-y+A,Z(b,A)-y)}}}}}if(s){const{durationOffset:p,value:m}=s;Be(d,p-f(p),m)}return i!==void 0?d.subarray(0,i-g):d}function pg(r,e){const t=r.byteLength;for(let i=0;i<t;){const s=Z(r,i);if(s>8&&Z(r,i+4)===he[e])return!0;i=s>1?i+s:t}return!1}function fe(r,e){const t=[];return e.length&&el(r,e,0,0,r.byteLength,t),t}function el(r,e,t,i,s,n){const a=e[t];if((a==null?void 0:a.length)!==4)return;const o=a.charCodeAt(0),l=a.charCodeAt(1),c=a.charCodeAt(2),u=a.charCodeAt(3),h=e.length-1;for(let d=i;d<s;){const g=d+8<=s,f=d+4<=s?r[d]*16777216+(r[d+1]<<16|r[d+2]<<8|r[d+3]):Z(r,d),p=f>1?d+f:s;if(g&&r[d+4]===o&&r[d+5]===l&&r[d+6]===c&&r[d+7]===u){const m=Math.min(p,s);t===h?n.push(r.subarray(d+8,m)):el(r,e,t+1,d+8,m,n)}d=p}}function mg(r){const e=[],t=r[0];let i=8;const s=Z(r,i);i+=4;let n=0,a=0;t===0?(n=Z(r,i),a=Z(r,i+4),i+=8):(n=Qo(r,i),a=Qo(r,i+8),i+=16),i+=2;let o=r.length+a;const l=Xo(r,i);i+=2;for(let c=0;c<l;c++){let u=i;const h=Z(r,u);u+=4;const d=h&2147483647;if((h&2147483648)>>>31===1)return be.warn("SIDX has hierarchical references (not supported)"),null;const f=Z(r,u);u+=4,e.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+d-1}}),o+=d,u+=4,i=u}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:l,references:e}}function tl(r){const e=[],t=fe(r,["moov","trak"]);for(let s=0;s<t.length;s++){const n=t[s],a=fe(n,["tkhd"])[0];if(a){let o=a[0];const l=Z(a,o===0?12:20),c=fe(n,["mdia","mdhd"])[0];if(c){o=c[0];const u=Z(c,o===0?12:20),h=fe(n,["mdia","hdlr"])[0];if(h){const d=bt(h.subarray(8,12)),g={soun:_e.AUDIO,vide:_e.VIDEO}[d],f=fe(n,["mdia","minf","stbl","stsd"])[0],p=yg(f);g?(e[l]={timescale:u,type:g,stsd:p},e[g]=re({timescale:u,id:l},p)):e[l]={timescale:u,type:d,stsd:p}}}}}return fe(r,["moov","mvex","trex"]).forEach(s=>{const n=Z(s,4),a=e[n];a&&(a.default={duration:Z(s,12),sampleSize:Z(s,16),flags:Z(s,20)})}),e}function yg(r){const e=r.subarray(8),t=e.subarray(86),i=bt(e.subarray(4,8));let s=i,n;const a=i==="enca"||i==="encv";if(a){const c=fe(e,[i])[0].subarray(i==="enca"?28:78);fe(c,["sinf"]).forEach(h=>{const d=fe(h,["schm"])[0];if(d){const g=bt(d.subarray(4,8));if(g==="cbcs"||g==="cenc"){const f=fe(h,["frma"])[0];f&&(s=bt(f))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const l=fe(t,["avcC"])[0];l&&l.length>3&&(s+="."+Rs(l[1])+Rs(l[2])+Rs(l[3]),n=Is(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const l=fe(e,[i])[0],c=fe(l.subarray(28),["esds"])[0];if(c&&c.length>7){let u=4;if(c[u++]!==3)break;u=$r(c,u),u+=2;const h=c[u++];if(h&128&&(u+=2),h&64&&(u+=c[u++]),c[u++]!==4)break;u=$r(c,u);const d=c[u++];if(d===64)s+="."+Rs(d);else break;if(u+=12,c[u++]!==5)break;u=$r(c,u);const g=c[u++];let f=(g&248)>>3;f===31&&(f+=1+((g&7)<<3)+((c[u]&224)>>5)),s+="."+f}break}case"hvc1":case"hev1":{const l=fe(t,["hvcC"])[0];if(l&&l.length>12){const c=l[1],u=["","A","B","C"][c>>6],h=c&31,d=Z(l,2),g=(c&32)>>5?"H":"L",f=l[12],p=l.subarray(6,12);s+="."+u+h,s+="."+vg(d).toString(16).toUpperCase(),s+="."+g+f;let m="";for(let y=p.length;y--;){const E=p[y];(E||m)&&(m="."+E.toString(16).toUpperCase()+m)}s+=m}n=Is(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=Is(s,t)||s;break}case"vp09":{const l=fe(t,["vpcC"])[0];if(l&&l.length>6){const c=l[4],u=l[5],h=l[6]>>4&15;s+="."+wt(c)+"."+wt(u)+"."+wt(h)}break}case"av01":{const l=fe(t,["av1C"])[0];if(l&&l.length>2){const c=l[1]>>>5,u=l[1]&31,h=l[2]>>>7?"H":"M",d=(l[2]&64)>>6,g=(l[2]&32)>>5,f=c===2&&d?g?12:10:d?10:8,p=(l[2]&16)>>4,m=(l[2]&8)>>3,y=(l[2]&4)>>2,E=l[2]&3;s+="."+c+"."+wt(u)+h+"."+wt(f)+"."+p+"."+m+y+E+"."+wt(1)+"."+wt(1)+"."+wt(1)+"."+0,n=Is("dav1",t)}break}}return{codec:s,encrypted:a,supplemental:n}}function Is(r,e){const t=fe(e,["dvvC"]),i=t.length?t[0]:fe(e,["dvcC"])[0];if(i){const s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return r+"."+wt(s)+"."+wt(n)}}function vg(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function $r(r,e){const t=e+5;for(;r[e++]&128&&e<t;);return e}function Rs(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function wt(r){return(r<10?"0":"")+r}function Eg(r,e){if(!r||!e)return;const t=e.keyId;(t==null?void 0:t.byteLength)===16&&e.isCommonEncryption&&il(r,(i,s)=>{const n=i.subarray(8,24);n.some(a=>a!==0)||(be.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Ge(n)} -> ${Ge(t)}`),i.set(t,8))})}function Sg(r){const e=[];return il(r,t=>e.push(t.subarray(8,24))),e}function il(r,e){fe(r,["moov","trak"]).forEach(i=>{const s=fe(i,["mdia","minf","stbl","stsd"])[0];if(!s)return;const n=s.subarray(8);let a=fe(n,["enca"]);const o=a.length>0;o||(a=fe(n,["encv"])),a.forEach(l=>{const c=o?l.subarray(28):l.subarray(78);fe(c,["sinf"]).forEach(h=>{const d=sl(h);d&&e(d,o)})})})}function sl(r){const e=fe(r,["schm"])[0];if(e){const t=bt(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=fe(r,["schi","tenc"])[0];if(i)return i}}}let rl;function Tg(r){return typeof TextDecoder>"u"?ft(r):(rl||(rl=new TextDecoder("utf-8"))).decode(r).replace(/\0/g,"")}function bg(r){const e=r.byteLength,t=[];for(let i=0;i<e;){const s=i+8<=e,n=i+4<=e?r[i]*16777216+(r[i+1]<<16|r[i+2]<<8|r[i+3]):Z(r,i),a=n>1?i+n:e;if(s&&r[i+4]===109&&r[i+5]===111&&r[i+6]===111&&r[i+7]===102){const o=Math.min(a,e);for(let l=i+8;l<o;){const c=l+8<=o,u=l+4<=o?r[l]*16777216+(r[l+1]<<16|r[l+2]<<8|r[l+3]):Z(r,l),h=u>1?l+u:o;if(c&&r[l+4]===116&&r[l+5]===114&&r[l+6]===97&&r[l+7]===102){const d=Math.min(h,o);let g,f;const p=[];for(let m=l+8;m<d;){const y=m+8<=d,E=m+4<=d?r[m]*16777216+(r[m+1]<<16|r[m+2]<<8|r[m+3]):Z(r,m),S=E>1?m+E:d;if(y&&r[m+4]===116){const T=Math.min(S,d);r[m+5]===102&&r[m+6]===104&&r[m+7]===100?f||(f=r.subarray(m+8,T)):r[m+5]===102&&r[m+6]===100&&r[m+7]===116?g||(g=r.subarray(m+8,T)):r[m+5]===114&&r[m+6]===117&&r[m+7]===110&&p.push(r.subarray(m+8,T))}m=S}t.push({moofOffset:r.byteOffset+i,tfdt:g,tfhd:f,truns:p})}l=h}}i=a}return t}function Ag(r,e,t,i,s=!0){return nl(r,e,i,s)}function xg(r,e,t,i,s=!1){const n=[],a=e.samples,o=nl(a,t,i,s,{isHEVCFlavor:Ui(e.codec),samples:n,timeOffset:r,timescale:e.timescale,trackId:e.id});return{samples:n,sampleData:{includeSampleDetails:s,tracks:o}}}function nl(r,e,t,i,s){const n={};let a=!1;const o=bg(r),l=r.byteLength;for(let h=0;h<o.length;h++){const{moofOffset:d,tfdt:g,tfhd:f,truns:p}=o[h],m=Z(f,4),y=e[m];if(!y)continue;const E=n[m]||(n[m]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:y.timescale,type:y.type});let S;if(g){const F=g[0];S=Z(g,4),F===1&&(S===Dt?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Dt+1,S+=Z(g,8))),q(S)&&(!q(E.start)||S<E.start)&&(E.start=S),s&&q(S)&&(s.timeOffset=S/s.timescale)}const T=(s==null?void 0:s.trackId)===m&&y.type===_e.VIDEO,b=y.default,R=Z(f,0)&16777215;let I=(b==null?void 0:b.duration)||0,L,A=(b==null?void 0:b.sampleSize)||0,x=8;R&1&&(x+=8),R&2&&(x+=4),R&8&&(I=Z(f,x),L=f.byteOffset-r.byteOffset+x,x+=4),R&16&&(A=Z(f,x));let _=0;const w=(R&1)!==0,G=!w&&(R&131072)!==0;w?(_=Z(f,8),_*=Math.pow(2,32),_+=Z(f,12)):G&&(_=d);let B=S||0,K=0,O=I;for(let F=0;F<p.length;F++){const M=p[F],V=Z(M,4),$=E.sampleCount;E.sampleCount+=V;const C=M[3]&1;let H=0;const Q=M[3]&4,J=M[2]&1,ce=M[2]&2,ie=M[2]&4,z=M[2]&8;let ne=8;C&&(H=Br(M,ne),ne+=4),Q&&(!(M[ne+1]&1)&&E.keyFrameIndex===void 0&&(E.keyFrameIndex=$),ne+=4);let oe=_+H;if(!i&&M[1]===0&&M[2]===6&&M[3]===1){var c,u;const ae=B,ye=oe,Me=ne;let j=-1,ee=0,W=0,ge=(c=s==null?void 0:s.timeOffset)!=null?c:0;const ve=I/((u=s==null?void 0:s.timescale)!=null?u:1),Te=(s==null?void 0:s.isHEVCFlavor)===!0,$e=Te?2:1;for(let Le=0;Le<V;Le++){const Xe=M[ne]===0?M[ne+1]<<16|M[ne+2]<<8|M[ne+3]:Z(M,ne),ct=j===-1&&E.keyFrameIndex===void 0&&(M[ne+5]&1)===0;ne+=8;const it=oe+Xe;if(T){if(Xe>0){let We=oe;do{const ut=r[We]===0?r[We+1]<<16|r[We+2]<<8|r[We+3]:Z(r,We);We+=4;const mt=r[We],ht=Te?mt>>1&63:mt&31;(Te?ht===39||ht===40:ht===6)&&$i(r.subarray(We,We+ut),$e,ge,s.samples),We+=ut}while(We<it)}ge+=ve}oe=it,ct&&(j=Le,ee=oe)}if(oe<=l)W=V;else{let Le=ye,Xe=Me;for(let ct=0;ct<V;ct++){const it=M[Xe]===0?M[Xe+1]<<16|M[Xe+2]<<8|M[Xe+3]:Z(M,Xe);if(Le+=it,Le>l)break;W=ct+1,Xe+=8}}if(T&&(s.timeOffset=ge),j!==-1&&ee<=l&&E.keyFrameIndex===void 0&&(E.keyFrameIndex=j,E.keyFrameStart=ae+j*I),W){(!q(E.ptsMin)||ae<E.ptsMin)&&(E.ptsMin=ae);const Le=ae+W*I;(!q(E.ptsMax)||Le>E.ptsMax)&&(E.ptsMax=Le)}const tt=I*V;B=ae+tt,K+=tt;continue}let ue,Ee;i&&(ue=[],Ee={sampleOffset:oe,samples:ue,defaultSampleDurationOffset:L},oe<=l&&E.trun.push(Ee));let de;for(let ae=0;ae<V;ae++){let ye;J?(i&&(ye=M.byteOffset-r.byteOffset+ne),O=Z(M,ne),ne+=4):O=I,ce?(de=Z(M,ne),ne+=4):de=A;let Me,j;ie&&(j=M[ne+1]&1?1:0,i&&(Me={isNonSync:j,dependsOn:(M[ne]&3)===1?1:2}),ne+=4);let ee=0;if(z&&(ee=M[0]===0?Z(M,ne):Br(M,ne),ne+=4),T){let W=oe,ge=0;for(;ge<de;){const ve=Z(r,W);W+=4,al(s.isHEVCFlavor,r[W])&&$i(r.subarray(W,W+ve),s.isHEVCFlavor?2:1,s.timeOffset+ee/s.timescale,s.samples),W+=ve,ge+=ve+4}s.timeOffset+=O/s.timescale}if(oe+=de,oe<=l){Ee&&ye!==void 0&&(Ee.lastSampleDurationOffset=ye),j===0&&E.keyFrameIndex===void 0&&(E.keyFrameIndex=ae,E.keyFrameStart=B);const W=B+ee;(!q(E.ptsMin)||W<E.ptsMin)&&(E.ptsMin=W),(!q(E.ptsMax)||W+O>E.ptsMax)&&(E.ptsMax=W+O),ue&&(ue[ae]={cts:ee,duration:O,flags:Me,size:de})}B+=O,K+=O}!K&&I&&(K+=I*V)}E.duration+=K,E.duration&&(a=!0)}if(!a){let h=1/0,d=0;const g=fe(r,["sidx"]);for(let f=0;f<g.length;f++){const p=mg(g[f]);if(p!=null&&p.references){h=Math.min(h,p.earliestPresentationTime/p.timescale);const m=p.references.reduce((y,E)=>y+E.info.duration||0,0);d=Math.max(d,m+p.earliestPresentationTime/p.timescale)}}d&&q(d)&&Object.keys(n).forEach(f=>{n[f].duration||(n[f].duration=d*n[f].timescale-n[f].start)})}return n}function Ig(r){const e={valid:null,remainder:null},t=fe(r,["moof"]);if(t.length<2)return e.remainder=r,e;const i=t[t.length-1];return e.valid=r.slice(0,i.byteOffset-8),e.remainder=r.slice(i.byteOffset-8),e}function Et(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function Rg(r,e){const t=[],i=e.samples,s=e.timescale,n=e.id;let a=!1;return fe(i,["moof"]).map(l=>{const c=l.byteOffset-8;fe(l,["traf"]).map(h=>{const d=fe(h,["tfdt"]).map(g=>{const f=g[0];let p=Z(g,4);return f===1&&(p*=Math.pow(2,32),p+=Z(g,8)),p/s})[0];return d!==void 0&&(r=d),fe(h,["tfhd"]).map(g=>{const f=Z(g,4),p=Z(g,0)&16777215,m=(p&1)!==0;let y=0;const E=(p&2)!==0,S=(p&8)!==0;let T=0;const b=(p&16)!==0;let R=0;const I=(p&32)!==0,L=!m&&(p&131072)!==0;let A=8;f===n&&(m?(y=Z(g,A),A+=4,y*=Math.pow(2,32),y+=Z(g,A),A+=4):L&&(y=c),E&&(A+=4),S&&(T=Z(g,A),A+=4),b&&(R=Z(g,A),A+=4),I&&(A+=4),e.type==="video"&&(a=Ui(e.codec)),fe(h,["trun"]).map(x=>{const _=x[0],w=Z(x,0)&16777215,G=(w&1)!==0;let B=0;const K=(w&4)!==0,O=(w&256)!==0;let F=0;const M=(w&512)!==0;let V=0;const $=(w&1024)!==0,C=(w&2048)!==0;let H=0;const Q=Z(x,4);let J=8;G&&(B=Z(x,J),J+=4),K&&(J+=4);let ce=y+B;for(let ie=0;ie<Q;ie++){if(O?(F=Z(x,J),J+=4):F=T,M?(V=Z(x,J),J+=4):V=R,$&&(J+=4),C&&(_===0?H=Z(x,J):H=Br(x,J),J+=4),e.type===_e.VIDEO){let z=0;for(;z<V;){const ne=Z(i,ce);if(ce+=4,al(a,i[ce])){const oe=i.subarray(ce,ce+ne);$i(oe,a?2:1,r+H/s,t)}ce+=ne,z+=ne+4}}r+=F/s}}))})})}),t}function Ui(r){if(!r)return!1;const e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function al(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function $i(r,e,t,i){const s=ol(r);let n=0;n+=e;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(l===255);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(l===255);const c=s.length-n;let u=n;if(o<c)n+=o;else if(o>c){be.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(s[u++]===181){const d=Xo(s,u);if(u+=2,d===49){const g=Z(s,u);if(u+=4,g===1195456820){const f=s[u++];if(f===3){const p=s[u++],m=31&p,y=64&p,E=y?2+m*3:0,S=new Uint8Array(E);if(y){S[0]=p;for(let T=1;T<E;T++)S[T]=s[u++]}i.push({type:f,payloadType:a,pts:t,bytes:S})}}}}}else if(a===5&&o>16){const h=[];for(let f=0;f<16;f++){const p=s[u++].toString(16);h.push(p.length==1?"0"+p:p),(f===3||f===5||f===7||f===9)&&h.push("-")}const d=o-16,g=new Uint8Array(d);for(let f=0;f<d;f++)g[f]=s[u++];i.push({payloadType:a,pts:t,uuid:h.join(""),userData:Tg(g),userDataBytes:g})}}}function ol(r){const e=r.byteLength;let t,i=r.indexOf(3,3);for(;i!==-1;)r[i-1]===0&&r[i-2]===0&&(t||(t=[])).push(i),i=r.indexOf(3,i+1);if(!t)return r;const s=e-t.length,n=new Uint8Array(s);let a=0,o=0;for(let l=0;l<s;o++,l++)o===t[a]&&(o++,a++),n[l]=r[o];return n}function Lg(r){const e=r[0];let t="",i="",s=0,n=0,a,o=0,l=0,c=4;if(e===0){const h=xs(r,c),d=h!==null?xs(r,c+h.length):null;h!==null&&d!==null?(t=h,i=d,c+=h.length+d.length,s=Z(r,c),c+=4,n=Z(r,c),c+=4,o=Z(r,c),c+=4,l=Z(r,c),c+=4):(be.warn(`Unterminated ${h===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),c=r.length)}else if(e===1){s=Z(r,c),c+=4;const h=Z(r,c);c+=4;const d=Z(r,c);c+=4,a=2**32*h+d,pi(a)||(a=Number.MAX_SAFE_INTEGER,be.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Z(r,c),c+=4,l=Z(r,c),c+=4;const g=xs(r,c),f=g!==null?xs(r,c+g.length):null;g!==null&&(t=g,c+=g.length),f!==null?(i=f,c+=f.length):(be.warn(`Unterminated ${g===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${g===null?"strings and payload":"value and payload"}`),c=r.length)}const u=r.subarray(c,r.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function _g(r,...e){const t=e.length;let i=8,s=t;for(;s--;)i+=e[s].byteLength;const 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 Pg(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;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),_g([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,a,t)}function ll(r){const e=[];if(r instanceof ArrayBuffer){const t=r.byteLength;let i=0;for(;i+32<t;){const s=new DataView(r,i),n=wg(s);e.push(n),i+=n.size}}return e}function Dg(r){const e=[];for(let t=0;t<r.length;){const i=r[t++],s=i&7;if(s===0){for(;r[t++]&128;);continue}if(s!==2){t+=s===1?8:4;continue}let n=0;for(let a=0,o=128;o&128;a+=7)n|=((o=r[t++])&127)<<a;if(i>>3===2)if(n===32){const a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(r[t+o*2],r[t+o*2+1]),16);e.push(a)}else n===16&&e.push(r.subarray(t,t+16));t+=n}return e}function wg(r){const 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};const n=r.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};const a=r.buffer,o=Ge(new Uint8Array(a,t+12,16));let l=null,c=null,u=0;if(n===0)u=28;else{const d=r.getUint32(28);if(!d||i<32+d*16)return{offset:t,size:e};l=[];for(let g=0;g<d;g++)l.push(new Uint8Array(a,t+32+g*16,16));u=32+d*16}if(!u)return{offset:t,size:e};const h=r.getUint32(u);return e-32<h?{offset:t,size:e}:(c=new Uint8Array(a,t+u+4,h),n===0&&(l=Dg(c)),{version:n,systemId:o,kids:l,data:c,offset:t,size:e})}const yi=cl("userAgent"),Cg=cl("vendor");let Gr,Vr,Hr;function cl(r){try{return navigator[r]||""}catch{}return""}function kg(){if(Hr===void 0){const r=yi.match(/Safari\/(\d+)/i);Hr=r?parseInt(r[1]):0}return Hr}function Gi(){if(Gr===void 0){const r=yi.match(/Chrome\/(\d+)/i);Gr=r?parseInt(r[1]):0}return Gr}function Og(){if(Vr===void 0){const r=yi.match(/Firefox\/(\d+)/i);Vr=r?parseInt(r[1]):0}return Vr}function ul(){return/\(Windows.+Firefox\//i.test(yi)}function Fg(){return Cg.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(yi)}function Mg(){return/Android/.test(yi)}const vi={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function Kr(r,e){const t=vi[e];return!!t&&!!t[r.slice(0,4)]}function Vi(r,e,t=!0){return!r.split(",").some(i=>!qr(i,e,t))}function qr(r,e,t=!0){var i;const s=qt(t);return(i=s==null?void 0:s.isTypeSupported(Hi(r,e)))!=null?i:!1}function Hi(r,e){return`${e}/mp4;codecs=${r}`}function hl(r){if(r){const e=r.substring(0,4);return vi.video[e]}return 2}function Ls(r){const e=ul();return r.split(",").reduce((t,i)=>{const n=e&&Ui(i)?9:vi.video[i];return n?(n*2+t)/(t?3:2):(vi.audio[i]+t)/(t?2:1)},0)}const Wr={};function Ng(r,e=!0){if(Wr[r])return Wr[r];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let s=0;s<t.length;s++){var i;if(qr(t[s],"audio",e))return Wr[r]=t[s],t[s];if(t[s]==="mp3"&&(i=qt(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return r}const Bg=/flac|opus|mp4a\.40\.34/i;function _s(r,e=!0){return r.replace(Bg,t=>Ng(t.toLowerCase(),e))}function Ug(r,e){const t=[];if(r){const i=r.split(",");for(let s=0;s<i.length;s++)Kr(i[s],"video")||t.push(i[s])}return e&&t.push(e),t.join(",")}function Ps(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(dl(r,"audio")||dl(r,"video")))return r;if(e){const 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 dl(r,e){return Kr(r,e)&&qr(r,e)}function $g(r){const e=r.split(",");for(let t=0;t<e.length;t++){const 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 Gg(r){if(r.startsWith("av01.")){const 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 fl(r){const e=qt(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 jr(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Vg={supported:!0,powerEfficient:!0,smooth:!0},Hg={supported:!1,smooth:!1,powerEfficient:!1},gl={supported:!0,configurations:[],decodingInfoResults:[Vg]};function pl(r,e){return{supported:!1,configurations:e,decodingInfoResults:[Hg],error:r}}function Kg(r,e,t,i,s,n){const a=r.videoCodec,o=r.audioCodec?r.audioGroups:null,l=n==null?void 0:n.audioCodec,c=n==null?void 0:n.channels,u=c?parseInt(c):l?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=e.groups[o[0]].channels:h=o.reduce((d,g)=>{if(g){const f=e.groups[g];if(!f)throw new Error(`Audio track group ${g} not found`);Object.keys(f.channels).forEach(p=>{d[p]=(d[p]||0)+f.channels[p]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>Ui(d))||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&&q(u)&&Object.keys(h).some(d=>parseInt(d)>u)}function ml(r,e,t,i={}){const s=r.videoCodec;if(!s&&!r.audioCodec||!t)return Promise.resolve(gl);const n=[],a=qg(r),o=a.length,l=Wg(r,e,o>0),c=l.length;for(let u=o||1*c||1;u--;){const h={type:"media-source"};if(o&&(h.video=a[u%o]),c){h.audio=l[u%c];const d=h.audio.bitrate;h.video&&d&&(h.video.bitrate-=d)}n.push(h)}if(s){const u=navigator.userAgent;if(s.split(",").some(h=>Ui(h))&&ul())return Promise.resolve(pl(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{const h=jg(u);return i[h]||(i[h]=t.decodingInfo(u))})).then(u=>({supported:!u.some(h=>!h.supported),configurations:n,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:n,decodingInfoResults:[],error:u}))}function qg(r){var e;const t=(e=r.videoCodec)==null?void 0:e.split(","),i=vl(r),s=r.width||640,n=r.height||480,a=r.frameRate||30,o=r.videoRange.toLowerCase();return t?t.map(l=>{const c={contentType:Hi(Gg(l),"video"),width:s,height:n,bitrate:i,framerate:a};return o!=="sdr"&&(c.transferFunction=o),c}):[]}function Wg(r,e,t){var i;const s=(i=r.audioCodec)==null?void 0:i.split(","),n=vl(r);return s&&r.audioGroups?r.audioGroups.reduce((a,o)=>{var l;const c=o?(l=e.groups[o])==null?void 0:l.tracks:null;return c?c.reduce((u,h)=>{if(h.groupId===o){const d=parseFloat(h.channels||"");s.forEach(g=>{const f={contentType:Hi(g,"audio"),bitrate:t?yl(g,n):n};d&&(f.channels=""+d),u.push(f)})}return u},a):a},[]):[]}function yl(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 vl(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function jg(r){let e="";const{audio:t,video:i}=r;if(i){const s=jr(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){const s=jr(t.contentType);e+=`${i?"_":""}${s}_c${t.channels}`}return e}function Wt(r,e,t){const i=encodeURIComponent(e),s=`${i}=${encodeURIComponent(t)}`;let n=!1;const a=[];r.search.substring(1).split("&").forEach(o=>{o===i||o.startsWith(i+"=")?n||(a.push(s),n=!0):o&&a.push(o)}),n||a.push(s),r.search=a.join("&")}const Yr=["NONE","TYPE-0","TYPE-1",null];function Yg(r){return Yr.indexOf(r)>-1}const Ds=["SDR","PQ","HLG"];function zg(r){return!!r&&Ds.indexOf(r)>-1}var ws={No:"",Yes:"YES",v2:"v2"};function El(r){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=r,s=i<e/2;return e&&s?t?ws.v2:ws.Yes:ws.No}class Sl{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){const t=new self.URL(e);return this.msn!==void 0&&Wt(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&Wt(t,"_HLS_part",this.part.toString()),this.skip&&Wt(t,"_HLS_skip",this.skip),t.href}}class Ki{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Tl(this._audioGroups,e)}hasSubtitleGroup(e){return Tl(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 Tl(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function Xg(){if(typeof matchMedia=="function"){const r=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(r.media!==e.media)return r.matches===!0}return!1}function Qg(r,e){let t=!1,i=[];if(r&&(t=r!=="SDR",i=[r]),e){i=e.allowedVideoRanges||Ds.slice(0);const s=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:s&&Xg(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const Jg=r=>{const 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}},Pe=(r,e)=>JSON.stringify(r,Jg(e));function Zg(r,e,t,i,s){const n=Object.keys(r),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=s==null?void 0:s.videoCodec,c=a&&parseInt(a)===2;let u=!1,h=!1,d=1/0,g=1/0,f=1/0,p=1/0,m=0,y=[];const{preferHDR:E,allowedVideoRanges:S}=Qg(e,s);for(let L=n.length;L--;){const A=r[n[L]];u||(u=A.channels[2]>0),d=Math.min(d,A.minHeight),g=Math.min(g,A.minFramerate),f=Math.min(f,A.minBitrate),S.filter(_=>A.videoRanges[_]>0).length>0&&(h=!0)}d=q(d)?d:0,g=q(g)?g:0;const T=Math.max(1080,d),b=Math.max(30,g);f=q(f)?f:t,t=Math.max(f,t),h||(e=void 0);const R=n.length>1;return{codecSet:n.reduce((L,A)=>{const x=r[A];if(A===L)return L;if(y=h?S.filter(_=>x.videoRanges[_]>0):[],R){if(x.minBitrate>t)return Ct(A,`min bitrate of ${x.minBitrate} > current estimate of ${t}`),L;if(!x.hasDefaultAudio)return Ct(A,"no renditions with default or auto-select sound found"),L;if(o&&A.indexOf(o.substring(0,4))%5!==0)return Ct(A,`audio codec preference "${o}" not found`),L;if(a&&!c){if(!x.channels[a])return Ct(A,`no renditions with ${a} channel sound found (channels options: ${Object.keys(x.channels)})`),L}else if((!o||c)&&u&&x.channels[2]===0)return Ct(A,"no renditions with stereo sound found"),L;if(x.minHeight>T)return Ct(A,`min resolution of ${x.minHeight} > maximum of ${T}`),L;if(x.minFramerate>b)return Ct(A,`min framerate of ${x.minFramerate} > maximum of ${b}`),L;if(!y.some(_=>x.videoRanges[_]>0))return Ct(A,`no variants with VIDEO-RANGE of ${Pe(y)} found`),L;if(l&&A.indexOf(l.substring(0,4))%5!==0)return Ct(A,`video codec preference "${l}" not found`),L;if(x.maxScore<m)return Ct(A,`max score of ${x.maxScore} < selected max of ${m}`),L}return L&&(Ls(A)>=Ls(L)||x.fragmentError>r[L].fragmentError)?L:(p=x.minIndex,m=x.maxScore,A)},void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:f,minIndex:p}}function Ct(r,e){be.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function bl(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);const 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 ep(r,e,t,i){return r.slice(t,i+1).reduce((s,n,a)=>{if(!n.codecSet)return s;const o=n.audioGroups;let l=s[n.codecSet];l||(s[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);const c=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,c),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const h=e.groups[u];h&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(d=>{l.channels[d]=(l.channels[d]||0)+h.channels[d]}))}),s},{})}function Al(r){if(!r)return r;const{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}=r;return{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}}function kt(r,e,t){if("attrs"in r){const i=e.indexOf(r);if(i!==-1)return i}for(let i=0;i<e.length;i++){const s=e[i];if(ti(r,s,t))return i}return-1}function ti(r,e,t){const{groupId:i,name:s,lang:n,assocLang:a,default:o}=r,l=r.forced;return(i===void 0||e.groupId===i)&&(s===void 0||e.name===s)&&(n===void 0||tp(n,e.lang))&&(a===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in r)||ip(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function tp(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function ip(r,e=""){const t=r.split(","),i=e.split(",");return t.length===i.length&&!t.some(s=>i.indexOf(s)===-1)}function ii(r,e){const{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 sp(r,e,t,i,s){const n=e[i],o=e.reduce((d,g,f)=>{const p=g.uri;return(d[p]||(d[p]=[])).push(f),d},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=n.videoRange,c=n.frameRate,u=n.codecSet.substring(0,4),h=xl(e,i,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==u)return!1;const g=d.audioGroups,f=t.filter(p=>qi(p.groupId,g));return kt(r,f,s)>-1});return h>-1?h:xl(e,i,d=>{const g=d.audioGroups,f=t.filter(p=>qi(p.groupId,g));return kt(r,f,s)>-1})}function xl(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 Cs(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}function qi(r,e){return e?e.indexOf(r)!==-1:!0}function Il(r,e){if(e||r){const t=Re({},e);return r&&(r.videoCodec&&(t.videoCodec=r.videoCodec),r.videoRange&&(t.allowedVideoRanges=[r.videoRange])),t}}class rp extends dt{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:n,hls:a}=this;if(!a)return;const{autoLevelEnabled:o,media:l}=a;if(!s||!l)return;const c=performance.now(),u=n?n.stats:s.stats,h=n?n.duration:s.duration,d=c-u.loading.start,g=a.minAutoLevel,f=s.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||f<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const m=p>-1&&p!==f,y=!!t||m;if(!y&&(l.paused||!l.playbackRate||!l.readyState))return;const E=a.mainForwardBufferInfo;if(!y&&E===null)return;const S=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(d<=Math.max(S,1e3*(h/(T*2))))return;const b=E?E.len/T:0,R=u.loading.first?u.loading.first-u.loading.start:-1,I=u.loaded&&R>-1,L=this.getBwEstimate(),A=a.levels,x=A[f],_=Math.max(u.loaded,Math.round(h*(s.bitrate||x.averageBitrate)/8));let w=I?d-R:d;w<1&&I&&(w=Math.min(d,u.loaded*8/L));const G=I?u.loaded*1e3/w:0,B=S/1e3,K=G?(_-u.loaded)/G:_*8/L+B;if(K<=b)return;const O=G?G*8:L,F=((i=(t==null?void 0:t.details)||a.latestLevelDetails)==null?void 0:i.live)===!0,M=a.config.abrBandWidthUpFactor;let V=Number.POSITIVE_INFINITY,$;for($=f-1;$>g;$--){const J=A[$].maxBitrate,ce=!A[$].details||F;if(V=this.getTimeToLoadFrag(B,O,h*J,ce),V<Math.min(b,h+B))break}if(V>=K||V>h*10)return;I?this.bwEstimator.sample(d-Math.min(S,R),u.loaded):this.bwEstimator.sampleTTFB(d);const C=A[$].maxBitrate;this.getBwEstimate()*M>C&&(this.firstAutoFloor=Math.min($,a.firstLevel),this.resetEstimator(C));const H=this.findBestLevel(C,g,$,0,b,1,1);H>-1&&($=H),this.warn(`Fragment ${s.sn}${n?" part "+n.index:""} of level ${f} is loading too slowly;
2
- Fragment duration: ${s.duration.toFixed(3)}
3
- Time to underbuffer: ${b.toFixed(3)} s
4
- Estimated load time for current fragment: ${K.toFixed(3)} s
5
- Estimated load time for down switch fragment: ${V.toFixed(3)} s
6
- TTFB estimate: ${R|0} ms
7
- Current BW estimate: ${q(L)?L|0:"Unknown"} bps
8
- New BW estimate: ${this.getBwEstimate()|0} bps
9
- Switching to level ${$} @ ${C|0} bps`),a.nextLoadLevel=a.nextAutoLevel=$,this.clearTimer();const Q=()=>{this.clearTimer();const J=this.hls;if(this.fragCurrent===s&&J.loadLevel===$&&$>0){const ce=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${$>0?"and switching down":""}
10
- Fragment duration: ${s.duration.toFixed(3)} s
11
- Time to underbuffer: ${ce.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,$>g){let ie=this.findBestLevel(J.levels[g].bitrate,g,$,0,ce,1,1);ie===-1&&(ie=g),J.nextLoadLevel=J.nextAutoLevel=ie,this.firstAutoFloor=Math.min(ie,J.firstLevel),this.resetEstimator(J.levels[ie].bitrate)}}};m||K>V*2?Q():this.timer=self.setInterval(Q,V*1e3),a.trigger(v.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const e=this.hls.config;return new Kf(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const e=this.hls;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(v.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const 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 D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case D.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:s,partCurrent:n}=this;if(i&&Pr(i,s)){const a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(h,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,s){const n=e+i/t,a=s?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,n=s.end-s.first;q(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var i;const{frag:s,part:n}=t,a=n?n.stats:s.stats;if(s.type===te.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(s)){if(this.clearTimer(),s.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(i=this.hls)!=null&&i.config.abrMaxWithRealBitrate){const o=n?n.duration:s.duration,l=this.hls.levels[s.level],c=(l.loaded?l.loaded.bytes:0)+a.loaded,u=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:c,duration:u},l.realBitrate=Math.round(8*c/u)}if(s.bitrateTest){const o={stats:a,frag:s,part:n,id:s.type};this.onFragBuffered(v.FRAG_BUFFERED,o),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;const o=((i.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==te.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:e}=this;if(!e)return 0;const{maxAutoLevel:t,minAutoLevel:i}=e,s=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(s,i,t,n/2,a,1,1);if(o>-1)return o;const l=e.firstLevel,c=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,u=Math.min(Math.max(l,i),t,c);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${u}`),u}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const 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(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let u=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(c){const m=this.findBestLevel(l,a,s,c,0,u,h);if(m>=0)return this.rebufferNotice=-1,m}let d=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!c){const m=this.bitrateTestDelay;m&&(d=(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*d)} ms`),u=h=1)}const g=this.findBestLevel(l,a,s,c,d,u,h);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const f=i.levels[a],p=i.loadLevelObj;return p&&(f==null?void 0:f.bitrate)<p.bitrate?a:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e==null?void 0:e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,i,s,n,a,o){const{hls:l,lastLoadedFragLevel:c,fragCurrent:u,partCurrent:h}=this;if(!l)return-1;const d=s+n,g=c===-1?l.firstLevel:c,{levels:f,allAudioTracks:p,loadLevel:m,latestLevelDetails:y,config:E}=l;if(f.length===1)return 0;const S=f[g],T=!!(y!=null&&y.live),b=m===-1||c===-1;let R,I="SDR",L=(S==null?void 0:S.frameRate)||0;const{audioPreference:A,videoPreference:x}=E,_=this.audioTracksByGroup||(this.audioTracksByGroup=bl(p));let w=-1;if(b){if(this.firstSelection!==-1)return this.firstSelection;const F=this.codecTiers||(this.codecTiers=ep(f,_,t,i)),M=Zg(F,I,e,A,x),{codecSet:V,videoRanges:$,minFramerate:C,minBitrate:H,minIndex:Q,preferHDR:J}=M;w=Q,R=V,I=J?$[$.length-1]:$[0],L=C,e=Math.max(e,H),this.log(`picked start tier ${Pe(M)}`)}else R=S==null?void 0:S.codecSet,I=S==null?void 0:S.videoRange;const G=h?h.duration:u?u.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,K=[];for(let F=i;F>=t;F--){var O;const M=f[F],V=F>g;if(!M)continue;if(E.useMediaCapabilities&&!M.supportedResult&&!M.supportedPromise){const ie=navigator.mediaCapabilities;typeof(ie==null?void 0:ie.decodingInfo)=="function"&&Kg(M,_,I,L,e,A)?(M.supportedPromise=ml(M,_,ie,this.supportedCache),M.supportedPromise.then(z=>{if(!this.hls)return;M.supportedResult=z;const ne=this.hls.levels,oe=ne.indexOf(M);z.error?this.warn(`MediaCapabilities decodingInfo error: "${z.error}" for level ${oe} ${Pe(z)}`):z.supported?z.decodingInfoResults.some(ue=>ue.smooth===!1||ue.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${oe} not smooth or powerEfficient: ${Pe(z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${oe} ${Pe(z)}`),oe>-1&&ne.length>1&&(this.log(`Removing unsupported level ${oe}`),this.hls.removeLevel(oe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${z}`)})):M.supportedResult=gl}if((R&&M.codecSet!==R||I&&M.videoRange!==I||V&&L>M.frameRate||!V&&L>0&&L<M.frameRate||(O=M.supportedResult)!=null&&(O=O.decodingInfoResults)!=null&&O.some(ie=>ie.smooth===!1))&&(!b||F!==w)){K.push(F);continue}const $=M.details,C=(h?$==null?void 0:$.partTarget:$==null?void 0:$.averagetargetduration)||G||1;let H;V?H=o*e:H=a*e;const Q=G&&s>=G*2&&n===0?M.averageBitrate:M.maxBitrate,J=this.getTimeToLoadFrag(B,H,Q*C,!$||$.live);if(H>=Q&&(F===c||M.loadError===0&&M.fragmentError===0||Uo(M,E.errorPenaltyExpireMs))&&(J<=B||!q(J)||T&&!this.bitrateTestDelay||J<d)){const ie=this.forcedAutoLevel;return F!==m&&(ie===-1||ie!==m)&&(K.length&&this.trace(`Skipped level(s) ${K.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[K[0]].codecs}" ${f[K[0]].videoRange}; not compatible with "${R}" ${I}`),this.info(`switch candidate:${g}->${F} adjustedbw(${Math.round(H)})-bitrate=${Math.round(H-Q)} ttfb:${B.toFixed(1)} avgDuration:${C.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${J.toFixed(1)} firstSelection:${b} codecSet:${M.codecSet} videoRange:${M.videoRange} hls.loadLevel:${m}`)),b&&(this.firstSelection=F),F}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Rl={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];const a=e(n);if(a>0)t=s+1;else if(a<0)i=s-1;else return n}return null}};function np(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!q(e))return null;const i=r[0].programDateTime;if(e<(i||0))return null;const s=r[r.length-1].endProgramDateTime;if(e>=(s||0))return null;for(let n=0;n<r.length;++n){const a=r[n];if(op(e,t,a))return a}return null}function Ei(r,e,t=0,i=0,s=.005){let n=null;if(r){n=e[1+r.sn-e[0].sn]||null;const 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)&&Ll(t,i,n)===0||ap(n,r,Math.min(s,i))))return n;const a=Rl.search(e,Ll.bind(null,t,i));return a&&(a!==r||!n)?a:n}function ap(r,e,t){if((e==null?void 0:e.start)===0&&e.level<r.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((s,n)=>(n[0]==="INF"&&(s+=parseFloat(n[1])),s),t);return r.start<=i}return!1}function Ll(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const 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 op(r,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function _l(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){let i=r.fragments;const{fragmentHint:s}=r;s&&(i=i.concat(s));let n;return Rl.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 Pl(r,e){return e===r.endSN&&r.fragmentHint?r.fragmentHint:r.fragments[1+e-r.startSN]||null}var je={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ke={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class lp extends dt{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(v.ERROR,this.onError,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(v.ERROR,this.onError,this),e.off(v.ERROR,this.onErrorOut,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===te.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const 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;const 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;const s=this.hls,n=t.context;switch(t.details){case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case D.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Wi();return}case D.FRAG_GAP:case D.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=je.SendAlternateToPenaltyBox;return}case D.PLAYLIST_UNCHANGED_ERROR:case D.LEVEL_EMPTY_ERROR:case D.LEVEL_PARSING_ERROR:{var a;const o=t.parent===te.MAIN?t.level:s.loadLevel;t.details===D.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_LOAD_ERROR:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const o=s.loadLevelObj;if(o&&(n.type===pe.AUDIO_TRACK&&o.hasAudioGroup(n.groupId)||n.type===pe.SUBTITLE_TRACK&&o.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=je.SendAlternateToPenaltyBox,t.errorAction.flags=Ke.MoveAllAlternatesMatchingHost;return}}return;case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:je.SendAlternateToPenaltyBox,flags:Ke.MoveAllAlternatesMatchingHDCP};return;case D.KEY_SYSTEM_SESSION_UPDATE_FAILED:case D.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case D.KEY_SYSTEM_NO_SESSION:t.errorAction={action:je.SendAlternateToPenaltyBox,flags:Ke.MoveAllAlternatesMatchingKey};return;case D.BUFFER_ADD_CODEC_ERROR:case D.REMUX_ALLOC_ERROR:case D.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case D.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=Ke.ResetMediaSource|Ke.SwitchToSDR;return;case D.INTERNAL_EXCEPTION:case D.BUFFER_APPENDING_ERROR:case D.BUFFER_APPEND_NO_PROGRESS:case D.BUFFER_FULL_ERROR:case D.LEVEL_SWITCH_ERROR:case D.BUFFER_STALLED_ERROR:case D.BUFFER_SEEK_OVER_HOLE:case D.BUFFER_NUDGE_ON_STALL:t.errorAction=Wi();return}t.type===se.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Wi())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,s=No(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(Mi(s,n,Es(e),e.response))return{action:je.RetryRequest,flags:Ke.None,retryConfig:s,retryCount:n};const o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=No(Fo(e)?a:n,e),l=t.levels.reduce((u,h)=>u+h.fragmentError,0);if(s&&(e.details!==D.FRAG_GAP&&s.fragmentError++,!Mo(e)&&Mi(o,l,Es(e),e.response)))return{action:je.RetryRequest,flags:Ke.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,i);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var n,a;const c=e.details;s.loadError++,s.loadErrorTime=self.performance.now(),c===D.BUFFER_APPEND_ERROR&&s.fragmentError++;let u=-1;const{levels:h,loadLevel:d,minAutoLevel:g,maxAutoLevel:f}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const p=(n=e.frag)==null?void 0:n.type,y=(p===te.AUDIO&&c===D.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&Dl(e))&&h.some(({audioCodec:R})=>s.audioCodec!==R),S=e.sourceBufferName==="video"&&Dl(e)&&h.some(({codecSet:R,audioCodec:I})=>s.codecSet!==R&&s.audioCodec===I),{type:T,groupId:b}=(a=e.context)!=null?a:{};for(let R=h.length;R--;){const I=(R+d)%h.length;if(I!==d&&I>=g&&I<=f&&(h[I].loadError===0||Uo(h[I],i.config.errorPenaltyExpireMs))){var o,l;const L=h[I];if(c===D.FRAG_GAP&&p===te.MAIN&&e.frag){const A=h[I].details;if(A){const x=Ei(e.frag,A.fragments,e.frag.start);if(x!=null&&x.gap)continue}}else{if(T===pe.AUDIO_TRACK&&L.hasAudioGroup(b)||T===pe.SUBTITLE_TRACK&&L.hasSubtitleGroup(b))continue;if(p===te.AUDIO&&(o=s.audioGroups)!=null&&o.some(A=>L.hasAudioGroup(A))||p===te.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(A=>L.hasSubtitleGroup(A))||y&&s.audioCodec===L.audioCodec||S&&s.codecSet===L.codecSet||!y&&s.audioCodec!==L.audioCodec)continue}u=I;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:je.SendAlternateToPenaltyBox,flags:Ke.None,nextAutoLevel:u}}return{action:je.SendAlternateToPenaltyBox,flags:Ke.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i,s;switch((i=t.errorAction)==null?void 0:i.action){case je.DoNothing:break;case je.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==D.FRAG_GAP&&t.details!==D.PLAYLIST_UNCHANGED_ERROR&&!wl(t)&&(t.fatal=!0);break}if((((s=t.errorAction)==null?void 0:s.flags)||0)&Ke.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;let s=i.nextAutoLevel;if(i.flags===Ke.None)this.switchLevel(e,s);else if(i.flags&Ke.SwitchToSDR){const o=this.hls.levels,l=o.length;for(let c=l;c--;)o[c].videoRange!=="SDR"?(o[c].fragmentError++,o[c].loadError++):s===void 0&&(s=c)}else if(i.flags&Ke.MoveAllAlternatesMatchingHDCP){const o=this.getVariantLevelIndex(e.frag),l=t.levels[o],c=l==null?void 0:l.attrs["HDCP-LEVEL"];i.hdcpLevel=c;const u=c==="NONE";c&&!u?(t.maxHdcpLevel=Yr[Yr.indexOf(c)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),i.flags|=Ke.MoveAllAlternatesMatchingKey)}if(i.flags&Ke.MoveAllAlternatesMatchingKey){const o=e.decryptdata;if(o){const l=this.hls.levels,c=l.length;for(let h=c;h--;)if(this.variantHasKey(l[h],o)){var n,a;this.log(`Banned key found in level ${h} (${l[h].bitrate}bps) or audio group "${(n=l[h].audioGroups)==null?void 0:n.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${Ge(o.keyId||[])}`),l[h].fragmentError++,l[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const u=e.frag;if(this.hls.levels.length<c)i.resolved=!0;else if(u&&u.type!==te.MAIN){const h=u.decryptdata;h&&!o.matches(h)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(e,s)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===D.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=jr(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 Dl(r){const e=r.details;return e===D.BUFFER_ADD_CODEC_ERROR||e===D.MEDIA_SOURCE_REQUIRES_RESET||e===D.BUFFER_APPEND_ERROR&&!wl(r)}function wl(r){return r.details===D.BUFFER_APPEND_ERROR&&(r.error.name==="QuotaExceededError"||r.error.name==="InvalidStateError")}function Wi(r){const e={action:je.DoNothing,flags:Ke.None};return r&&(e.resolved=!0),e}var ke={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class cp{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(){const{hls:e}=this;e&&(e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.BUFFER_APPENDED,this.onBufferAppended,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.BUFFER_APPENDED,this.onBufferAppended,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const 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){const{fragments:s}=this,n=Object.keys(s);for(let a=n.length;a--;){const o=s[n[a]];if((o==null?void 0:o.body.type)===t&&(!i||o.buffered)){const l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,s,n,a){this.timeRanges&&(this.timeRanges[e]=t);const o=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(l=>{const c=this.fragments[l];if(!c||!this.hls)return;const u=c.body;if(o>=u.sn)return;if(!c.buffered&&(!c.loaded||a)){u.type===i&&this.removeFragment(u);return}const h=c.range[e];if(h){if(h.time.length===0){this.removeFragment(u);return}if(h.time.some(d=>{const g=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return g&&this.removeFragment(u),g}),s&&s!==u&&Gi()){const d=s.endPTS,g=u.startPTS;if(d&&g&&c.range.video){const f=g-d;f<0&&f>-.1&&(this.removeFragment(u),this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:d+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:s,id:n}=e;if(!t||!Ne(i))return;const a=Si(i),o=this.fragments[a];if(!o||o.buffered&&i.gap)return;const l=!i.relurl;Object.keys(t).forEach(u=>{const h=i.elementaryStreams[u];if(!h)return;const d=t[u],g=l||h.partial===!0;o.range[u]=this.getBufferedTimes(i,s,g,d),this.detectEvictedFragments(u,d,n,i,s)}),o.loaded=null;const c=Object.keys(o.range);if(c.length){if(this.bufferedEnd(o,i),ks(o)||this.removeParts(i.sn-1,i.type),!s){const u=Math.min(.004,i.duration);c.some(h=>{var d;const g=(d=o.range[h])==null?void 0:d.time,f=g.length===0||g.length===1&&g[0].endPTS-g[0].startPTS<u;return f&&this.addAsGap(i),f})}}else this.removeFragment(i)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=Cl(i,s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=Si(e);let s=this.fragments[i];return!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,e)),s}getBufferedTimes(e,t,i,s){const n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let u=0;u<s.length;u++){const h=s.start(u)-this.bufferPadding,d=s.end(u)+this.bufferPadding;if(c>=h&&l<=d){n.time.push({startPTS:Math.max(a,s.start(u)),endPTS:Math.min(o,s.end(u))});break}else if(a<d&&o>h){const g=Math.max(a,s.start(u)),f=Math.min(o,s.end(u));f>g&&(n.partial=!0,n.time.push({startPTS:g,endPTS:f}))}else if(o<=h)break}return n}getPartialFragment(e){let t=null,i,s,n,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const u=l[c];u&&ks(u)&&(s=u.body.start-o,n=u.body.end+o,e>=s&&e<=n&&(i=Math.min(e-s,n-e),a<=i&&(t=u.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||ks(t))}getState(e){const t=Si(e),i=this.fragments[t];return i?i.buffered?ks(i)?ke.PARTIAL:ke.OK:ke.APPENDING:ke.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(!Ne(t.frag)||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,n=Si(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:n}=t;if(!Ne(i))return;const a=i.type;if(s){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=n}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Si(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){const n=t[i[s]];if((n==null?void 0:n.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,i){const{fragments:s}=this;let n=0,a=0;const o=Object.keys(s);for(let l=0;l<o.length;l++){const c=s[o[l]];if(!c||!c.buffered||c.body.type!==t)continue;const u=c.body;if(u.gap)return 0;const h=u.hasStats&&u.stats.loaded||u.byteLength||u.bitrate&&u.bitrate*8*u.duration;if(u.end<=e&&h&&(n+=h,a=Math.max(a,u.end),n>=i))return a}return a>0?a:0}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||s&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){const t=Si(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=Cl(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;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}}function ks(r){var e,t,i,s;return r.buffered&&!!(r.body.gap||(e=r.range.video)!=null&&e.partial||(t=r.range.audio)!=null&&t.partial||(i=r.range.audiovideo)!=null&&i.partial||(s=r.range.subs)!=null&&s.partial)}function Si(r){return`${r.type}_${r.level}_${r.sn}`}function Cl(r,e){return r.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var jt={cbc:0,ctr:1};class up{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 jt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case jt.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 hp(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class dp{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){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,c=l[0],u=l[1],h=l[2],d=l[3],g=new Uint32Array(256);let f=0,p=0,m=0;for(m=0;m<256;m++)m<128?g[m]=m<<1:g[m]=m<<1^283;for(m=0;m<256;m++){let y=p^p<<1^p<<2^p<<3^p<<4;y=y>>>8^y&255^99,e[f]=y,t[y]=f;const E=g[f],S=g[E],T=g[S];let b=g[y]*257^y*16843008;s[f]=b<<24|b>>>8,n[f]=b<<16|b>>>16,a[f]=b<<8|b>>>24,o[f]=b,b=T*16843009^S*65537^E*257^f*16843008,c[y]=b<<24|b>>>8,u[y]=b<<16|b>>>16,h[y]=b<<8|b>>>24,d[y]=b,f?(f=E^g[g[g[T^E]]],p^=g[g[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const a=this.ksRows=(n+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),h=this.sBox,d=this.rcon,g=this.invSubMix,f=g[0],p=g[1],m=g[2],y=g[3];let E,S;for(o=0;o<a;o++){if(o<n){E=c[o]=t[o];continue}S=E,o%n===0?(S=S<<8|S>>>24,S=h[S>>>24]<<24|h[S>>>16&255]<<16|h[S>>>8&255]<<8|h[S&255],S^=d[o/n|0]<<24):n>6&&o%n===4&&(S=h[S>>>24]<<24|h[S>>>16&255]<<16|h[S>>>8&255]<<8|h[S&255]),c[o]=E=(c[o-n]^S)>>>0}for(l=0;l<a;l++)o=a-l,l&3?S=c[o]:S=c[o-4],l<4||o<=4?u[l]=S:u[l]=f[h[S>>>24]]^p[h[S>>>16&255]]^m[h[S>>>8&255]]^y[h[S&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],u=o[2],h=o[3],d=this.uint8ArrayToUint32Array_(i);let g=d[0],f=d[1],p=d[2],m=d[3];const y=new Int32Array(e),E=new Int32Array(y.length);let S,T,b,R,I,L,A,x,_,w,G,B,K,O;const F=this.networkToHostOrderSwap;for(;t<y.length;){for(_=F(y[t]),w=F(y[t+1]),G=F(y[t+2]),B=F(y[t+3]),I=_^n[0],L=B^n[1],A=G^n[2],x=w^n[3],K=4,O=1;O<s;O++)S=l[I>>>24]^c[L>>16&255]^u[A>>8&255]^h[x&255]^n[K],T=l[L>>>24]^c[A>>16&255]^u[x>>8&255]^h[I&255]^n[K+1],b=l[A>>>24]^c[x>>16&255]^u[I>>8&255]^h[L&255]^n[K+2],R=l[x>>>24]^c[I>>16&255]^u[L>>8&255]^h[A&255]^n[K+3],I=S,L=T,A=b,x=R,K=K+4;S=a[I>>>24]<<24^a[L>>16&255]<<16^a[A>>8&255]<<8^a[x&255]^n[K],T=a[L>>>24]<<24^a[A>>16&255]<<16^a[x>>8&255]<<8^a[I&255]^n[K+1],b=a[A>>>24]<<24^a[x>>16&255]<<16^a[I>>8&255]<<8^a[L&255]^n[K+2],R=a[x>>>24]<<24^a[I>>16&255]<<16^a[L>>8&255]<<8^a[A&255]^n[K+3],E[t]=F(S^g),E[t+1]=F(R^f),E[t+2]=F(b^p),E[t+3]=F(T^m),g=_,f=w,p=G,m=B,t=t+4}return E.buffer}}class fp{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(){const e=gp(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function gp(r){switch(r){case jt.cbc:return"AES-CBC";case jt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const pp=16;class zr{constructor(e,t){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,t!==!0)try{const 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(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);this.reset();const s=this.decryptRange;return s?s.start===0&&s.end>=i.length?i:i.slice(s.start,s.end):hp(i)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s,n){return this.decryptRange=n,this.useSoftware||n?new Promise((a,o)=>{const l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,i,s);const c=this.flush();c?a(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:n,currentResult:a,remainderData:o}=this;if(s!==jt.cbc||t.byteLength!==16)return be.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Et(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;n&&(i=n);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new dp),c.expandKey(t);const u=a;return this.currentResult=c.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,u||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 fp(this.subtle,t,s)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new up(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(be.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%pp;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(be.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const kl=Math.pow(2,17);class Ol{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t,i,s){const n=e.url;if(!n)return Promise.reject(new Ot({type:se.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,o=a.fLoader,l=a.loader;return new Promise((c,u)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){u(Ml(e));return}else e.gap=!1;const h=this.loader=o?new o(a):new l(a),d=Fl(e,null,t);e.loader=h;const g=Bo(a.fragLoadPolicy.default),f={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:kl};h.stats.retry=e.stats.retry,e.stats=h.stats;const p={onSuccess:(m,y,E,S)=>{this.resetLoader(e,h);let T=m.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),c({frag:e,part:null,payload:T,networkDetails:S})},onError:(m,y,E,S)=>{this.resetLoader(e,h),u(new Ot({type:se.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:re({url:n,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:E,stats:S}))},onAbort:(m,y,E)=>{this.resetLoader(e,h),u(new Ot({type:se.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:E,stats:m}))},onTimeout:(m,y,E)=>{this.resetLoader(e,h),u(new Ot({type:se.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:E,stats:m}))}};if(i){const m=this.gateProgress(i,s);p.onProgress=(y,E,S,T)=>m({frag:e,part:null,payload:S,networkDetails:T})}h.load(d,f,p)})}gateProgress(e,t){let i=e;if(t){const s=[];let n=!1;t.then(()=>{n=!0,s.forEach(a=>e(a)),s.length=0}).catch(()=>{}),i=a=>{n?e(a):s.push(a)}}return i}loadPart(e,t,i){this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Ml(e,t));return}const c=this.loader=n?new n(s):new a(s),u=Fl(e,t);e.loader=c;const h=Bo(s.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:kl};t.stats=c.stats,c.load(u,d,{onSuccess:(g,f,p,m)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const y={frag:e,part:t,payload:g.data,networkDetails:m};i(y),o(y)},onError:(g,f,p,m)=>{this.resetLoader(e,c),l(new Ot({type:se.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:re({url:u.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:m}))},onAbort:(g,f,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new Ot({type:se.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,f,p)=>{this.resetLoader(e,c),l(new Ot({type:se.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:g}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/n),l),h=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Fl(r,e=null,t){const i=e||r,s={type:pe.MEDIA_FRAGMENT,frag:r,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=Os(r,e,t);return n.resetIV&&(s.resetIV=!0),n.byteRange&&(s.rangeStart=n.byteRange.start,s.rangeEnd=n.byteRange.end),s}function Os(r,e=null,t){const i={},s=e||r,n=s.byteRangeStartOffset,a=s.byteRangeEndOffset;if(q(n)&&q(a)){var o;if((r.sn==="initSegment"||t)&&mp((o=r.decryptdata)==null?void 0:o.method)){let l=Math.floor(n/16)*16;const c=Math.ceil(a/16)*16;i.decryptRange={start:n-l,end:a-l},l>=16&&(i.resetIV=!0,l=l-16),i.byteRange={start:l,end:c}}else i.byteRange={start:n,end:a}}return i}function Ml(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:se.MEDIA_ERROR,details:D.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new Ot(i)}function mp(r){return r==="AES-128"||r==="AES-256"}class Ot extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Nl extends dt{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Xr{constructor(e,t,i,s=0,n=-1,a=!1,o,l,c){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=Fs(),this.buffering={audio:Fs(),video:Fs(),audiovideo:Fs()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=a,this.duration=o||0,this.decryptRange=c,this.iframe=l||!1}}function Fs(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Bl={length:0,start:()=>0,end:()=>0};class le{static isBuffered(e,t){if(e){const i=le.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){const t=le.getBuffered(e);return le.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const 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){const s=le.bufferedRanges(e);if(s.length)return le.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((u,h)=>u.start-h.start||h.end-u.end);let s=-1,n=[];if(i)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(s=u);const h=n.length;if(h){const d=n[h-1].end;e[u].start-d<i?e[u].end>d&&(n[h-1].end=e[u].end):n.push(e[u])}else n.push(e[u])}else n=e;let a=0,o,l=t,c=t;for(let u=0;u<n.length;u++){const h=n[u].start,d=n[u].end;if(s===-1&&t>=h&&t<=d&&(s=u),t+i>=h&&t<d)l=h,c=d,a=c-t;else if(t+i<h){o=h;break}}return{len:a,start:l||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||Bl}catch(t){return be.log("failed to get media.buffered",t),Bl}}}const Qr=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ul(r){return Qr.lastIndex=0,Qr.test(r)}function Jr(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(Qr,i=>{const s=i.substring(2,i.length-1),n=t==null?void 0: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 $l(r,e,t){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const 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 yp(r,e,t){const 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}"`))}const vp=/^(\d+)x(\d+)$/,Gl=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Oe{constructor(e,t){typeof e=="string"&&(e=Oe.parseAttrList(e,t)),Re(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const 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;const 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){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((s,n)=>(s[n.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=vp.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const s={};for(Gl.lastIndex=0;(i=Gl.exec(e))!==null;){const a=i[1].trim();let o=i[2];const l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let c=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(t&&(l||c))o=Jr(t,o);else if(!c&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":be.warn(`${e}: attribute ${a} is missing quotes`)}s[a]=o}return s}}const Ep="com.apple.hls.interstitial";function Sp(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function Tp(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class Vl{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==null?void 0:t.tagAnchor)||null,this.tagOrder=(s=t==null?void 0:t.tagOrder)!=null?s:i,t){const n=t.attr;for(const a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){be.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=Re(new Oe({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){const n=(t==null?void 0:t.endDate)||new Date(e["END-DATE"]);q(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const 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(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(be.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(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(q(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===Ep}get isValid(){return!!this.id&&!this._badValueForSameId&&q(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:q(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}}const Hl=10;class bp{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?q(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Hl}get drift(){const 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(){const e=this.partList;if(e){const 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){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Ms(r,e){return r.length===e.length?!r.some((t,i)=>t!==e[i]):!1}function Kl(r,e){return!r&&!e?!0:!r||!e?!1:Ms(r,e)}function Ti(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function Zr(r){switch(r){case"AES-128":case"AES-256":return jt.cbc;case"AES-256-CTR":return jt.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function en(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function Ap(r){const e=en(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function ql(r){const e=function(i,s,n){const 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 Wl(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const n=s[0]==="base64",a=s[1];n?(i.splice(-1,1),t=Nr(a)):t=Ap(a)}}return t}const Ns=typeof self<"u"?self:void 0;var we={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ye={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Bs(r){switch(r){case Ye.FAIRPLAY:return we.FAIRPLAY;case Ye.PLAYREADY:return we.PLAYREADY;case Ye.WIDEVINE:return we.WIDEVINE;case Ye.CLEARKEY:return we.CLEARKEY}}var jl={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function tn(r){switch(r){case we.FAIRPLAY:return Ye.FAIRPLAY;case we.PLAYREADY:return Ye.PLAYREADY;case we.WIDEVINE:return Ye.WIDEVINE;case we.CLEARKEY:return Ye.CLEARKEY}}function ji(r){const{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[we.FAIRPLAY,we.WIDEVINE,we.PLAYREADY,we.CLEARKEY].filter(s=>!!e[s]):[];return!i[we.WIDEVINE]&&t&&i.push(we.WIDEVINE),i}const Yl=(function(r){return Ns!=null&&(r=Ns.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function xp(r,e,t,i){let s;switch(r){case we.FAIRPLAY:s=["cenc","sinf"];break;case we.WIDEVINE:case we.PLAYREADY:s=["cenc"];break;case we.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Ip(s,e,t,i)}function Ip(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 Rp(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function sn(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=bt(e),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=Nr(o).subarray(0,16);return ql(l),l}}return null}let bi={};class Ut{static clearKeyUriToKeyIdMap(){bi={}}static setKeyIdForUri(e,t){bi[e]=t}static addKeyIdForUri(e){const t=Object.keys(bi).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),bi[e]=i,i}constructor(e,t,i,s=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ti(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Yo(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Ms(e.keyFormatVersions,this.keyFormatVersions)&&Kl(e.iv,this.iv)&&Kl(e.keyId,this.keyId)}isSupported(){if(this.method){if(Ti(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ye.FAIRPLAY:case Ye.WIDEVINE:case Ye.PLAYREADY:case Ye.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var i;if(!this.encrypted||!this.uri)return null;if(Ti(this.method)){let a=this.iv;return a||(typeof e!="number"&&(be.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=_p(e)),new Ut(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){const a=bi[this.uri];if(a&&!Ms(this.keyId,a)&&Ut.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Wl(this.uri);if(s)switch(this.keyFormat){case Ye.WIDEVINE:if(this.pssh=s,!this.keyId){const a=ll(s.buffer).filter(o=>o.systemId===jl.WIDEVINE);if(a.length){var n;const o=a[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=zl(t));break;case Ye.PLAYREADY:{const a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Pg(a,null,s),this.keyId=sn(s);break}default:{let a=s.subarray(0,16);if(a.length!==16){const o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a;break}}if(((i=this.keyId)==null?void 0:i.byteLength)!==16){let a;a=Lp(t),a||(a=zl(t),a||(a=bi[this.uri])),a&&(this.keyId=a,Ut.setKeyIdForUri(this.uri,a))}return this}}function Lp(r){const e=r==null?void 0:r[Ye.WIDEVINE];return e?e.keyId:null}function zl(r){const e=r==null?void 0:r[Ye.PLAYREADY];if(e){const t=Wl(e.uri);if(t)return sn(t)}return null}function _p(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const Xl=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Ql=/#EXT-X-MEDIA:(.*)/g,Pp=/^#EXT(?:INF|-X-TARGETDURATION):/m,rn=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Dp=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ft{static findGroup(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.id===t)return s}}static resolve(e,t){return Lr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Pp.test(e)}static parseMasterPlaylist(e,t){const i=Ul(e),s={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];if(Xl.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let a;for(;(a=Xl.exec(e))!=null;)if(a[1]){const l=new Oe(a[1],s),c=Jl(l,a[2],t,s,n);c&&s.levels.push(c)}else if(a[3]){const l=a[3],c=a[4];switch(l){case"I-FRAME-STREAM-INF":{const u=new Oe(c,s),h=Jl(u,u.URI,t,s,n,!0);h&&s.iframeVariants.push(h)}break;case"SESSION-DATA":{const u=new Oe(c,s),h=u["DATA-ID"];h&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[h]=u);break}case"SESSION-KEY":{const u=ec(c,t,s);u.encrypted&&u.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(u)):be.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{const u=new Oe(c,s);$l(s,u,t)}break}case"CONTENT-STEERING":{const u=new Oe(c,s);s.contentSteering={uri:Ft.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=tc(c);break}}}const o=n.length>0&&n.length<s.levels.length;return s.levels=o?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s;const n={},a=i.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Ql.lastIndex=0;(s=Ql.exec(e))!==null;){const c=new Oe(s[1],i),u=c.TYPE;if(u){const h=o[u],d=n[u]||[];n[u]=d;const g=c.LANGUAGE,f=c["ASSOC-LANGUAGE"],p=c.CHANNELS,m=c.CHARACTERISTICS,y=c["INSTREAM-ID"],E={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||g||"",type:u,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:g,url:c.URI?Ft.resolve(c.URI,t):""};if(f&&(E.assocLang=f),p&&(E.channels=p),m&&(E.characteristics=m),y&&(E.instreamId=y),h!=null&&h.length){const S=Ft.findGroup(h,E.groupId)||h[0];sc(E,S,"audioCodec"),sc(E,S,"textCodec")}d.push(E)}}return n}static parseLevelPlaylist(e,t,i,s,n,a){var o;const l={url:t},c=new bp(t),u=c.fragments,h=[];let d=null,g=0,f=0,p=0,m=0,y=0,E=null,S=new ys(s,l),T,b,R,I=-1,L=!1,A=null,x;if(rn.lastIndex=0,c.m3u8=e,c.hasVariableRefs=Ul(e),((o=rn.exec(e))==null?void 0:o[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(T=rn.exec(e))!==null;){L&&(L=!1,S=new ys(s,l),S.playlistOffset=p,S.setStart(p),S.sn=g,S.cc=m,y&&(S.bitrate=y),S.level=i,d&&(S.initSegment=d,d.rawProgramDateTime&&(S.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),A&&(S.setByteRange(A),A=null)));const K=T[1];if(K){S.duration=parseFloat(K);const O=(" "+T[2]).slice(1);S.title=O||null,S.tagList.push(O?["INF",K,O]:["INF",K])}else if(T[3]){if(q(S.duration)){var _;S.playlistOffset=p,S.setStart(p),R&&nc(S,R,c),S.sn=g,S.level=i,S.cc=m;const O=(" "+T[3]).slice(1);S.relurl=Jr(c,O),nn(S,E,h),E=S,p+=S.duration,g++,f=0;const F=S.byteRange;if(F.length===2&&(S.bitrate=(F[1]-F[0])*8/S.duration|0),c.iframesOnly&&F[0]&&((_=d)==null?void 0:_.cc)!==m){const M=new ys(s,l);M.relurl=S.relurl,M.setByteRange(`${Math.min(F[0],1316)}@0`),M.level=i,M.sn="initSegment",R&&(M.levelkeys=R,R.identity&&(M._decryptdata=R.identity.getDecryptData(0))),d=M,S.initSegment=d}u.push(S),L=!0}}else{if(T=T[0].match(Dp),!T){be.warn("No matches on slow regex match for level playlist!");continue}for(b=1;b<T.length&&T[b]===void 0;b++);const O=(" "+T[b]).slice(1),F=(" "+T[b+1]).slice(1),M=T[b+2]?(" "+T[b+2]).slice(1):null;switch(O){case"BYTERANGE":E?S.setByteRange(F,E):S.setByteRange(F);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=F,S.tagList.push(["PROGRAM-DATE-TIME",F]),I===-1&&(I=u.length);break;case"PLAYLIST-TYPE":c.type&&$t(c,O,T),c.type=F.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?$t(c,O,T):E!==null&&kp(c,O,T),c.startSN=parseInt(F),g=c.startSN+c.skippedSegments;break;case"SKIP":{c.skippedSegments&&$t(c,O,T);const V=new Oe(F,c),$=V.decimalInteger("SKIPPED-SEGMENTS");if(q($)){c.skippedSegments+=$;for(let H=$;H--;)u.push(null);g+=$}const C=V.enumeratedString("RECENTLY-REMOVED-DATERANGES");C&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(C.split(" ")));break}case"TARGETDURATION":c.targetduration!==0&&$t(c,O,T),c.targetduration=Math.max(parseInt(F),1);break;case"VERSION":c.version!==null&&$t(c,O,T),c.version=parseInt(F);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":c.iframesOnly=!0;break;case"ENDLIST":c.live||$t(c,O,T),c.live=!1;break;case"#":(F||M)&&S.tagList.push(M?[F,M]:[F]);break;case"DISCONTINUITY":m++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([O]);break;case"BITRATE":S.tagList.push([O,F]),y=parseInt(F)*1e3,q(y)?S.bitrate=y:y=0;break;case"DATERANGE":{const V=new Oe(F,c),$=new Vl(V,c.dateRanges[V.ID],c.dateRangeTagCount);c.dateRangeTagCount++,$.isValid||c.skippedSegments?c.dateRanges[$.id]=$:be.log(`Ignoring invalid DATERANGE tag: ${$.invalidReason}: ${F}`),S.tagList.push(["EXT-X-DATERANGE",F]);break}case"DEFINE":{{const V=new Oe(F,c);"IMPORT"in V?yp(c,V,a):$l(c,V,t)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0&&$t(c,O,T),c.startCC=m=parseInt(F),u.forEach(V=>V&&(V.cc=m));break;case"KEY":{const V=ec(F,t,c);if(V.isSupported()){if(V.method==="NONE"){R=void 0;break}R||(R={});const $=R[V.keyFormat];$!=null&&$.matches(V)||($&&(R=Re({},R)),R[V.keyFormat]=V)}else be.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${F}"`);break}case"START":c.startTimeOffset=tc(F);break;case"MAP":{const V=new Oe(F,c);if(S.duration){const $=new ys(s,l);rc($,V,i,R),d=$,S.initSegment=d,d.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=d.rawProgramDateTime)}else{const $=S.byteRangeEndOffset;if($){const C=S.byteRangeStartOffset;A=`${$-C}@${C}`}else A=null;rc(S,V,i,R),d=S,L=!0}d.cc=m;break}case"SERVER-CONTROL":{x&&$t(c,O,T),x=new Oe(F),c.canBlockReload=x.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=x.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&x.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=x.optionalFloat("PART-HOLD-BACK",0),c.holdBack=x.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{c.partTarget&&$t(c,O,T);const V=new Oe(F);c.partTarget=V.decimalFloatingPoint("PART-TARGET");break}case"PART":{let V=c.partList;V||(V=c.partList=[]);const $=f>0?V[V.length-1]:void 0,C=f++,H=new Oe(F,c),Q=new Nf(H,S,l,C,$);V.push(Q),S.duration+=Q.duration;break}case"PRELOAD-HINT":{const V=new Oe(F,c);c.preloadHint=V;break}case"RENDITION-REPORT":{const V=new Oe(F,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(V);break}default:be.warn(`line parsed but not handled: ${T}`);break}}}E&&!E.relurl?(u.pop(),p-=E.duration,c.partList&&(c.fragmentHint=E)):c.partList&&(nn(S,E,h),S.cc=m,c.fragmentHint=S,R&&nc(S,R,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const w=u.length,G=u[0],B=u[w-1];if(p+=c.skippedSegments*c.targetduration,p>0&&w&&B){c.averagetargetduration=p/w;const K=B.sn;c.endSN=K!=="initSegment"?K:0,c.live||(B.endList=!0),I>0&&(Cp(u,I,I>w-1?S:null),G&&h.unshift(G))}return c.fragmentHint&&(p+=c.fragmentHint.duration),c.totalduration=p,h.length&&c.dateRangeTagCount&&G&&Zl(h,c),c.endCC=m,c}}function Jl(r,e,t,i,s,n){var a;if(e===void 0)return null;const o=Jr(i,e),l={attrs:r,bitrate:r.decimalInteger("BANDWIDTH")||r.decimalInteger("AVERAGE-BANDWIDTH"),name:r.NAME,url:Ft.resolve(o,t)},c=r.decimalResolution("RESOLUTION");c&&(l.width=c.width,l.height=c.height),ic(r.CODECS,l);const u=r["SUPPLEMENTAL-CODECS"];return u&&(l.supplemental={},ic(u,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||s.push(l),n&&(l.iframes=!0),l}function Zl(r,e){let t=r.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];r.push(o),t++}else return;const i=r[t-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],c=l.startDate.getTime();l.tagAnchor=i.ref;for(let u=t;u--;){var a;if(((a=r[u])==null?void 0:a.sn)<e.startSN)break;const h=wp(e,c,r,u,s);if(h){l.tagAnchor=h.ref;break}}}}function wp(r,e,t,i,s){const n=t[i];if(n){const o=n.programDateTime;if(e>=o||i===0){var a;const l=(((a=t[i+1])==null?void 0:a.start)||s)-n.start;if(e<=o+l*1e3){const c=n.sn-r.startSN,u=r.fragments;if(c>=0&&c<u.length){if(u.length>t.length){const h=t[i+1]||u[u.length-1],d=Math.min(h.sn-r.startSN,u.length-1);for(let g=d;g>c;g--){const f=u[g].programDateTime;if(e>=f&&e<f+u[g].duration*1e3)return u[g]}}return u[c]}}}}return null}function ec(r,e,t){var i,s;const n=new Oe(r,t),a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),c=n.KEYFORMATVERSIONS,u=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!l&&be.error(`Invalid IV: ${n.IV}`);const h=o?Ft.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Ut(a,h,u,d,l,n.KEYID)}function tc(r){const t=new Oe(r).decimalFloatingPoint("TIME-OFFSET");return q(t)?t:null}function ic(r,e){let t=(r||"").split(/[ ,]+/).filter(i=>i);["video","audio","text","image"].forEach(i=>{const s=t.filter(n=>Kr(n,i));s.length&&(e[`${i}Codec`]=s.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>s.indexOf(n)===-1))}),e.unknownCodecs=t}function sc(r,e,t){const i=e[t];i&&(r[t]=i)}function Cp(r,e,t){if(t||(t=r[e]),!!t)for(let i=e;i--;){const s=r[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function nn(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function rc(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 nc(r,e,t){r.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(r)}function $t(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function kp(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function an(r,e){const t=e.startPTS;if(q(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 ac(r,e,t,i,s,n,a,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,n=s+e.duration);let c=t,u=i;const h=e.startPTS,d=e.endPTS;if(q(h)){const E=Math.abs(h-t);r&&E>r.totalduration?o.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${r.url}`):q(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,c=Math.max(t,h),t=Math.min(t,h),s=e.startDTS!==void 0?Math.min(s,e.startDTS):s,u=Math.min(i,d),i=Math.max(i,d),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}const g=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=u,e.endDTS=n;const f=e.sn;if(!r||f<r.startSN||f>r.endSN)return 0;let p;const m=f-r.startSN,y=r.fragments;for(y[m]=e,p=m;p>0;p--)an(y[p],y[p-1]);for(p=m;p<y.length-1;p++)an(y[p],y[p+1]);return r.fragmentHint&&an(y[y.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,g}function Op(r,e,t){if(r===e)return;let i=null;const s=r.fragments;for(let u=s.length-1;u>=0;u--){const h=s[u].initSegment;if(h){i=h;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;Np(r,e,(u,h,d,g)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==u.cc){const f=u.cc-h.cc;for(let p=d;p<g.length;p++)g[p].cc+=f;e.endCC=g[g.length-1].cc}q(u.startPTS)&&q(u.endPTS)&&(h.setStart(h.startPTS=u.startPTS),h.startDTS=u.startDTS,h.maxStartPTS=u.maxStartPTS,h.endPTS=u.endPTS,h.endDTS=u.endDTS,h.minEndPTS=u.minEndPTS,h.setDuration(u.endPTS-u.startPTS),h.duration&&(n=h),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(h.elementaryStreams=u.elementaryStreams),h.loader=u.loader,u.hasStats&&(h.stats=u.stats),u.initSegment&&(h.initSegment=u.initSegment,i=u.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(u=>{var h;u&&(!u.initSegment||u.initSegment.relurl===((h=i)==null?void 0:h.relurl))&&(u.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Fp(r.dateRanges,e,t));const u=r.fragments.filter(h=>h.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let h=1;h<o.length;h++)o[h].programDateTime===null&&nn(o[h],o[h-1],u);Zl(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const u=uc(r,e.startSN-1);e.startCC=(l=u==null?void 0:u.cc)!=null?l:a[0].cc}if(Mp(r.partList,e.partList,(u,h)=>{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats,h.gap=u.gap||h.gap}),n){const u=e.iframesOnly&&n.type===te.MAIN;ac(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,u,t)}else lc(r,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const c=e.advancedDateTime;if(e.advanced&&c){const u=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=u),e.driftEndTime=c,e.driftEnd=u}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function Fp(r,e,t){const{dateRanges:i,recentlyRemovedDateranges:s}=e,n=Re({},r);s&&s.forEach(l=>{delete n[l]});const o=Object.keys(n).length;return o?(Object.keys(i).forEach(l=>{const c=n[l],u=new Vl(i[l].attr,c);u.isValid?(n[l]=u,c||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Pe(i[l].attr)}"`)}),n):i}function Mp(r,e,t){if(r&&e){let i=0;for(let s=0,n=r.length;s<n;s++){const a=r[s],o=e[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Np(r,e,t){var i;const s=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,a=(r.fragmentHint?1:0)+(s?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,o=e.startSN-r.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=(i=r.fragmentHint)!=null&&i.duration?r.fragments.concat(r.fragmentHint):r.fragments;for(let u=n;u<=a;u++){const h=c[o+u];let d=l[u];if(s&&!d&&h&&(d=e.fragments[u]=h),h&&d){t(h,d,u,l);const g=h.relurl,f=d.relurl;if(g&&Up(g,f)){e.playlistParsingError=oc(`media sequence mismatch ${d.sn}:`,r,e,h,d);return}else if(h.cc!==d.cc){e.playlistParsingError=oc(`discontinuity sequence mismatch (${h.cc}!=${d.cc})`,r,e,h,d);return}}}}function oc(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 lc(r,e,t=!0,i){const s=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,a=s>=0;let o=0;if(a&&s<n.length)o=n[s].start,i==null||i.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===r.endSN+1)o=r.fragmentEnd,i==null||i.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=r.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=r.fragmentStart,i==null||i.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return Bp(e,o),o}function Bp(r,e){if(e){const t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function cc(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const i=r.fragments;if(i.length&&t*4>e){const n=i[i.length-1].duration*1e3;n>0&&n<t&&(t=n)}}else t/=2;return Math.round(t)}function uc(r,e,t){var i;if(!r)return null;let s=r.fragments[e-r.startSN];return s||(s=r.fragmentHint,((i=s)==null?void 0:i.sn)===e)?s:t&&e<r.startSN&&t.sn===e?t:null}function hc(r,e,t){return r?dc(r.partList,e,t):null}function dc(r,e,t){if(r)for(let i=r.length;i--;){const s=r[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function fc(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 Up(r,e){return r!==e&&e?gc(r)!==gc(e):!1}function gc(r){return r.replace(/\?[^?]*$/,"")}function Yi(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 $p(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function pc(r,e){const t=r.start+e;r.setStart(t)}function mc(r,e){const t=e.fragments;for(let i=0,s=t.length;i<s;i++)pc(t[i],r);e.fragmentHint&&pc(e.fragmentHint,r),e.alignedSliding=!0}function Us(r,e,t){r&&(Gp(e,r,t),e.alignedSliding||Vp(e,r,t),!e.alignedSliding&&!e.skippedSegments&&lc(r,e,!1,t))}function Gp(r,e,t){if(!$p(e,r))return;const i=Math.min(e.endCC,r.endCC),s=Yi(e.fragments,i),n=Yi(r.fragments,i);if(!s||!n)return;const a=s.start-n.start;t.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),mc(a,r)}function Vp(r,e,t){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const i=r.fragments,s=e.fragments;if(!i.length||!s.length)return;let n,a;const o=Math.min(e.endCC,r.endCC);e.startCC<o&&r.startCC<o&&(n=Yi(s,o),a=Yi(i,o)),(!n||!a)&&(n=s[Math.floor(s.length/2)]||s.filter(d=>!!d)[0],a=Yi(i,n.cc)||i[Math.floor(i.length/2)]);const l=n.programDateTime,c=a.programDateTime;if(!l||!c)return;const u=(c-l)/1e3;if(Math.abs(u)>Math.max(60,r.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(u)} > ${r.totalduration})`);return}const h=u-(a.start-n.start);t.log(`Aligning playlists using PDT (diff: ${h})`),mc(h,r)}function xe(r,e,t){Ae(r,e,t),r.addEventListener(e,t)}function Ae(r,e,t){r.removeEventListener(e,t)}function $s(r){let e="";const t=r.length;for(let i=0;i<t;i++)e+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return e}const U={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"};class on extends Nl{constructor(e,t,i,s,n){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=U.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:l,mediaBuffer:c,state:u}=this,h=l?l.currentTime:0,d=le.bufferInfo(c||l,h,a.maxBufferHole),g=d.len;if(this.log(`Media seeking to ${h}, state: ${u}, ${g?"in":"out of"} buffer`),this.state===U.ENDED)this.resetLoadingState();else if(o){const p=a.maxFragLookUpTolerance,m=o.start-p,y=o.start+o.duration+p;if(!g||y<d.start||m>d.end){const E=h<m,S=h>y;(E||S)&&(o.loader&&(S||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${E?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);const p=this.lastCurrentTime;if(h>p&&(this.lastCurrentTime=h),!this.loadingParts){const m=Math.max(d.end,h),y=this.shouldLoadParts(this.getLevelDetails(),m);y&&(this.log(`LL-Part loading ON after seeking to ${h} with buffer @${m}`),this.loadingParts=y)}}const f=!le.isBuffered(l,h);(!this.hls.hasEnoughToStart||f)&&(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,f&&(this.startPosition=h)),g<1&&this.state===U.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 Ol(e.config),this.initFragmentLoader=new Ol(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new zr(e.config)}registerListeners(){const{hls:e}=this;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===U.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const 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=U.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){const i=this.getLevelDetails();return i!=null&&i.live?(this.hls.liveSyncPosition||i.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=le.bufferedInfo(n,e.start,0));const a=e.nextStart;if(a&&a>s&&a<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const u=l[l.length-1];return le.isBuffered(this.media,u.start+u.duration/2)}const c=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(c.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;xe(i,"seeking",this.onMediaSeeking),xe(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===U.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;const 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.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=U.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const s=n=>{const 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}const o=++a.stats.chunkCount;this.log(`load progress ${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)} chunk: ${o}`),this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,s).then(n=>{if(!n)return;const a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===U.FRAG_LOADING||!this.fragCurrent&&a===U.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=U.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(v.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===U.STOPPED||this.state===U.ERROR||(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===ke.APPENDING){const n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===ke.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=this.fragmentTracker,i=e.fragments[e.fragments.length-1];if(i.endList&&!t.isEndListAppended(this.playlistType)){const s=t.getPartialFragment(i.end);s&&(t.removeFragment(s),t.fragBuffered(i,!0))}t.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(v.BUFFER_FLUSHING,s)}_loadInitSegment(e){const{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(v.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(i=>{var s;const n=i.frag;if(!this.levels||!Pr(n,(s=this.fragCurrent)==null?void 0:s.initSegment))throw new Ot({type:se.NETWORK_ERROR,details:D.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:n,networkDetails:null});return i}).then(i=>{const{frag:s,payload:n}=i,a=s.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&Ti(a.method)){const o=self.performance.now(),{decryptRange:l}=Os(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Zr(a.method),l).catch(c=>{throw t.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:s}),this.fragmentLoader.abort(),c}).then(c=>{const u=self.performance.now();return t.trigger(v.FRAG_DECRYPTED,{frag:s,part:null,payload:c,stats:{tstart:o,tdecrypt:u}}),i.payload=c,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)})}completeInitSegmentLoad(e){const t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){const{initSegment:t}=e;if(!this.bitrateTest&&Ne(e)&&t&&!t.data){var i;return(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(n=>{throw this.state===U.STOPPED||this.state===U.ERROR||("data"in n&&(n.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(n)),this.resetFragmentLoading(e)),n})}}unhandledEncryptionError(e,t){var i,s;const 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)){const 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(v.ERROR,{type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!Pr(e,t)}fragBufferedComplete(e,t){const 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?$s(le.getBuffered(i)):"(detached)"})`),Ne(e)){var s;if(e.type!==te.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=U.IDLE;return}}const n=(s=this.levels)==null?void 0:s[e.level];n!=null&&n.fragmentError&&(t||this.fragmentTracker.getState(e)!==ke.PARTIAL)&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0,e.stats.retry=0)}this.state=U.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const i=e.frag,{part:s,partsLoaded:n}=e,a=!n||n.length===0||n.some(c=>!c),{decryptRange:o}=Os(i,s),l=new Xr(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a,i.duration,this.iframesOnly,o);this.log(`load complete ${i.type} sn: ${i.sn}${s?" part: "+s.index:""} of ${this.fragInfo(i,!1,s)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,i){var s;let n=null;return e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=U.KEY_LOADING,n=this.keyLoader.load(e,i).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(v.KEY_LOADED,a),this.state===U.KEY_LOADING&&(this.state=U.IDLE),a}),this.hls.trigger(v.KEY_LOADING,{frag:e})):e.encrypted||(n=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),n&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),n}_doFragLoad(e,t,i=null,s){this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);const a=this.fragPrevious;if(!Fi(e,a)){const g=this.shouldLoadParts(t.details,e.end);g!==this.loadingParts&&(this.log(`LL-Part loading ${g?"ON":"OFF"} loading sn ${a==null?void 0:a.sn}->${e.sn}`),this.loadingParts=g)}if(i=Math.max(e.start,i||0),this.loadingParts){const g=n.partList;if(g&&s){i>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const f=this.getNextPart(g,e,i);if(f>-1){const p=g[f];if(e=this.fragCurrent=p.fragment,!Fi(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,p)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(p,t.details))return Promise.resolve(null);const m=this.loadKeyFor(e,n);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${f}/${g.length-1}) of ${this.fragInfo(e,!1,p)} cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${i}${p.byteRange.length?` range:${p.byteRange.join("-")}`:""}`),this.nextLoadPosition=p.start+p.duration,this.state=U.FRAG_LOADING;let y;const E=this.loadInitSegmentIfNeeded(e);if(m||E){const S=!!m;y=Promise.all([m,E]).then(([T])=>S&&(!T||this.fragContextChanged(T.frag))?null:this.doFragPartsLoad(e,p,t,s)).catch(T=>this.handleFragLoadError(T))}else y=this.doFragPartsLoad(e,p,t,s).catch(S=>this.handleFragLoadError(S));return this.hls.trigger(v.FRAG_LOADING,{frag:e,part:p,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(g,i))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${e.sn} loaded parts: ${(o=n.partList)==null?void 0:o.filter(g=>g.loaded).map(g=>`[${g.start}-${g.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);const l=this.loadInitSegmentIfNeeded(e),c=this.loadKeyFor(e,n,l);if(this.fragContextChanged(e)){var u;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(u=this.fragCurrent)==null?void 0:u.relurl}`),l==null||l.catch(()=>null),c==null||c.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${i}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),q(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=U.FRAG_LOADING;const h=this.config.progressive&&e.type!==te.SUBTITLE;let d;return h&&c?d=c.then(g=>!g||this.fragContextChanged(g.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,s,l)).catch(g=>this.handleFragLoadError(g)):d=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,h?s:void 0,h?l:void 0),c,l]).then(([g])=>(!h&&s&&s(g),g)).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(v.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([d,l]).then(([g])=>g)}doFragPartsLoad(e,t,i,s){return new Promise((n,a)=>{var o;const l=[],c=(o=i.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(e,h,s).then(d=>{l[h.index]=d;const g=d.part;this.hls.trigger(v.FRAG_LOADED,d);const f=hc(i.details,e.sn,h.index+1)||dc(c,e.sn,h.index+1);if(f)u(f);else return n({frag:e,part:g,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===D.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===se.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(v.ERROR,t)}else this.hls.trigger(v.ERROR,{type:se.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==U.PARSING){!this.fragCurrent&&this.state!==U.STOPPED&&this.state!==U.ERROR&&(this.state=U.IDLE);return}const{frag:i,part:s,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a);const o=this.getLevelDetails(),c=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=c),this.updateLevelTiming(i,s,n,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var i;const s=e.partList[0],n=s.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=n&&this.playhead>s.start-s.fragment.duration)return!0}}return!1}getCurrentContext(e){const{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;const o=t[s],l=o.details,c=a>-1?hc(l,n,a):null,u=c?c.fragment:uc(l,n,i);return u?(i&&i!==u&&(u.stats=i.stats),{frag:u,part:c,level:o}):null}bufferFragmentData(e,t,i,s,n){if(this.state!==U.PARSING)return;Ne(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);const{data1:a,data2:o}=e;let l=a;if(o&&(l=Et(a,o)),!l.length)return;const c=this.initPTS[t.cc],u=c?-c.baseTime/c.timescale:void 0,h={type:e.type,frag:t,part:i,chunkMeta:s,offset:u,parent:t.type,data:l};if(this.hls.trigger(v.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!le.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=le.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;const s=this.playhead,a=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,a)}getFwdBufferInfoAtPos(e,t,i,s){const n=le.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(n.nextStart,a.end)-t,s);return le.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){const s=e.nextStart;if(s&&i.start>s){const n=e.buffered;if(n){let a=e.len;const o=e.bufferedIndex;for(let l=n.length-1;l>o;l--)n[l].start<i.start&&(a+=n[l].end-n[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t/2),n=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return n>=s?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e){const t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:n}=this,a=t.fragmentStart,o=n.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const h=n.initialLiveManifestSize;if(s<h)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${h})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var c;l=this.getInitialLiveFragment(t);const d=this.config.startPosition,g=this.hls.startPosition,f=this.hls.liveSyncPosition,p=((c=l)==null?void 0:c.start)||0;let m,y;if(g!==-1&&g>=a?(m=g,y=g===d?"config":"next load start"):f?(m=f,y="live edge"):(m=e,y="buffer pos"),m<p&&(m=p,y="live frag start"),m<a&&(m=a,y="playlist start"),this.startPosition!=m||this.nextLoadPosition!=m){const S=t.live&&!this.filterReplacedPrimary(l,t)?-1:m;this.log(`Setting startPosition to ${S} next load ${m} ${g===-1?"":`(from ${d}) `}based on ${y}. live edge: ${f} live frag start: ${p} playlist start: ${a} buffer pos: ${e}`),this.startPosition=S,this.nextLoadPosition=m}}}else e<=a&&(l=i[0]);if(!l){const h=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,h,t)}let u=this.filterReplacedPrimary(l,t);return!u&&l&&(u=Pl(t,l.sn),u&&(this.nextLoadPosition=u.start)),u}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const i=this.fragmentTracker.getState(e);return!!(i===ke.OK||i===ke.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,i,s,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(o!==null&&i.len+o.len>=n){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Gs(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(Gs(this.config)&&("type"in e?e:e.fragment).type!==te.SUBTITLE){const i=this.hls.interstitialsManager,s=i==null?void 0:i.bufferingItem;if(s){const n=s.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-s.start)>1||s.start===0))return null}else if(e.end<=s.start&&(t==null?void 0:t.live)===!1||e.start>=s.end&&s.nextEvent&&(s.nextEvent.appendInPlace&&!s.nextEvent.hasPlayed||e.start-s.end>1))return null}if(yc(e,i==null?void 0:i.playerQueue,this.playhead))return null}return e}getNextPart(e,t,i){let s=-1,n=!1,a=!0;for(let l=0,c=e.length;l<c;l++){const u=e[l];if(a=a&&!u.independent,s>-1&&i<u.start)break;const h=u.loaded||u.gap;h?s=-1:(n||(u.independent||a)&&u.fragment===t)&&(s=l),n=h&&!u.gap}const o=e[s];return o&&o.fragment!==t&&this.log(`Need buffer at ${i} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(s=np(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!s){const n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){const 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=_l(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:c}=s,u=i.partList,h=!!(this.loadingParts&&u!=null&&u.length&&l);h&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),n&&this.fragmentTracker.getState(n)===ke.NOT_LOADED&&(n=null);let d;if(e<t){var g;const p=e<this.lastCurrentTime||e>t-c||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:c;d=Ei(n,a,e,p)}else d=a[a.length-1];if(d){const f=d.sn-i.startSN,p=this.fragmentTracker.getState(d);if((p===ke.OK||p===ke.PARTIAL&&d.gap)&&(n=d),Fi(d,n)&&(!h||u[0].fragment.sn>d.sn||!i.live)){const m=a[f+1];d.sn<o&&this.fragmentTracker.getState(m)!==ke.OK?d=m:d=null}}return d}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const n=e.fragmentStart,a=!t,o=e.alignedSliding&&q(n);if(a||!o&&!n){Us(i,e,this);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const s=this.timelineOffset;if(i===-1){const n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;if(a!==null&&q(a))i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i;else if(e.live){const o=this.hls.liveSyncPosition;i=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${i}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=i=0;this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;const i=(t=this.media)==null?void 0:t.currentTime;return q(i)?i:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==te.MAIN)return!1;const t=this.getLevelDetails();return t?t.iframesOnly:(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ne(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!==U.FRAG_LOADING_WAITING_RETRY)&&(this.state=U.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const{frag:i,part:s}=t;if(!i||!this.levels||i.type!==e)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${(n=this.fragCurrent)==null?void 0:n.relurl}`);return}const a=t.details===D.FRAG_GAP;a&&this.fragmentTracker.addAsGap(i);const o=t.errorAction;if(!o){this.state=U.ERROR;return}const{action:l,flags:c,retryCount:u=0,retryConfig:h}=o,d=!!h,g=d&&l===je.RetryRequest,f=d&&!o.resolved&&c&Ke.MoveAllAlternatesMatchingHost,p=this.hls.latestLevelDetails,m=p==null?void 0:p.live;if(!g&&f&&Ne(i)&&m&&i.sn<p.endSN&&!Mo(t))this.resetFragmentErrors(e),s?s.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((g||f)&&u<h.maxNumRetry){var y;const E=Ni((y=t.response)==null?void 0:y.code),S=Dr(h,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+S,this.state=U.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${u+1}/${h.maxNumRetry} in ${S}ms`)}else if(h)if(this.resetFragmentErrors(e),u<h.maxNumRetry)!a&&l!==je.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else l===je.SendAlternateToPenaltyBox?this.state=U.WAITING_LEVEL:this.state=U.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!Ni(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=U.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===U.PARSING||this.state===U.PARSED){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),n=s&&s.len>.5;n&&this.reduceMaxBufferLength(s.len,(t==null?void 0:t.duration)||10);const a=!n;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`):s.nextStart&&t&&s.nextStart>t.start&&this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,i===te.AUDIO?i:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===te.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==U.STOPPED&&(this.state=U.IDLE)}afterBufferFlushed(e,t){if(!e)return;const i=le.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,this.playlistType),this.state===U.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==U.STOPPED&&(this.state=U.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.getLevelDetails();e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){const n=i.details;if(!n){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((h,d)=>{const g=e.elementaryStreams[d];if(g){const f=g.endPTS-g.startPTS;if(f<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${f})`),h||!1;const p=s.partial?0:ac(n,e,g.startPTS,g.endPTS,g.startDTS,g.endDTS,this.iframesOnly,this);return this.hls.trigger(v.LEVEL_PTS_UPDATED,{details:n,level:i,drift:p,type:d,frag:e,start:g.startPTS,end:g.endPTS}),!0}return h},!1)){var o,l,c,u;const h=((o=this.transmuxer)==null?void 0:o.error)===null,d=((l=this.transmuxer)==null?void 0:l.error)!=null,g=((c=(u=this.levels)==null?void 0:u.length)!=null?c:0)>1;if((i.fragmentError===0||h&&(i.fragmentError<2||e.endList)||d&&g)&&this.treatAsGap(e,i),h){const f=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(f.message),this.hls.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:f,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=U.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(v.FRAG_PARSED,{frag:e,part:t,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,i){var s,n;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN}-${(n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;const i=(t=e.loader)==null?void 0:t.stats;if(!i)return!1;const s=i.loading.first>0,a=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&a<=.15}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let i=0;const{hls:s,media:n,config:a,levels:o,playlistType:l}=this,c=this.getLevelDetails();if(n&&!n.paused&&o){var u;const g=l===te.AUDIO?yl(e.audioCodec,128e3):e.maxBitrate,f=1+s.ttfbEstimate/1e3,p=s.bandwidthEstimate*a.abrBandWidthUpFactor,m=c&&(this.loadingParts?c.partTarget:c.averagetargetduration)||((u=this.fragCurrent)==null?void 0:u.duration)||6;i=f+g*m/p,e.details||(i+=f)}const h=this.playhead,d=!(c!=null&&c.live)||t.end-h>i*1.5;return{fetchdelay:i,okToFlushForwardBuffer:d}}scheduleTrackSwitch(e,t,i){const{media:s,playlistType:n}=this;if(!s||!e)return;const a=i?this.getBufferedFrag(this.playhead+t):null;if(a){const l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();const c=l.maxStartPTS?l.maxStartPTS:l.start,u=l.duration,h=Math.max(a.end,c+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>h)return;const g=n===te.MAIN?null:"audio";this.flushMainBuffer(h,Number.POSITIVE_INFINITY,g),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:e,playlistType:t}=this;if(!e)return;const i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){const s=t===te.AUDIO;this.flushMainBuffer(0,i.start-(s?0:1),s?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case U.KEY_LOADING:case U.FRAG_LOADING:case U.FRAG_LOADING_WAITING_RETRY:case U.PARSING:case U.PARSED:this.state=U.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(le.isBuffered(e,i)?t=this.getAppendedFrag(i):le.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t&&(this.backtrackFragment=void 0,!Fi(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:e,media:t,hls:i,config:s,playlistType:n}=this;if(t!=null&&t.readyState&&e&&i&&s){const a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,n);if(!o)return;const l=n===te.AUDIO?i.nextAudioTrack:i.nextLoadLevel,c=e[l],{fetchdelay:u,okToFlushForwardBuffer:h}=this.calculateOptimalSwitchPoint(c,o);this.scheduleTrackSwitch(o,u,h)}this.tickImmediate()}}function yc(r,e,t){if(e)for(let i=e.length;i--;){const s=e[i].interstitial,n=s.startTime,a=Math.min(n+s.duration,s.resumeTime);if(s.appendInPlace&&(r.start>=n&&r.end<=a||t>r.start&&r.end>n&&r.start<a))return!0}return!1}function Gs(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class vc{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=Hp(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Hp(r,e){const t=new Uint8Array(e);let i=0;for(let s=0;s<r.length;s++){const n=r[s];t.set(n,i),i+=n.length}return t}var ln={exports:{}},Ec;function Kp(){return Ec||(Ec=1,(function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function n(l,c,u,h,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,h||l,d),f=t?t+c:c;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],g]:l._events[f].push(g):(l._events[f]=g,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var d=0,g=h.length,f=new Array(g);d<g;d++)f[d]=h[d].fn;return f},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,d,g,f){var p=t?t+c:c;if(!this._events[p])return!1;var m=this._events[p],y=arguments.length,E,S;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),y){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,u),!0;case 3:return m.fn.call(m.context,u,h),!0;case 4:return m.fn.call(m.context,u,h,d),!0;case 5:return m.fn.call(m.context,u,h,d,g),!0;case 6:return m.fn.call(m.context,u,h,d,g,f),!0}for(S=1,E=new Array(y-1);S<y;S++)E[S-1]=arguments[S];m.fn.apply(m.context,E)}else{var T=m.length,b;for(S=0;S<T;S++)switch(m[S].once&&this.removeListener(c,m[S].fn,void 0,!0),y){case 1:m[S].fn.call(m[S].context);break;case 2:m[S].fn.call(m[S].context,u);break;case 3:m[S].fn.call(m[S].context,u,h);break;case 4:m[S].fn.call(m[S].context,u,h,d);break;default:if(!E)for(b=1,E=new Array(y-1);b<y;b++)E[b-1]=arguments[b];m[S].fn.apply(m[S].context,E)}}return!0},o.prototype.on=function(c,u,h){return n(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return n(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,d){var g=t?t+c:c;if(!this._events[g])return this;if(!u)return a(this,g),this;var f=this._events[g];if(f.fn)f.fn===u&&(!d||f.once)&&(!h||f.context===h)&&a(this,g);else{for(var p=0,m=[],y=f.length;p<y;p++)(f[p].fn!==u||d&&!f[p].once||h&&f[p].context!==h)&&m.push(f[p]);m.length?this._events[g]=m.length===1?m[0]:m:a(this,g)}return this},o.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(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})(ln)),ln.exports}var qp=Kp(),cn=Ff(qp);const zi="1.7.3",Ai={};function Wp(){return typeof __HLS_WORKER_BUNDLE__=="function"}function jp(){const r=Ai[zi];if(r)return r.clientCount++,r;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),s={worker:new self.Worker(t),objectURL:t,clientCount:1};return Ai[zi]=s,s}function Yp(r){const e=Ai[r];if(e)return e.clientCount++,e;const t=new self.URL(r,self.location.href).href,s={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Ai[r]=s,s}function zp(r){const e=Ai[r||zi];if(e&&e.clientCount--===1){const{worker:i,objectURL:s}=e;delete Ai[r||zi],s&&self.URL.revokeObjectURL(s),i.terminate()}}function Xp(r,e,t,i){const 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){const m=new Error(`invalid ADTS sampling index:${a}`);r.emit(v.ERROR,v.ERROR,{type:se.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!0,error:m,reason:m.message});return}const o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,c=s[a];let u=a;(o===5||o===29)&&(u-=3);let h;const d=(u&14)>>1,g=(u&1)<<7|l<<3;let f=0;if(o===1&&a>=6){f=5;const m=a-3;h=[f<<3|d,g|(m&14)>>1,(m&1)<<7|8,0]}else h=[o<<3|d,g];const p="mp4a.40."+(f||o);return be.log(`manifest codec:${i}, parsed codec:${p}, channels:${l}, rate:${c} (ADTS object type:${o} sampling index:${a} esds config:[${h.join(",")}])`),{config:h,samplerate:c,channelCount:l,codec:p,parsedCodec:p,manifestCodec:i}}function Sc(r,e){return r[e]===255&&(r[e+1]&246)===240}function Tc(r,e){return r[e+1]&1?7:9}function un(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function Qp(r,e){return e+5<r.length}function Vs(r,e){return e+1<r.length&&Sc(r,e)}function Jp(r,e){return Qp(r,e)&&Sc(r,e)&&un(r,e)<=r.length-e}function Zp(r,e){if(Vs(r,e)){const t=Tc(r,e);if(e+t>=r.length)return!1;const i=un(r,e);if(i<=t)return!1;const s=e+i;return s===r.length||Vs(r,s)}return!1}function bc(r,e,t,i,s){if(!r.samplerate){const n=Xp(e,t,i,s);if(!n)return;Re(r,n)}}function Ac(r){return 1024*9e4/r}function em(r,e){const t=Tc(r,e);if(e+t<=r.length){const i=un(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function xc(r,e,t,i,s){const n=Ac(r.samplerate),a=i+s*n,o=em(e,t);let l;if(o){const{frameLength:h,headerLength:d}=o,g=d+h,f=Math.max(0,t+g-e.length);f?(l=new Uint8Array(g-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+g);const p={unit:l,pts:a};return f||r.samples.push(p),{sample:p,length:g,missing:f}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}let st=(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 Mt(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class hn{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=Et(this.cachedData,e),this.cachedData=null);let i=Bi(e,0),s=i?i.length:0,n;const a=this._audioTrack,o=this._id3Track,l=i?Mr(i):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&q(l))&&(this.basePTS=tm(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:st.audioId3,duration:Number.POSITIVE_INFINITY});s<c;){if(this.canParse(e,s)){const u=this.appendFrame(a,e,s);u?(this.frameIndex++,this.lastPTS=u.sample.pts,s+=u.length,n=s):s=c}else eg(e,s)?(i=Bi(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:st.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===c&&n!==c){const u=e.slice(n);this.cachedData?this.cachedData=Et(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Mt(),id3Track:o,textTrack:Mt()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Mt(),id3Track:this._id3Track,textTrack:Mt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const tm=(r,e,t)=>{if(q(r))return r*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},im=[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],sm=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],rm=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],nm=[0,1,1,4];function Ic(r,e,t,i,s){if(t+24>e.length)return;const n=Rc(e,t);if(n&&t+n.frameLength<=e.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function Rc(r,e){const 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){const a=r[e+2]>>1&1,o=r[e+3]>>6,l=t===3?3-i:i===3?3:4,c=im[l*14+s-1]*1e3,h=sm[(t===3?0:t===2?1:2)*3+n],d=o===3?1:2,g=rm[t][i],f=nm[i],p=g*8*f,m=Math.floor(g*c/h+a)*f,y=Gi();return!!y&&y<=87&&i===2&&c>=224e3&&o===0&&(r[e+3]=r[e+3]|128),{sampleRate:h,channelCount:d,frameLength:m,samplesPerFrame:p}}}function dn(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Lc(r,e){return e+1<r.length&&dn(r,e)}function am(r,e){return dn(r,e)&&4<=r.length-e}function _c(r,e){if(e+1<r.length&&dn(r,e)){const i=Rc(r,e);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const n=e+s;return n===r.length||Lc(r,n)}return!1}class Pc{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new zr(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,jt.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let 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){const i=new Uint8Array(t);let 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){const a=ol(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const n=e[t].units;for(;!(i>=n.length);i++){const 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}}}}class om extends hn{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Bi(e,0);let s=(i==null?void 0:i.length)||0;if(_c(e,s))return!1;for(let n=e.length;s<n;s++)if(Zp(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Jp(e,t)}appendFrame(e,t,i){bc(e,this.observer,t,i,e.manifestCodec);const s=xc(e,t,i,this.basePTS,this.frameIndex);if((s==null?void 0:s.missing)===0)return s}demuxSampleAes(e,t,i){const s=this.demux(e,i),n=this.sampleAes=new Pc(this.observer,this.config,t);return new Promise(a=>{n.decryptAacSamples(s.audioTrack.samples,0,()=>{a(s)})})}}const Dc=(r,e)=>{let t=0,i=5;e+=i;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=r[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,t=t?t<<o|s[0]:s[0],e+=1,i-=o}return t};class lm extends hn{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){const s=wc(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;const t=Bi(e,0);if(!t)return!1;const i=t.length;if(e[i]===11&&e[i+1]===119&&Mr(t)!==void 0){if(Dc(e,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function wc(r,e,t,i,s){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const n=e[t+4]>>6;if(n>=3)return-1;const o=[48e3,44100,32e3][n],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+u>e.length)return-1;const h=e[t+6]>>5;let d=0;h===2?d+=2:(h&1&&h!==1&&(d+=2),h&4&&(d+=2));const g=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][h]+g,m=e[t+5]>>3,y=e[t+5]&7,E=new Uint8Array([n<<6|m<<1|y>>2,(y&3)<<6|h<<3|g<<2|l>>4,l<<4&224]),S=1536/o*9e4,T=i+s*S,b=e.subarray(t,t+u);return r.config=E,r.channelCount=p,r.samplerate=o,r.samples.push({unit:b,pts:T}),u}class cm extends hn{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;const t=Bi(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&Mr(t)!==void 0&&Dc(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(_c(e,i))return be.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return am(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Ic(e,t,i,this.basePTS,this.frameIndex)}}const um=/\/emsg[-/]ID3/i;class hm{constructor(e,t,i,s=be){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=t,this.logger=s}resetTimeStamp(){}resetInitSegment(e,t,i,s){const n=this.videoTrack=Mt("video",1),a=this.audioTrack=Mt("audio",1),o=this.txtTrack=Mt("text",1);if(this.id3Track=Mt("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=this.initData=tl(e);if(l.video){const{id:c,timescale:u,codec:h,supplemental:d}=l.video;n.id=c,n.timescale=o.timescale=u,n.codec=h,n.supplemental=d}if(l.audio){const{id:c,timescale:u,codec:h}=l.audio;a.id=c,a.timescale=u,a.codec=h}o.id=zo.text,n.sampleDuration=0,n.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return pg(e,"moof")}demux(e,t,i){this.timeOffset=t;let s=e;const n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Et(this.remainderData,e));const c=Ig(s);this.remainderData=c.remainder,n.samples=c.valid||new Uint8Array}else n.samples=s;const o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,i);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){const i=this.timeOffset,s=this.videoTrack,n=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;const a=this.extractID3Track(s,this.timeOffset),o=this.parseFragment(s,n,i,t);return{videoTrack:s,audioTrack:Mt(),id3Track:a,textTrack:Mt(),initData:this.initData,sampleData:o}}parseFragment(e,t,i,s){const n=this.initData;if(n&&s){const{samples:a,sampleData:o}=xg(i,e,n,this.logger,s.iframe);return t.samples=a,o}t.samples=Rg(i,e)}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=fe(e.samples,["emsg"]);s&&s.forEach(n=>{const a=Lg(n);if(um.test(a.schemeIdUri)){const o=Cc(a,t);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;i.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:st.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){const o=this.config.emsgKLVSchemaUri||st.misbklv;if(a.schemeIdUri.startsWith(o)){const l=Cc(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:st.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}function Cc(r,e){return q(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}const dm=1,fm=2,Xi=-1;class kc{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){const n=i.units;s=n[n.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,s=i.length;if(s){const n=i[s-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;if(s===0)return[];const n=e.naluState||0,a=n===Xi?0:n,o=[];let l=0,c=0,u=-1,h=0;for(n===Xi&&(u=0,h=this.getNALuType(t,0),c=1);c<s;){const d=t.indexOf(dm,c);if(d===-1)break;c=d+1;let g=d;for(;g>0&&t[g-1]===0;)g--;if(!(d-g+(g===0?a:0)<fm)){if(u>=0)o.push({data:t.subarray(u,g),type:h});else{const p=this.getLastNalUnit(e.samples);p&&(g>0?p.data=Et(p.data,t.subarray(0,g)):a>0&&(p.data=p.data.subarray(0,p.data.byteLength-a)),p.state=0)}if(c<s)u=c,h=this.getNALuType(t,c);else{l=Xi,u=-1;break}}}if(l!==Xi){let d=s;for(;d>0&&t[d-1]===0;)d--;l=s-d+(d===0?a:0)}if(u>=0)o.push({data:t.subarray(u),type:h,state:l});else if(o.length===0&&l!==Xi){const d=this.getLastNalUnit(e.samples);d&&(d.data=Et(d.data,t),d.state=l)}return e.naluState=l,o}}class Qi{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(){const 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);const i=this.word>>>32-t;if(e>32&&be.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(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class gm extends kc{parsePES(e,t,i,s,n){const a=n.iframe,o=this.parseNALu(e,i.data,s);let l=this.VideoSample,c,u=!1;i.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.forEach(h=>{var d,g;switch(h.type){case 1:{if(a)break;let y=!1;c=!0;const E=h.data;if(u&&E.length>4){const S=this.readSliceType(E);(S===2||S===4||S===7||S===9)&&(y=!0)}if(y){var f;(f=l)!=null&&f.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.frame=!0,l.key=y;break}case 5:c=!0,(d=l)!=null&&d.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;c=!0,$i(h.data,1,i.pts,t.samples);break}case 7:{var p,m;c=!0,u=!0;const y=h.data,E=this.readSPS(y);if(!e.sps||e.width!==E.width||e.height!==E.height||((p=e.pixelRatio)==null?void 0:p[0])!==E.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[y];const S=y.subarray(1,4);let T="avc1.";for(let b=0;b<3;b++){let R=S[b].toString(16);R.length<2&&(R="0"+R),T+=R}e.codec=T}break}case 8:c=!0,e.pps=[h.data];break;case 9:c=!0,e.audFound=!0,(g=l)!=null&&g.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:c=!0;break;default:c=!1;break}l&&c&&l.units.push(h)}),s&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Qi(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){const t=new Qi(e);let i=0,s=0,n=0,a=0,o,l,c;const u=t.readUByte.bind(t),h=t.readBits.bind(t),d=t.readUEG.bind(t),g=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),m=t.skipUEG.bind(t),y=this.skipScalingList.bind(this);u();const E=u();if(h(5),f(3),u(),m(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const L=d();if(L===3&&f(1),m(),m(),f(1),g())for(l=L!==3?8:12,c=0;c<l;c++)g()&&(c<6?y(16,t):y(64,t))}m();const S=d();if(S===0)d();else if(S===1)for(f(1),p(),p(),o=d(),c=0;c<o;c++)p();m(),f(1);const T=d(),b=d(),R=h(1);R===0&&f(1),f(1),g()&&(i=d(),s=d(),n=d(),a=d());let I=[1,1];if(g()&&g())switch(u()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:{I=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((T+1)*16-i*2-s*2),height:(2-R)*(b+1)*16-(R?2:4)*(n+a),pixelRatio:I}}}class pm extends kc{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){const n=this.parseNALu(e,i.data,s);let a=this.VideoSample,o,l=!1;i.data=null;const c=u=>(a=this.VideoSample=this.createVideoSample(u,i.pts,i.dts),a);n.forEach((u,h)=>{var d,g;if(this.startsNewAccessUnit(a,e,u,h)){this.pushAccessUnit(a,e);const p=u.type>=16&&u.type<=23;a=c(p),l=!1}switch(u.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=c(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var f;(f=a)!=null&&f.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=c(!0)),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=c(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,$i(u.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Re(e.params,this.readVPS(u.data)),this.initVPS=u.data),e.vps=[u.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],u.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const p=this.readSPS(u.data);e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.codec=p.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const m in p.params)e.params[m]=p.params[m]}this.pushParameterSet(e.sps,u.data,e.vps),a||(a=c(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const p=this.readPPS(u.data);for(const m in p)e.params[m]=p[m]}this.pushParameterSet(e.pps,u.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(g=a)!=null&&g.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=c(!1));break;default:o=!1;break}a&&o&&a.units.push(u)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,i,s){if(!e)return!1;if(!t.audFound&&s===0)return!0;if(!e.frame)return!1;const{type:n,data:a}=i;return n>=32&&n<=35||n===39||n>=41&&n<=44||n>=48&&n<=55?!0:n<=31&&a.length>2&&(a[2]&128)!==0}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let 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){const t=new Qi(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(e){const t=new Qi(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),c=t.readUByte(),u=t.readUByte(),h=t.readUByte(),d=t.readUByte(),g=t.readUByte(),f=t.readUByte(),p=t.readUByte(),m=t.readUByte(),y=t.readUByte(),E=[],S=[];for(let j=0;j<i;j++)E.push(t.readBoolean()),S.push(t.readBoolean());if(i>0)for(let j=i;j<8;j++)t.readBits(2);for(let j=0;j<i;j++)E[j]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[j]&&t.readUByte();t.readUEG();const T=t.readUEG();T==3&&t.skipBits(1);const b=t.readUEG(),R=t.readUEG(),I=t.readBoolean();let L=0,A=0,x=0,_=0;I&&(L+=t.readUEG(),A+=t.readUEG(),x+=t.readUEG(),_+=t.readUEG());const w=t.readUEG(),G=t.readUEG(),B=t.readUEG(),K=t.readBoolean();for(let j=K?0:i;j<=i;j++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let ee=0;ee<4;ee++)for(let W=0;W<(ee===3?2:6);W++)if(!t.readBoolean())t.readUEG();else{const ve=Math.min(64,1<<4+(ee<<1));ee>1&&t.readEG();for(let Te=0;Te<ve;Te++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const M=t.readUEG();let V=0;for(let j=0;j<M;j++){let ee=!1;if(j!==0&&(ee=t.readBoolean()),ee){j===M&&t.readUEG(),t.readBoolean(),t.readUEG();let W=0;for(let ge=0;ge<=V;ge++){const ve=t.readBoolean();let Te=!1;ve||(Te=t.readBoolean()),(ve||Te)&&W++}V=W}else{const W=t.readUEG(),ge=t.readUEG();V=W+ge;for(let ve=0;ve<W;ve++)t.readUEG(),t.readBoolean();for(let ve=0;ve<ge;ve++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const j=t.readUEG();for(let ee=0;ee<j;ee++){for(let W=0;W<B+4;W++)t.readBits(1);t.readBits(1)}}let C=0,H=1,Q=1,J=!0,ce=1,ie=0;t.readBoolean(),t.readBoolean();let z=!1;if(t.readBoolean()){if(t.readBoolean()){const $e=t.readUByte(),tt=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Le=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];$e>0&&$e<16?(H=tt[$e-1],Q=Le[$e-1]):$e===255&&(H=t.readBits(16),Q=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(),z=t.readBoolean(),z&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ce=t.readBits(32),ie=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Le=t.readBoolean(),Xe=t.readBoolean();let ct=!1;(Le||Xe)&&(ct=t.readBoolean(),ct&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ct&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let it=0;it<=i;it++){J=t.readBoolean();const We=J||t.readBoolean();let ut=!1;We?t.readEG():ut=t.readBoolean();const mt=ut?1:t.readUEG()+1;if(Le)for(let ht=0;ht<mt;ht++)t.readUEG(),t.readUEG(),ct&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Xe)for(let ht=0;ht<mt;ht++)t.readUEG(),t.readUEG(),ct&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),C=t.readUEG())}let oe=b,ue=R;if(I){let j=1,ee=1;T===1?j=ee=2:T==2&&(j=2),oe=b-j*A-j*L,ue=R-ee*_-ee*x}const Ee=s?["A","B","C"][s]:"",de=o<<24|l<<16|c<<8|u;let ae=0;for(let j=0;j<32;j++)ae=(ae|(de>>j&1)<<31-j)>>>0;let ye=ae.toString(16);return a===1&&ye==="2"&&(ye="6"),{codecString:`hvc1.${Ee}${a}.${ye}.${n?"H":"L"}${y}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:s,general_profile_compatibility_flags:[o,l,c,u],general_constraint_indicator_flags:[h,d,g,f,p,m],general_level_idc:y,bit_depth:w+8,bit_depth_luma_minus8:w,bit_depth_chroma_minus8:G,min_spatial_segmentation_idc:C,chroma_format_idc:T,frame_rate:{fixed:J,fps:ie/ce}},width:oe,height:ue,pixelRatio:[H,Q]}}readPPS(e){const t=new Qi(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);const s=t.readBoolean(),n=t.readBoolean();let a=1;return n&&s?a=0:n?a=3:s&&(a=2),{parallelismType:a}}matchSPS(e,t){return bt(e).substring(3)===bt(t).substring(3)}}const Ve=188;class Gt{constructor(e,t,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){const i=Gt.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(Ve*5,t-Ve)+1,s=0;for(;s<i;){let n=!1,a=-1,o=0;for(let l=s;l<t;l+=Ve)if(e[l]===71&&(t-l===Ve||e[l+Ve]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+Ve*99,e.length-Ve)+1)),n||(n=Hs(e,l)===0),n&&o>1&&(a===0&&o>2||l+Ve>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:zo[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Gt.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new vm(this.logger):null,this._audioTrack=Gt.createTrack("audio",s),this._id3Track=Gt.createTrack("id3"),this._txtTrack=Gt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,e&&this.demux(e,0,a,(n==null?void 0:n.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i,s=!1,n=!1){s||(this.sampleAes=null);let a;const o=this._videoTrack,l=this.videoIntegrityChecker,c=this._audioTrack,u=this._id3Track,h=this._txtTrack,d=i.iframe;let g=o.pid,f=o.pesData,p=c.pid,m=u.pid,y=this._klvPid,E=c.pesData,S=u.pesData,T=null,b=null,R=this.pmtParsed,I=this._pmtId,L=e.length;if(this.remainderData&&(e=Et(this.remainderData,e),L=e.length,this.remainderData=null),L<Ve&&!n)return this.remainderData=e,{audioTrack:c,videoTrack:o,id3Track:u,textTrack:h};const A=Math.max(0,Gt.syncOffset(e));L-=(L-A)%Ve,L<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,L,e.buffer.byteLength-L));let x=0;for(let w=A;w<L;w+=Ve)if(e[w]===71){const G=!!(e[w+1]&64),B=Hs(e,w),K=(e[w+3]&48)>>4;let O;if(K>1){if(O=w+5+e[w+4],O===w+Ve)continue}else O=w+4;switch(B){case g:G&&(f&&!(l!=null&&l.isCorrupted)&&(a=si(f,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,h,a,!1,i)),f={data:[],size:0},l==null||l.reset(g)),l==null||l.handlePacket(e.subarray(w)),f&&(f.data.push(e.subarray(O,w+Ve)),f.size+=w+Ve-O);break;case p:if(d)break;if(G){if(E&&(a=si(E,this.logger)))switch(c.segmentCodec){case"aac":this.parseAACPES(c,a,i);break;case"mp3":this.parseMPEGPES(c,a);break;case"ac3":this.parseAC3PES(c,a);break}E={data:[],size:0}}E&&(E.data.push(e.subarray(O,w+Ve)),E.size+=w+Ve-O);break;case m:if(d)break;G&&(S&&(a=si(S,this.logger))&&this.parseID3PES(u,a),S={data:[],size:0}),S&&(S.data.push(e.subarray(O,w+Ve)),S.size+=w+Ve-O);break;case y:if(d)break;G&&(T&&(a=si(T,this.logger))&&this.parseKlvPES(u,a),T={data:[],size:0}),T&&(T.data.push(e.subarray(O,w+Ve)),T.size+=w+Ve-O);break;case 0:G&&(O+=e[O]+1),I=this._pmtId=mm(e,O);break;case I:{G&&(O+=e[O]+1);const F=ym(e,O,this.typeSupported,s,this.observer,this.logger,this.config,i);g=F.videoPid,g>0&&(o.pid=g,o.segmentCodec=F.segmentVideoCodec),p=F.audioPid,p>0&&(c.pid=p,c.segmentCodec=F.segmentAudioCodec),m=F.id3Pid,m>0&&(u.pid=m),y=F.klvPid,y>0&&(this._klvPid=y),b!==null&&!R&&(this.logger.warn(`MPEG-TS PMT found at ${w} after unknown PID '${b}'. Backtracking to sync byte @${A} to parse all TS packets.`),b=null,w=A-188),R=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=B;break}}else x++;x>0&&fn(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),i,void 0,this.logger),o.pesData=f,c.pesData=E,u.pesData=S;const _={audioTrack:c,videoTrack:o,id3Track:u,textTrack:h};return n&&this.extractRemainingSamples(_,i),_}flush(e,t){const{remainderData:i}=this;this.remainderData=null;let s;return i?s=this.demux(i,0,t,!1,!0):s={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(s,t),this.sampleAes?this.decrypt(s,this.sampleAes):s}extractRemainingSamples(e,t){const{audioTrack:i,videoTrack:s,id3Track:n,textTrack:a}=e,o=s.pesData,l=i.pesData,c=n.pesData,u=this.videoIntegrityChecker;let h;if(o&&!(u!=null&&u.isCorrupted)&&(h=si(o,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,a,h,!0,t),s.pesData=null)):s.pesData=o,l&&(h=si(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,h,t);break;case"mp3":this.parseMPEGPES(i,h);break;case"ac3":this.parseAC3PES(i,h);break}i.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;c&&(h=si(c,this.logger))?(this.parseID3PES(n,h),n.pesData=null):n.pesData=c}demuxSampleAes(e,t,i,s){const n=this.demux(e,i,s,!0,!this.config.progressive),a=this.sampleAes=new Pc(this.observer,this.config,t);return this.decrypt(n,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new gm:e==="hevc"&&(this.videoParser=new pm))}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,i){let s=0;const n=this.aacOverFlow;let a=t.data;if(n){this.aacOverFlow=null;const d=n.missing,g=n.sample.unit.byteLength;if(d===-1)a=Et(n.sample.unit,a);else{const f=g-d;n.sample.unit.set(a.subarray(0,d),f),e.samples.push(n.sample),s=n.missing}}let o,l;for(o=s,l=a.length;o<l-1&&!Vs(a,o);o++);if(o!==s){let d;const g=o<l-1;if(g?d=`AAC PES did not start with ADTS header,offset:${o}`:d="No ADTS header found in AAC PES",fn(this.observer,new Error(d),i,g,this.logger),!g)return}bc(e,this.observer,a,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(n){const d=Ac(e.samplerate);c=n.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let u=0,h;for(;o<l;)if(h=xc(e,a,o,c,u),o+=h.length,h.missing){this.aacOverFlow=h;break}else for(u++;o<l-1&&!Vs(a,o);o++);}parseMPEGPES(e,t){const i=t.data,s=i.length;let n=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(Lc(i,a)){const l=Ic(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{const i=t.data,s=t.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=i.length;let a=0,o=0,l;for(;o<n&&(l=wc(e,i,o,s,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=Re({},t,{type:this._videoTrack?st.emsg:st.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}parseKlvPES(e,t){var i;const s=(i=t.pts)!=null?i:t.dts;if(s===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}const n=t.data;if(n.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let a=0;for(;a<n.length;){var o;if(a+16>n.length)break;const l=a;if(a+=16,a>=n.length)break;const c=n[a];a+=1;let u=0;if(c&128){const f=c&127;if(f===0||f>4||a+f>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let p=0;p<f;p++)u=u<<8|n[a+p];a+=f}else u=c;if(a+u>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const h=a+u,d=n.subarray(l,h),g={data:d,len:d.byteLength,pts:s,dts:(o=t.dts)!=null?o:s,type:st.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(g),a=h}}}function Hs(r,e){return((r[e+1]&31)<<8)+r[e+2]}function mm(r,e){return(r[e+10]&31)<<8|r[e+11]}function ym(r,e,t,i,s,n,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},c=(r[e+1]&15)<<8|r[e+2],u=e+3+c-4,h=(r[e+10]&15)<<8|r[e+11];for(e+=12+h;e<u;){const d=Hs(r,e),g=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!i){gn("ADTS AAC",n);break}case 15:l.audioPid===-1&&(l.audioPid=d);break;case 21:l.id3Pid===-1&&(l.id3Pid=d);break;case 219:if(!i){gn("H.264",n);break}case 27:l.videoPid===-1&&(l.videoPid=d);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=d,l.segmentAudioCodec="mp3");break;case 193:if(!i){gn("AC-3",n);break}case 129:t.ac3?l.audioPid===-1&&(l.audioPid=d,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(g>0){let f=e+5,p=g;for(;p>2;){switch(r[f]){case 106:l.audioPid===-1&&(t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:l.klvPid===-1&&a.enableEmsgKLVMetadata&&(l.klvPid=d,n.log(`KLV metadata PID found: ${d}`));break}const y=r[f+1]+2;f+=y,p-=y}}break;case 194:case 135:return fn(s,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:l.videoPid===-1&&(l.videoPid=d,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=g+5}return l}function fn(r,e,t,i,s){s.warn(`parsing error: ${e.message}`),r.emit(v.ERROR,v.ERROR,{type:se.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:t,error:e,reason:e.message})}function gn(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function si(r,e){let t=0,i,s,n,a,o;const l=r.data;if(!r||r.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Et(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(s=(i[4]<<8)+i[5],s&&s>r.size-6)return null;const u=i[7];u&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,u&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;const d=new Uint8Array(r.size);for(let g=0,f=l.length;g<f;g++){i=l[g];let p=i.byteLength;if(h)if(h>p){h-=p;continue}else i=i.subarray(h),p-=h,h=0;d.set(i,t),t+=p}return s&&(s-=n+3),{data:d,pts:a,dts:o,len:s}}return null}class vm{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;const t=Hs(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}const i=(e[3]&48)>>4;if(i===0)return;const s=e[3]&15,n=this.lastContinuityCounter;this.lastContinuityCounter=s;const a=(i&1)!=0;if((i&2)!=0&&e[4]!=0&&(e[5]&128)!=0||n<0)return;const c=a?n+1&15:n;if(s!==c){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${s}, Expected-CC=${c} Last-CC=${n}`),this.integrityState="cc-failed";return}if((e[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}}class Em{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}}}var Ks;const Sm={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},pn=new Uint8Array([0,0,0,0,0,0,0,0]),Tm=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),bm=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Am=new Uint8Array([0,0,0,0,0,0,0,0]),Ji=new Uint8Array([0,0,0,0,0,0,0,1]),Oc=new Uint8Array([105,115,111,109]),xm=new Uint8Array([97,118,99,49]),Im=new Uint8Array([0,0,0,1]);class Y{static box(e,...t){let i=8,s=t.length;const n=s;for(;s--;)i+=t[s].byteLength;const a=new Uint8Array(i);for(Be(a,0,i),Be(a,4,e),s=0,i=8;s<n;s++)a.set(t[s],i),i+=t[s].byteLength;return a}static hdlr(e){return Y.box(he.hdlr,Sm[e])}static mdat(e){return Y.box(he.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(Dt+1)),s=Math.floor(t%(Dt+1));return Y.box(he.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 Y.box(he.mdia,Y.mdhd(e.timescale||0,e.duration||0),Y.hdlr(e.type),Y.minf(e))}static mfhd(e){return Y.box(he.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?Y.box(he.minf,Y.box(he.smhd,Am),Y.DINF,Y.stbl(e)):Y.box(he.minf,Y.box(he.vmhd,bm),Y.DINF,Y.stbl(e))}static moof(e,t,i){return Y.box(he.moof,Y.mfhd(e),Y.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Y.trak(e[t]);return Y.box.apply(null,[he.moov,Y.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(Y.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Y.trex(e[t]);return Y.box.apply(null,[he.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Dt+1)),s=Math.floor(t%(Dt+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 Y.box(he.mvhd,n)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let 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 Y.box(he.sdtp,i)}static stbl(e){return Y.box(he.stbl,Y.stsd(e),Y.box(he.stts,pn),Y.box(he.stsc,pn),Y.box(he.stsz,Tm),Y.box(he.stco,pn))}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));const o=Y.box(he.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,c=e.height,u=e.pixelRatio[0],h=e.pixelRatio[1];return Y.box(he.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&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,Y.box(he.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Y.box(he.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.config,i=t.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...t,6,1,2])}static audioStsd(e){const 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 Y.box(he.mp4a,Y.audioStsd(e),Y.box(he.esds,Y.esds(e)))}static mp3(e){return Y.box(he[".mp3"],Y.audioStsd(e))}static ac3(e){return Y.box(he["ac-3"],Y.audioStsd(e),Y.box(he.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return Y.box(he.stsd,Ji,Y.mp4a(e));if(t==="ac3"&&e.config)return Y.box(he.stsd,Ji,Y.ac3(e));if(t==="mp3"&&e.codec==="mp3")return Y.box(he.stsd,Ji,Y.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return Y.box(he.stsd,Ji,Y.avc1(e));if(t==="hevc"&&e.vps)return Y.box(he.stsd,Ji,Y.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){const t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,n=e.height||0,a=Math.floor(i/(Dt+1)),o=Math.floor(i%(Dt+1));return Y.box(he.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){const i=Y.sdtp(e),s=e.id,n=Math.floor(t/(Dt+1)),a=Math.floor(t%(Dt+1));return Y.box(he.traf,Y.box(he.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),Y.box(he.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])),Y.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Y.box(he.trak,Y.tkhd(e),Y.mdia(e))}static trex(e){const t=e.id;return Y.box(he.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){const i=e.samples||[],s=i.length,n=12+16*s,a=new Uint8Array(n);let o,l,c,u,h,d;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)l=i[o],c=l.duration,u=l.size,h=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return Y.box(he.trun,a)}static initSegment(e){const t=Y.moov(e);return Et(Y.FTYP,t)}static hvc1(e){const 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]);let a=n.length;for(let f=0;f<i.length;f+=1){a+=3;for(let p=0;p<i[f].length;p+=1)a+=2+i[f][p].length}const o=new Uint8Array(a);o.set(n,0),a=n.length;const l=i.length-1;for(let f=0;f<i.length;f+=1){o.set(new Uint8Array([32+f|(f===l?128:0),0,i[f].length]),a),a+=3;for(let p=0;p<i[f].length;p+=1)o.set(new Uint8Array([i[f][p].length>>8,i[f][p].length&255]),a),a+=2,o.set(i[f][p],a),a+=i[f][p].length}const c=Y.box(he.hvcC,o),u=e.width,h=e.height,d=e.pixelRatio[0],g=e.pixelRatio[1];return Y.box(he.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,u>>8&255,u&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]),c,Y.box(he.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Y.box(he.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,g>>24,g>>16&255,g>>8&255,g&255])))}}Ks=Y,Y.FTYP=Ks.box(he.ftyp,Oc,Im,Oc,xm),Y.DINF=Ks.box(he.dinf,Ks.box(he.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));const Fc=9e4;function mn(r,e,t=1,i=!1){const s=r*e*t;return i?Math.round(s):s}function Rm(r,e,t=1,i=!1){return mn(r,e,1/t,i)}function Zi(r,e=!1){return mn(r,1e3,1/Fc,e)}function Lm(r,e=1){return mn(r,Fc,1/e)}function Mc(r){const{baseTime:e,timescale:t,trackId:i}=r;return`${e/t} (${e}/${t}) trackId: ${i}`}const _m=10*1e3,Pm=1024,Dm=1152,wm=1536,yn=8589934592;function Nc(r,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1,paddingValue:0}}}class qs extends dt{constructor(e,t,i,s){super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Mc(t)} > ${e&&Mc(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;const i=e[0].pts,s=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=gt(o,i),l=o-n),l>0?n:o},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,n,a,o,l,c){let u,h,d,g,f,p,m=n,y=n;const S=!c.iframe&&e.pid>-1,T=t.pid>-1,b=t.samples.length,R=e.samples.length>0,I=o&&b>0||b>1;if((!S||R)&&(!T||I)||this.ISGenerated||o){if(this.ISGenerated){var A,x,_,w;const O=this.videoTrackConfig;(O&&(t.width!==O.width||t.height!==O.height||((A=t.pixelRatio)==null?void 0:A[0])!==((x=O.pixelRatio)==null?void 0:x[0])||((_=t.pixelRatio)==null?void 0:_[1])!==((w=O.pixelRatio)==null?void 0:w[1]))||!O&&I||this.nextAudioTs===null&&R)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,n,a));const G=this.isVideoContiguous;let B=-1,K;if(I&&(B=Cm(t.samples),!G&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,B>0){this.warn(`Dropped ${B} out of ${b} video samples due to a missing keyframe`);const O=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(B),t.dropped+=B,y+=(t.samples[0].pts-O)/t.inputTimeScale,K=y}else B===-1&&(this.warn(`No keyframe found out of ${b} video samples`),p=!1);if(this.ISGenerated){if(R&&I&&n){const O=this.getVideoStartPts(t.samples),M=(gt(e.samples[0].pts,O)-O)/t.inputTimeScale;m+=Math.max(0,M),y+=Math.max(0,-M)}if(R){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,n,a)),h=this.remuxAudio(e,m,this.isAudioContiguous,a,T||I||l===te.AUDIO?y:void 0,c),I){const O=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,n,a)),u=this.remuxVideo(t,y,G,O,c)}}else I&&(u=this.remuxVideo(t,y,G,0,c));u&&(u.firstKeyFrame=B,u.independent=B!==-1,u.firstKeyFramePTS=K)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Bc(i,n,this._initPTS,this._initDTS)),s.samples.length&&(g=Uc(s,n,this._initPTS))),{audio:h,video:u,initSegment:d,independent:p,text:g,id3:f}}computeInitPts(e,t,i,s){const n=Math.round(i*t);let a=gt(e,n);if(a<n)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${s}`);a<n;)a+=yn;return a-n}generateIS(e,t,i,s){const n=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS,u=!c||s;let h="audio/mp4",d,g,f,p=-1;if(u&&(d=g=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}if(l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):Y.initSegment([e]),metadata:{channelCount:e.channelCount}},u){p=e.id,f=e.inputTimeScale;const m=this.computeInitPts(n[0].pts,f,i,"audio");(!c||f!==c.timescale||i===0&&m<c.baseTime)&&(d=g=m)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Y.initSegment([t]),metadata:{width:t.width,height:t.height}},u){p=t.id,f=t.inputTimeScale;const m=this.getVideoStartPts(a),y=gt(a[0].dts,m),E=this.computeInitPts(y,f,i,"video"),S=this.computeInitPts(m,f,i,"video");(!c||f!==c.timescale||q(d)||i===0&&S<c.baseTime)&&(g=Math.min(g,E),d=Math.min(d,E))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u&&q(d)?(c&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${d/f} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${d/f} (${d}/${f}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:f,trackId:p},this._initDTS={baseTime:g,timescale:f,trackId:p}):d=f=void 0,{tracks:l,initPTS:d,timescale:f,trackId:p}}remuxVideo(e,t,i,s,n){const a=e.inputTimeScale,o=e.samples,l=[],c=o.length,u=this._initPTS,h=u.baseTime*a/u.timescale;let d=this.nextVideoTs,g=8,f=this.videoSampleDuration,p,m,y=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,S=!1;if(!i||d===null){const C=h+t*a,H=o[0].pts-gt(o[0].dts,o[0].pts);Gi()&&d!==null&&Math.abs(C-H-(d+h))<15e3?i=!0:d=C-H-h}const T=d+h;for(let C=0;C<c;C++){const H=o[C];H.pts=gt(H.pts,T),H.dts=gt(H.dts,T),H.dts<o[C>0?C-1:C].dts&&(S=!0)}S&&o.sort(function(C,H){const Q=C.dts-H.dts,J=C.pts-H.pts;return Q||J}),p=o[0].dts,m=o[o.length-1].dts;const b=m-p,R=b?Math.round(b/(c-1)):f||e.inputTimeScale/30;if(i){const C=p-T,H=C>R,Q=C<-1;if((H||Q)&&(H?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Zi(C,!0)} ms (${C}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Zi(-C,!0)} ms (${C}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Q||T>=o[0].pts||Gi())){p=T;const J=o[0].pts-C;if(H)o[0].dts=p,o[0].pts=J;else{let ce=!0;for(let ie=0;ie<o.length&&!(o[ie].dts>J&&ce);ie++){const z=o[ie].pts;if(o[ie].dts-=C,o[ie].pts-=C,ie<o.length-1){const ne=o[ie+1].pts,oe=o[ie].pts,ue=ne<=oe,Ee=ne<=z;ce=ue==Ee}}}this.log(`Video: Initial PTS/DTS adjusted: ${Zi(J,!0)}/${Zi(p,!0)}, delta: ${Zi(C,!0)} ms`)}}p=Math.max(0,p);let I=0,L=0,A=p;for(let C=0;C<c;C++){const H=o[C],Q=H.units,J=Q.length;let ce=0;for(let ie=0;ie<J;ie++)ce+=Q[ie].data.length;L+=ce,I+=J,H.length=ce,H.dts<A?(H.dts=A,A+=R/4|0||1):A=H.dts,y=Math.min(H.pts,y),E=Math.max(H.pts,E)}m=o[c-1].dts;const x=L+4*I+8;let _;try{_=new Uint8Array(x)}catch(C){this.observer.emit(v.ERROR,v.ERROR,{type:se.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:C,bytes:x,reason:`fail allocating video mdat ${x}`});return}Be(_,0,x),Be(_,4,he.mdat);let w=!1,G=Number.POSITIVE_INFINITY,B=Number.POSITIVE_INFINITY,K=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let C=0;C<c;C++){const H=o[C],Q=H.units;let J=0;for(let z=0,ne=Q.length;z<ne;z++){const oe=Q[z],ue=oe.data,Ee=oe.data.byteLength;Be(_,g,Ee),g+=4,_.set(ue,g),g+=Ee,J+=4+Ee}let ce;if(C<c-1)f=o[C+1].dts-H.dts,ce=o[C+1].pts-H.pts;else{const z=this.config,ne=C>0?H.dts-o[C-1].dts:R;if(ce=C>0?H.pts-o[C-1].pts:R,z.stretchShortVideoTrack&&this.nextAudioTs!==null){const oe=Math.floor(z.maxBufferHole*a),ue=(s?y+s*a:this.nextAudioTs+h)-H.pts;ue>oe?(f=ue-ne,f<0?f=ne:w=!0,this.log(`It is approximately ${ue/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=ne}else f=ne}let ie=Math.round(H.pts-H.dts);if(G=Math.min(G,f),K=Math.max(K,f),B=Math.min(B,ce),O=Math.max(O,ce),!i&&C===0&&ie>f){const z=Math.round(ie/R)*R;z-ie===1&&(this.log(`pad first CTS ${ie} -> ${z} of sn: ${n.sn}`),ie=z)}l.push(Nc(H.key,f,J,ie))}if(l.length){const C=Gi();if(C){if(C<70){const H=l[0].flags;H.dependsOn=2,H.isNonSync=0}}else if(kg()&&O-B<K-G&&R/K<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let H=p;for(let Q=0,J=l.length;Q<J;Q++){const ce=H+l[Q].duration,ie=H+l[Q].cts;if(Q<J-1){const z=ce+l[Q+1].cts;l[Q].duration=z-ie}else l[Q].duration=Q?l[Q-1].duration:R;l[Q].cts=0,H=ce}}}f=w||!f?R:f;const F=m+f;this.nextVideoTs=d=F-h,this.videoSampleDuration=f,this.isVideoContiguous=!0,n.iframe&&(l.length===1?(l[0].duration=f=n.duration*a,this.nextVideoTs=d=p+f-h):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));const $={data1:Y.moof(n.sn,p,Re(e,{samples:l})),data2:_,startPTS:(y-h)/a,endPTS:(E+f-h)/a,startDTS:(p-h)/a,endDTS:d/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,$}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Dm;case"ac3":return wm;default:return Pm}}remuxAudio(e,t,i,s,n,a){const o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,c=o/l,u=this.getSamplesPerFrame(e),h=u*c,d=this._initPTS,g=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],p=n!==void 0;let m=e.samples,y=g?0:8,E=this.nextAudioTs||-1;const S=d.baseTime*o/d.timescale,T=S+t*o;if(this.isAudioContiguous=i=i||m.length&&E>0&&(s&&Math.abs(T-(E+S))<9e3||Math.abs(gt(m[0].pts,T)-(E+S))<20*h),m.forEach(function(F){F.pts=gt(F.pts,T)}),!i||E<0){const F=m.length;if(m=m.filter(M=>M.pts>=0),F!==m.length&&this.warn(`Removed ${m.length-F} of ${F} samples (initPTS ${S} / ${o})`),!m.length)return;n===0?E=0:s&&!p?E=Math.max(0,T-S):E=m[0].pts-S}if(e.segmentCodec==="aac"){const F=this.config.maxAudioFramesDrift;for(let M=0,V=E+S;M<m.length;M++){const $=m[M],C=$.pts,H=C-V,Q=Math.abs(1e3*H/o);if(H<=-F*h&&p)M===0&&(this.warn(`Audio frame @ ${(C/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*H/o)} ms.`),this.nextAudioTs=E=C-S,V=C);else if(H>=F*h&&Q<_m&&p){let J=Math.round(H/h);for(V=C-J*h;V<0&&J&&h;)J--,V+=h;M===0&&(this.nextAudioTs=E=V-S),this.warn(`Injecting ${J} audio frames @ ${((V-S)/o).toFixed(3)}s due to ${Math.round(1e3*H/o)} ms gap.`);for(let ce=0;ce<J;ce++){let ie=Em.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ie||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ie=$.unit.subarray()),m.splice(M,0,{unit:ie,pts:V}),V+=h,M++}}$.pts=V,V+=h}}let b=null,R=null,I,L=0,A=m.length;for(;A--;)L+=m[A].unit.byteLength;for(let F=0,M=m.length;F<M;F++){const V=m[F],$=V.unit;let C=V.pts;if(R!==null){const Q=f[F-1];Q.duration=Math.round((C-R)/c)}else if(i&&e.segmentCodec==="aac"&&(C=E+S),b=C,L>0){L+=y;try{I=new Uint8Array(L)}catch(Q){this.observer.emit(v.ERROR,v.ERROR,{type:se.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:Q,bytes:L,reason:`fail allocating audio mdat ${L}`});return}g||(Be(I,0,L),Be(I,4,he.mdat))}else return;I&&I.set($,y);const H=$.byteLength;y+=H,f.push(Nc(!0,u,H,0)),R=C}const x=f.length;if(!x)return;const _=f[f.length-1];E=R-S,this.nextAudioTs=E+c*_.duration;const w=g?new Uint8Array(0):Y.moof(e.sequenceNumber++,b/c,Re({},e,{samples:f}));e.samples=[];const G=(b-S)/o,B=this.nextAudioTs/o,O={data1:w,data2:I,startPTS:G,endPTS:B,startDTS:G,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:x};return this.isAudioContiguous=!0,O}}function gt(r,e){let t;if(e===null)return r;for(e<r?t=-yn:t=yn;Math.abs(r-e)>4294967296;)r+=t;return r}function Cm(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function Bc(r,e,t,i){const s=r.samples.length;if(!s)return;const n=r.inputTimeScale;for(let o=0;o<s;o++){const l=r.samples[o];l.pts=gt(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=gt(l.dts-i.baseTime*n/i.timescale,e*n)/n}const a=r.samples;return r.samples=[],{samples:a}}function Uc(r,e,t){const i=r.samples.length;if(!i)return;const s=r.inputTimeScale;for(let a=0;a<i;a++){const o=r.samples[a];o.pts=gt(o.pts-t.baseTime*s/t.timescale,e*s)/s}r.samples.sort((a,o)=>a.pts-o.pts);const n=r.samples;return r.samples=[],{samples:n}}class km extends dt{constructor(e,t,i,s){super("passthrough-remuxer",s),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.decryptdata=s,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,i){this.videoOnlyRemux=!1;let{audioCodec:s,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:a,video:o}=this.initData=i||tl(e);if(t)Eg(e,t);else{const c=a||o;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}a&&(s=$c(a,_e.AUDIO,this)),o&&(n=$c(o,_e.VIDEO,this));const l={};a&&o?l.audiovideo={container:"video/mp4",codec:s+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:s,encrypted:a.encrypted,initSegment:e,id:"audio"}:o?l.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,i,s,n,a,o,l,c,u,h){var d,g;let{initPTS:f,lastEndTime:p}=this;const m={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};q(p)||(p=this.lastEndTime=n||0);const y=t.samples;if(!y.length)return m;const E=this.pendingInitSegment;E&&(this.pendingInitSegment=void 0,this.generateInitSegment(E,this.decryptdata,u));const S={initPTS:void 0,timescale:void 0,trackId:void 0};let T=this.initData;if((d=T)!=null&&d.length||(this.generateInitSegment(y),T=this.initData),!((g=T)!=null&&g.length))return this.warn("Failed to generate initSegment."),m;if(c.iframe&&T.audio&&T.video){var b;const j=(b=this.initTracks)==null||(b=b.audiovideo)==null?void 0:b.initSegment,ee=j?fg(j):null;if(ee){var R;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(ee,this.decryptdata),(R=this.initData)!=null&&R.length&&(T=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(S.tracks=this.initTracks,m.initSegment=S,this.emitInitSegment=!1);const I=c.iframe,L=h&&(!I||h.includeSampleDetails)?h.tracks:Ag(y,T,c,this,I),A=T.audio?L[T.audio.id]:null,x=T.video?L[T.video.id]:null,_=!!T.audio,w=!!T.video;let G="";_&&(G+="audio"),w&&(G+="video");const B=Ws(x,1/0),K=Ws(A,1/0),O=Ws(x,0,!0),F=Ws(A,0,!0);let M=n,V=0;x&&A&&T.audio&&(K>O||B>F)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${B}-${O} a: ${K}-${F}}`,x,A);const $=!!A&&(!x||!f&&K<B||!!f&&f.trackId===T.audio.id),C=$?A:x;if(!C)return this.log(`No media samples found in ${l} ${c.level} ${c.part===-1?"":`part: ${c.part} of`} sn: ${c.sn} at playlist time: ${n}`),m;let H=y,Q,J;if(x&&x.sampleCount>=1&&T.video&&c.iframe){const{trun:j,start:ee}=x,W=j.length===1,ge=j.length?W?j[0].samples:j[0].samples.concat(...j.slice(1).map(ve=>ve.samples)):[];if(ge.length){const ve=j[0];let Te=ve;for(let it=j.length;it--;)if(j[it].samples.length){Te=j[it];break}const $e=Te.lastSampleDurationOffset,{defaultSampleDurationOffset:tt}=ve,Le=Math.abs(c.duration-(O-B))>.05,Xe=ge.length<x.sampleCount;if(!(Le||Xe||this.videoOnlyRemux||!W))V=O-B;else{const it=Xe?Te.sampleOffset+Te.samples.reduce((ht,br)=>ht+br.size,0):void 0,We=Le?c.duration:O-B,ut=Fm(ge,We*T.video.timescale,$e,tt),mt=gg(y,T.video.id,ge.length,it,ut);mt?(H=mt,J=Om(ee,ge)):this.warn(`IFrame remux skipped (sn ${c.sn}); using native sample duration`),V=mt&&ut?We:O-B}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${j.length})`),V=O-B}else V=$?F-K:O-B;if(this.videoOnlyRemux&&H===y)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${c.sn})`),m;const ce=C.timescale,ie=C.start-n*ce,z=$?T.audio.id:T.video.id;if(M=C.start/ce,(a||!f)&&(Mm(f,M,n,V)||ce!==f.timescale)){let j=!1;const ee=$?"audio":"video";if(f){const W=n!==0?M/n:1+M/1;j=M>=0&&Math.abs(1-W)<.001,this.log(`${ee} timestamps in track ${z} at playlist time: ${a?"":"~"}${n} maps to ${M} with initPTS: ${f.baseTime/f.timescale} (${ie/ce-f.baseTime/f.timescale}s diff) (${G}) drift estimate: ${W} ${j?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}j||(this.log(`Found initPTS in ${ee} track ${z} at playlist time: ${n} offset: ${M-n} (${ie}/${ce})`),f=null,S.initPTS=ie,S.timescale=ce,S.trackId=z)}f?(S.initPTS=f.baseTime,S.timescale=f.timescale,S.trackId=f.trackId):((!S.timescale||S.trackId===void 0||S.initPTS===void 0)&&(this.warn("Could not set initPTS"),S.initPTS=M,S.timescale=1,S.trackId=-1),this.initPTS=f={baseTime:S.initPTS,timescale:S.timescale,trackId:S.trackId});const ne=M-f.baseTime/f.timescale,oe=ne+V,ue=w&&(C==null?void 0:C.ptsMin)!==void 0?C.ptsMin/C.timescale-f.baseTime/f.timescale:ne,Ee=J!==void 0&&x?J/x.timescale-f.baseTime/f.timescale:w&&C!=null&&C.ptsMax?C.ptsMax/C.timescale-f.baseTime/f.timescale:oe;V>0?this.lastEndTime=oe:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const de=(T.audio?T.audio.encrypted:!1)||(T.video?T.video.encrypted:!1),ae={data1:H,data2:Q,startPTS:ue,startDTS:ne,endPTS:Ee,endDTS:oe,type:G,hasAudio:_,hasVideo:w,nb:1,dropped:0,encrypted:de};m.audio=_&&!w?ae:void 0,m.video=w?ae:void 0;const ye=this.isVideoContiguous,Me=x==null?void 0:x.sampleCount;if(Me){const j=x.keyFrameIndex,ee=j!==-1;ae.nb=Me,ae.dropped=j===0||ye?0:ee?j:Me,ae.independent=ee,ae.firstKeyFrame=j,ee&&x.keyFrameStart&&(ae.firstKeyFramePTS=(x.keyFrameStart-f.baseTime)/f.timescale),ye||(m.independent=ee),this.isVideoContiguous||(this.isVideoContiguous=ee),ae.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${j}/${Me} dropped: ${ae.dropped} start: ${ae.firstKeyFramePTS||"NA"}`)}return m.initSegment=S,m.id3=Bc(i,n,f,f),s.samples.length&&(m.text=Uc(s,n,f)),m}}function Ws(r,e,t=!1){return(r==null?void 0:r.start)!==void 0?(r.start+(t?r.duration:0))/r.timescale:e}function Om(r,e){let t=r,i=r;for(let s=0;s<e.length;s++){const{cts:n,duration:a}=e[s];i=Math.max(i,t+(n||0)+a),t+=a}return i}function Fm(r,e,t,i){if(t!==void 0){const n=r[r.length-1];let a=e;for(let o=0;o<r.length-1;o++)a-=r[o].duration;return a<=0&&(a=n.duration),n.duration=a,{durationOffset:t,value:a}}if(i===void 0)return;const s=Math.round(e/r.length);for(let n=0;n<r.length;n++)r[n].duration=s;return{durationOffset:i,value:s}}function Mm(r,e,t,i){if(r===null)return!0;const s=Math.max(i,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>=s}function $c(r,e,t){const i=r.codec;return i&&i.length>4?i:e===_e.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?_s(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):i==="mjpg"?i:(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Yt;try{Yt=self.performance.now.bind(self.performance)}catch{Yt=Date.now}const js=[{demux:hm,remux:km},{demux:Gt,remux:qs},{demux:om,remux:qs},{demux:cm,remux:qs}];js.splice(2,0,{demux:lm,remux:qs});class Gc{constructor(e,t,i,s,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){if(!this.observer)return Ys(i);const n=i.transmuxing;n.executeStart=Yt();const a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:u,trackSwitch:h,accurateTimeOffset:d,timeOffset:g,initSegmentChange:f}=s||o,{audioCodec:p,videoCodec:m,defaultInitPts:y,duration:E,initSegmentData:S}=l,T=Nm(a,t);if(T&&Ti(T.method)){const L=this.getDecrypter(),A=Zr(T.method);return this.asyncResult=!0,this.decryptionPromise=L.decrypt(a,T.key.buffer,T.iv.buffer,A,i.decryptRange).then(x=>{const _=this.push(x,null,i);return this.decryptionPromise=null,_}),this.decryptionPromise}const b=this.needsProbing(u,h);if(b){const L=i.iframe&&S&&Gt.probe(S,this.logger)?S:a,A=this.configureTransmuxer(L);if(A)return this.logger.warn(`[transmuxer] ${A.message}`),this.observer.emit(v.ERROR,v.ERROR,{type:se.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:A,reason:A.message}),n.executeEnd=Yt(),Ys(i)}(u||h||f||b)&&this.resetInitSegment(S,p,m,E,t,i),(u||f||b)&&this.resetInitialTimestamp(y),c||this.resetContiguity();const R=this.transmux(a,T,g,d,i);this.asyncResult=es(R);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,n.executeEnd=Yt(),R}flush(e){const t=e.transmuxing;t.executeStart=Yt();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));const a=[],{timeOffset:o}=s;if(i){const h=i.flush();h&&a.push(this.push(h.buffer,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c){t.executeEnd=Yt();const h=[Ys(e)];return this.asyncResult?Promise.resolve(h):h}const u=l.flush(o,e);return es(u)?(this.asyncResult=!0,u.then(h=>(this.flushRemux(a,h,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){if(!this.remuxer)return;const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);const u=this.remuxer.remux(s,n,a,o,c,l,!0,this.id,i,t.initData,t.sampleData);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Yt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,n,a){const{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,i,s,n,a),l.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,i,s,n){let a;return(t==null?void 0: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){const{demuxer:n,remuxer:a}=this;if(!n||!a)return Ys(s);const o=n.demux(e,t,s,!1,!this.config.progressive),{audioTrack:l,videoTrack:c,id3Track:u,textTrack:h}=o;return{remuxResult:a.remux(l,c,u,h,t,i,!1,this.id,s,o.initData,o.sampleData),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer?this.demuxer.demuxSampleAes(e,t,i,n).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id,n,a.initData,a.sampleData),chunkMeta:n})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;if(!i)return;let n;try{for(let h=0,d=js.length;h<d;h++){var a;if((a=js[h].demux)!=null&&a.probe(e,this.logger)){n=js[h];break}}}catch(h){return h}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,c=n.demux,u=n.remux;(!o||!(o instanceof c))&&(this.logger.log(`Using ${c.name}`),this.demuxer=new c(i,t,s,this.logger),this.probe=c.probe),(!l||!(l instanceof u))&&(this.logger.log(`Using ${u.name}`),this.remuxer=new u(i,t,s,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new zr(this.config)),e}}function Nm(r,e){let t=null;return r.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Ys=r=>({remuxResult:{},chunkMeta:r});function es(r){return"then"in r&&r.then instanceof Function}class Bm{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}}class Um{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}}let Vc=0;class Hc{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Vc++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const c=l.data,u=this.hls;if(!(!u||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo))switch(c.event){case"init":{var h;const d=(h=this.workerContext)==null?void 0:h.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{u.logger[c.data.logType]&&u.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,u.trigger(c.event,c.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const c=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(v.ERROR,{type:se.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const a=(l,c)=>{c=c||{},c.frag=this.frag||void 0,l===v.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(l,c)};this.observer=new cn,this.observer.on(v.FRAG_DECRYPTED,a),this.observer.on(v.ERROR,a);const o=fl(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(n.workerPath||Wp()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Yp(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=jp());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:Pe(n)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Gc(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Gc(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Vc++;const t=this.hls.config,i=fl(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Pe(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),zp(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,n,a,o,l,c,u){var h,d;c.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:f}=this,p=a?a.start:n.start,m=n.decryptdata,y=this.frag,E=y?n.cc!==y.cc:!0,S=y?c.level!==y.level:!0,T=y?c.sn-y.sn:-1,b=this.part?c.part-this.part.index:-1,R=T===0&&c.id>1&&c.id===(y==null?void 0:y.stats.chunkCount),I=!S&&(T===1||T===0&&(b===1||R&&b<=0)),L=self.performance.now();(S||T||n.stats.parsing.start===0)&&(n.stats.parsing.start=L),a&&(b||!I)&&(a.stats.parsing.start=L);const A=!(y&&((h=n.initSegment)==null?void 0:h.url)===((d=y.initSegment)==null?void 0:d.url)),x=new Um(E,I,l,S,p,A);if(!I||E||A){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id} playlist: ${c.level} id: ${c.id}
17
- discontinuity: ${E}
18
- trackSwitch: ${S}
19
- contiguous: ${I}
20
- accurateTimeOffset: ${l}
21
- timeOffset: ${p}
22
- initSegmentChange: ${A}`);const _=new Bm(i,s,t,o,u);this.configureTransmuxer(_)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:m,chunkMeta:c,state:x},e instanceof ArrayBuffer?[e]:[]);else if(f){const _=f.push(e,m,c,x);es(_)?_.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,c,"transmuxer-interface push error")}):this.handleTransmuxComplete(_)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const s=i.flush(e);es(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(v.ERROR,{type:se.MEDIA_ERROR,details:D.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){const{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)}}const Kc=100;class $m extends on{constructor(e,t,i){super(e,t,i,"audio-stream-controller",te.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(v.BUFFER_RESET,this.onBufferReset,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(v.BUFFER_RESET,this.onBufferReset,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){const{frag:i,id:s,initPTS:n,timescale:a,trackId:o,timestampOffsets:l}=t;if(s===te.MAIN){const c=i.cc,u=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${c} found from main: ${n/a} (${n}/${a}) trackId: ${o}`),this.mainAnchor=i,this.state===U.WAITING_INIT_PTS){const h=this.waitingData;(!h&&!this.loadingParts||h&&h.frag.cc!==c)&&this.syncWithAnchor(i,h==null?void 0:h.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==c?(u.abortRequests(),this.syncWithAnchor(i,u)):this.state===U.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const s=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&(s==null?void 0:s.cc)===t.cc)return;const n=(s||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=_l(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===U.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=U.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Kc),i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=U.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case U.IDLE:this.doTickIdle();break;case U.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e==null?void 0:e[t],s=i==null?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=U.WAITING_INIT_PTS}break}case U.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case U.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=U.FRAG_LOADING;const o=s.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=U.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;const{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;const o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=U.WAITING_TRACK,this.startFragRequested=!1;return}const c=this.getBufferOutput();this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,_e.AUDIO));const u=this.getFwdBufferInfo();if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(v.BUFFER_EOS,{type:"audio"}),this.state=U.ENDED;return}const h=u.len,d=t.maxBufferLength,g=l.fragments,f=g[0].start,p=this.getLoadPosition(),m=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?p:u.end;if(this.switchingTrack&&s){const S=p;l.PTSKnown&&S<f&&S>=this.timelineOffset&&(u.end>f||u.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${S} -> ${f} + 0.05`),s.currentTime=f+.05)}if(h>=d&&!this.switchingTrack&&m<g[g.length-1].start)return;let y=this.getNextFragment(m,l);if(y&&this.isLoopLoading(y,m)&&(y=this.getNextFragmentLoopLoading(y,l,u,te.MAIN,d)),!y){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(u,d,y))return;let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&Ne(y)&&!y.endList&&(!l.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===ke.OK&&(this.mainFragLoading=E=null),E&&Ne(E))){if(y.start>E.end){const T=this.fragmentTracker.getFragAtPos(m,te.MAIN);T&&T.end>E.end&&(E=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(y.start>E.end)return}this.loadFragment(y,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 Ki(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==U.STOPPED&&(this.setInterval(Kc),this.state=U.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;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(v.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:n,id:a,groupId:o,track:l}=t;if(!s){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const c=this.mainDetails;if(!c||n.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==U.STOPPED&&(this.state=U.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const u=s[a];let h=0;if(n.live||(i=u.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(u.details){var d;h=this.alignPlaylists(n,u.details,(d=this.levelLastLoaded)==null?void 0:d.details)}n.alignedSliding||(Us(c,n,this),h=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(c,h),this.hls.trigger(v.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===U.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=U.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const u=c.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const h=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Hc(this.hls,te.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[i.cc],f=(t=i.initSegment)==null?void 0:t.data;if(g!==void 0){const m=s?s.index:-1,y=m!==-1,E=new Xr(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,y,i.duration);d.push(n,f,h,"",i,s,u.totalduration,!1,E,g)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new vc,complete:!1};p.push(new Uint8Array(n)),this.state!==U.STOPPED&&(this.state=U.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;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===te.MAIN&&Ne(t.frag)&&(this.mainFragLoading=t,this.state===U.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==te.AUDIO){!this.audioOnly&&i.type===te.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(Ne(i)){const n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(i,s),this.media&&this.tick()}getFwdBufferInfo(){const e=this.getBufferOutput();return super.getFwdBufferInfo(e,te.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const i=this.fragPlaying,s=e==null?void 0:e.level;return(!i||i.level!==s)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var i;if(t.fatal){this.state=U.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(te.AUDIO,t);break;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===U.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===pe.AUDIO_TRACK&&(this.state=U.IDLE);break;case D.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="audio")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case D.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==_e.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==_e.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===U.ENDED&&(this.state=U.IDLE);const i=this.getBufferOutput();i&&(this.afterBufferFlushed(i,t),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{details:h}=u,{audio:d,text:g,id3:f,initSegment:p}=n;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l),p!=null&&p.tracks&&this.resetTransmuxer();return}if(this.state=U.PARSING,d&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:m}=this,y=m.nextAudioTrackBufferFlushForwardOffset,E=Math.max(this.getLoadPosition()+y,l.start);super.flushMainBuffer(E,Number.POSITIVE_INFINITY,te.AUDIO)}if(p!=null&&p.tracks){const m=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(u,p.tracks,m,a),s.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:i,tracks:p.tracks})}if(d){const{startPTS:m,endPTS:y,startDTS:E,endDTS:S}=d;c&&(c.elementaryStreams[_e.AUDIO]={startPTS:m,endPTS:y,startDTS:E,endDTS:S}),l.setElementaryStreamInfo(_e.AUDIO,m,y,E,S),this.bufferFragmentData(d,l,c,a)}if(f!=null&&(t=f.samples)!=null&&t.length){const m=Re({id:i,frag:l,details:h},f);s.trigger(v.FRAG_PARSING_METADATA,m)}if(g){const m=Re({id:i,frag:l,details:h},g);s.trigger(v.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,t,i,s){if(this.state!==U.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const n=t.audio;n.id=te.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),(a==null?void 0:a.split(",").length)===1&&(n.levelCodec=a),this.hls.trigger(v.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(v.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===ke.NOT_LOADED||s===ke.PARTIAL){var n;if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=U.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Us(a,t.details,this)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){const{name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;ti({name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o},e,ii)||(Cs(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){const{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(v.AUDIO_TRACK_SWITCHED,re({},e))}get nextAudioTrack(){return this.nextTrackId}}class vn extends dt{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=t==null?void 0:t.renditionReports;if(s){let n=-1;for(let a=0;a<s.length;a++){const o=s[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a)}if(n!==-1){const a=s[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}const c=i&&El(i);return new Sl(o,l>=0?l:void 0,c)}}}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){const{details:s,stats:n}=t,a=s.fragments,o=self.performance.now(),l=n.loading.first?Math.max(0,Math.floor(o-n.loading.first)):0;s.advancedDateTime=Date.now()-l;const c=this.hls.config.timelineOffset;if(c!==s.appliedTimelineOffset){const h=Math.max(c||0,0);s.appliedTimelineOffset=h,a.forEach(d=>{d==null||d.setStart(d.playlistOffset+h)})}if(s.live||i!=null&&i.live){var u;const h="levelInfo"in t?t.levelInfo:t.track;s.reloaded(i);const d=(u=a[a.length-1])==null?void 0:u.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const b=new Error(`${d} playlist ${h.id} hit max allowed unchanged reloads.`);this.warn(b);const{networkDetails:R,context:I}=t;this.hls.trigger(v.ERROR,{type:se.NETWORK_ERROR,details:D.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:b,reason:b.message,level:t.level,parent:d,context:I,networkDetails:R,stats:n});return}if(i){Op(i,s,this);const b=s.playlistParsingError;if(b){this.warn(b);const R=this.hls;if(!R.config.ignorePlaylistParsingErrors){const{networkDetails:I}=t;R.trigger(v.ERROR,{type:se.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:b,reason:b.message,level:t.level,parent:d,networkDetails:I,stats:n});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=n.loading.start);const g=this.hls.mainForwardBufferInfo,f=g?g.end-g.len:0,p=(s.edge-f)*1e3,m=cc(s,p);s.requestScheduled+m<o?s.requestScheduled=o:s.requestScheduled<=o&&(s.requestScheduled+=m);const y=t.deliveryDirectives;if(this.log(`live playlist ${e} ${s.advanced?`REFRESHED ${s.lastPartSn} - ${s.lastPartIndex}`:s.updated?"UPDATED":`MISSED (received ${s.lastPartSn} - ${s.lastPartIndex}${y?` | requested ${y.msn} - ${y.part}`:""})`}`),!this.canLoad||!s.live)return;let E,S,T;if(s.canBlockReload&&s.advanced){const b=this.hls.config.lowLatencyMode,R=s.lastPartSn,I=s.endSN,L=s.lastPartIndex,A=L!==-1,x=R===I;A?x?(S=I+1,T=b?0:L):(S=R,T=b?L+1:s.maxPartIndex):S=I+1;const _=s.age,w=_+s.ageHeader;let G=Math.min(w-s.partTarget,s.targetduration*1.5);if(G>0){if(w>s.targetduration*3)this.log(`Playlist last advanced ${_.toFixed(2)}s ago. Omitting segment and part directives.`),S=void 0,T=void 0;else if(i!=null&&i.tuneInGoal&&w-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${G} with playlist age: ${s.age}`),G=0;else{const B=Math.floor(G/s.targetduration);if(S+=B,T!==void 0){const K=Math.round(G%s.targetduration/s.partTarget);T+=K}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${_.toFixed(2)}s goal: ${G} skip sn ${B} to part ${T}`)}s.tuneInGoal=G}if(E=this.getDeliveryDirectives(s,t.deliveryDirectives,S,T),b||!x){s.requestScheduled=o,this.loadingPlaylist(h,E);return}}else(s.canBlockReload||s.canSkipUntil)&&(E=this.getDeliveryDirectives(s,t.deliveryDirectives,S,T));E&&S!==void 0&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(m-l*2,m/2)),this.scheduleLoading(h,E,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}const n=self.performance.now(),a=s.requestScheduled;if(n>=a&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(e,t),this.loadingSync=!1;return}const o=Math.max(a-n,0);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=El(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=ws.No),new Sl(i,s,n)}checkRetry(e){const t=e.details,i=Es(e),s=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(n===je.RetryRequest||!s.resolved&&n===je.SendAlternateToPenaltyBox);if(l){var c;if(a>=o.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var u;const h=Ni((u=e.response)==null?void 0:u.code);if(this.clearTimer(),h)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const d=Dr(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${d}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),d)}}e.levelRetry=!0,s.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),Ni(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function qc(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!ts(r[t].attrs,e[t].attrs))return!1;return!0}function ts(r,e,t){const 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])}class Gm extends vn{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(){const{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVEL_LOADING,this.onLevelLoading,this),e.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(v.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){const{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==null?void 0:a.groupId}`);return}const 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){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,s=this.groupIds;let n=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(s==null?void 0:s.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>qi(d.groupId,i));if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,g)=>{d.id=g});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!n&&l){const d=kt(l,o,ii);if(d>-1)n=o[d];else{const g=kt(l,this.tracks);n=this.tracks[g]}}let c=this.findTrackId(n);c===-1&&n&&(c=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(v.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(c!==-1&&h===-1)this.setAudioTrack(c);else if(o.length&&h===-1){var a;const d=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(d.message),this.hls.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===pe.AUDIO_TRACK&&t.context.id===this.trackId&&qi(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&ti(e,s,ii))return s;const n=kt(e,this.tracksInGroup,ii);if(n>-1){const a=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in e&&e.flushImmediate),a}else if(s){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=sp(e,t.levels,i,a,ii);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=kt(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e,t=!0){const i=this.tracksInGroup;if(e<0||e>=i.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,n=i[e],a=n.details&&!n.details.live;if(e===this.trackId&&n===s&&a||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(v.AUDIO_TRACK_SWITCHING,re(re({},n),{},{flushImmediate:t})),a))return;const o=this.switchParams(n.url,s==null?void 0:s.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||ti(e,s,ii)))return i}if(e){const{name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const u=t[c];if(ti({name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:l},u,ii))return c}for(let c=0;c<t.length;c++){const u=t[c];if(ts(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const u=t[c];if(ts(e.attrs,u.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Cs(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${(t==null?void 0: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(v.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}}class Vm{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;const s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const 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;const i=(t=e[0])==null?void 0:t.label;i==="async-blocker"||i==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):i==="block-audio"&&e.splice(0,1)})}insertNext(e,t){this.queues!==null&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;this.queues!==null&&((e=this.current("audio"))==null?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(e=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(n){var i;if(s.onError(n),this.queues===null||this.tracks===null)return;const 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(){const{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;const i=(t=this.tracks)==null?void 0:t[e],s=i==null?void 0: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(", "))||""}}const Wc=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,jc="HlsJsTrackRemovedError",Hm=.25,Km=.001;class qm extends Error{constructor(e){super(e),this.name=jc}}class Wm extends dt{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:s,mediaSource:n}=this;i&&this.log("Media source opened"),!(!s||!n)&&(Ae(n,"sourceopen",this._onMediaSourceOpen),Ae(s,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(v.MEDIA_ATTACHED,{media:s,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const i=this.media.error,{appendError:s,appendErrors:n}=this;let a=!1;!s&&i&&(a=Math.max(++n.audio,++n.video,++n.audiovideo)>=this.hls.config.appendErrorMaxRetry);const o=new Error(`MediaSource closed while media attached${zc(a,i)}`);this.warn(o),this.hls.trigger(v.ERROR,Re({fatal:a},s,{type:se.MEDIA_ERROR,details:D.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:s}=this;i!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this._onMediaError=()=>{const{media:i}=this;if(i){var s,n;this.log(`Media error (code: ${(s=i.error)==null?void 0:s.code}): ${(n=i.error)==null?void 0:n.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=Yf(qt(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:e}=this;e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.BUFFER_RESET,this.onBufferReset,this),e.on(v.BUFFER_APPENDING,this.onBufferAppending,this),e.on(v.BUFFER_CODECS,this.onBufferCodecs,this),e.on(v.BUFFER_EOS,this.onBufferEos,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.FRAG_PARSED,this.onFragParsed,this),e.on(v.FRAG_CHANGED,this.onFragChanged,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.BUFFER_RESET,this.onBufferReset,this),e.off(v.BUFFER_APPENDING,this.onBufferAppending,this),e.off(v.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.BUFFER_EOS,this.onBufferEos,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.FRAG_PARSED,this.onFragParsed,this),e.off(v.FRAG_CHANGED,this.onFragChanged,this),e.off(v.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const n=this.isUpdating();n||this.operationQueue.removeBlockers();const a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===t?Re(i,s.tracks):this.sourceBuffers.forEach(n=>{const[a]=n;a&&(i[a]=Re({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const s=qt(this.appendSource);if(s){const n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,Yc(i),jm(i,o),i.load()}catch{i.src=o}else i.src=o}xe(i,"emptied",this._onMediaEmptied),xe(i,"error",this._onMediaError),this.appendSource&&xe(i,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),xe(e,"sourceopen",this._onMediaSourceOpen),xe(e,"sourceended",this._onMediaSourceEnded),xe(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(xe(e,"startstreaming",this._onStartStreaming),xe(e,"endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const 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: ${Pe(i,(l,c)=>l==="initSegment"?void 0:c)};
27
- transfer tracks: ${Pe(s,(l,c)=>l==="initSegment"?void 0:c)}}`),!Go(s,i)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,c=this.details,u=Math.max(l,(c==null?void 0:c.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(v.MEDIA_DETACHING,{}),this.onMediaAttaching(v.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,n.forEach(l=>{const c=l,u=s[c];if(u){const h=u.buffer;if(h){const d=this.fragmentTracker,g=u.id;if(d.hasFragments(g)||d.hasParts(g)){const m=le.getBuffered(h);d.detectEvictedFragments(c,m,g,null,null,!0)}const f=En(c),p=[c,h];this.sourceBuffers[f]=p,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(c),this.trackSourceBuffer(c,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{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){const o=n.readyState==="open";try{const l=n.sourceBuffers;for(let c=l.length;c--;)o&&l[c].abort(),n.removeSourceBuffer(l[c]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Ae(n,"sourceopen",this._onMediaSourceOpen),Ae(n,"sourceended",this._onMediaSourceEnded),Ae(n,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Ae(n,"startstreaming",this._onStartStreaming),Ae(n,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(Ae(s,"emptied",this._onMediaEmptied),Ae(s,"error",this._onMediaError),Ae(s,"seeking",this._onStartStreaming),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&Yc(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[En(e)]=[null,null];const t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Vm(this.tracks)}onBufferCodecs(e,t){var i;const s=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!s[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var c,u;const h=t[l],{id:d,codec:g,levelCodec:f,container:p,metadata:m,supplemental:y}=h;let E=s[l];const S=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],T=S!=null&&S.buffer?S:E,b=(T==null?void 0:T.pendingCodec)||(T==null?void 0:T.codec),R=T==null?void 0:T.levelCodec;E||(E=s[l]={buffer:void 0,listeners:[],codec:g,supplemental:y,container:p,levelCodec:f,metadata:m,id:d});const I=Ps(b,R),L=I==null?void 0:I.replace(Wc,"$1");let A=Ps(g,f);const x=(u=A)==null?void 0:u.replace(Wc,"$1");A&&I&&L!==x&&(l.slice(0,5)==="audio"&&(A=_s(A,this.appendSource)),this.log(`switching codec ${b} to ${A}`),A!==(E.pendingCodec||E.codec)&&(E.pendingCodec=A),E.container=p,this.appendChangeType(l,p,A))}),(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)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const s=`${t};codecs=${i}`,n={label:`change-type=${s}`,execute:()=>{const a=this.tracks[e];if(a){const 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;const i=e.start,s=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,te.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>s||le.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,s)||((l=this.fragmentTracker.getAppendedFrag(s,te.MAIN))==null?void 0:l.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.append(a,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:n,parent:a,frag:o,part:l,chunkMeta:c,offset:u}=t,h=c.buffering[n],d=Ne(o)&&!l&&!o.gap&&!c.partial&&!c.iframe;let g=null,f=!1;const{sn:p,cc:m}=o,y=self.performance.now();h.start=y;const E=o.stats.buffering,S=l?l.stats.buffering:null;E.start===0&&(E.start=y),(S==null?void 0:S.start)===0&&(S.start=y);const T=i.audio;let b=!1;n==="audio"&&(T==null?void 0:T.container)==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const R=i.video,I=R==null?void 0:R.buffer;if(I&&p!=="initSegment"&&u!==void 0){const x=T==null?void 0:T.buffer,_=l||o;if(n==="audio"&&a!=="main"&&!(R.ending||R.ended)&&x&&le.getBuffered(x).length){const G=_.start+_.duration*.05,B=le.getBuffered(I),K=this.currentOp("video");!B.length&&!K?this.blockAudio(_):!le.isBuffered(I,G)&&this.lastVideoAppendEnd<G&&this.blockAudio(_)}else if(n==="video"){const w=_.end,G=this.lastVideoAppendEnd-w;this.lastVideoAppendEnd=w,G<0||G>_.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const L=(l||o).start,A={label:`append-${n}`,execute:()=>{var x;h.executeStart=self.performance.now();const _=(x=this.tracks[n])==null?void 0:x.buffer;_&&(d&&(g=le.timeRangesToArray(le.getBuffered(_)),f=Qc(Sn(g,o),o)),b?this.updateTimestampOffset(_,L,.1,n,p,m):u!==void 0&&q(u)&&this.updateTimestampOffset(_,u,1e-6,n,p,m)),this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[n]);const x=self.performance.now();h.executeEnd=h.end=x,E.first===0&&(E.first=x),(S==null?void 0:S.first)===0&&(S.first=x);const _={};if(this.sourceBuffers.forEach(([w,G])=>{w&&(_[w]=le.getBuffered(G))}),d){const w=this.getFragmentAppendProgress(o),G=_[n];if(G&&g){const B=le.timeRangesToArray(G),K=Sn(B,o);w.progressed||(w.progressed=K-Sn(g,o)>Km);const O=f&&Qc(K,o);w.fullyBuffered[n]=(w.fullyBuffered[n]===void 0||w.fullyBuffered[n])&&O}}this.hls.trigger(v.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:c,parent:a,timeRanges:_})},onError:x=>{var _;this.clearBufferAppendTimeoutId(this.tracks[n]);const w=x.code===DOMException.QUOTA_EXCEEDED_ERR||x.name=="QuotaExceededError"||"quota"in x;if(w&&!this._quotaEvictionPending[n]){const O=this.getBackBufferEvictionTarget(n,s.byteLength,o.type);if(O>0){this._quotaEvictionPending[n]=!0,this.log(`QuotaExceededError on "${n}" append sn: ${p} - evicting back buffer to ${O.toFixed(3)}s and retrying`);const F=this.getFlushOp(n,0,O),M=this.getClearEvictionPendingOp(n);this.insertNext([F,A,M],n);return}this.warn(`QuotaExceededError on "${n}" sn: ${p} - no back buffer available to evict`)}d&&(this.getFragmentAppendProgress(o).errored=!0);const G={type:se.MEDIA_ERROR,parent:a,details:D.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:c,error:x,err:x,fatal:!1},B=(_=this.media)==null?void 0:_.error;if(x.name===jc&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))G.errorAction=Wi(!0);else{var K;w&&(G.details=D.BUFFER_FULL_ERROR);const O=++this.appendErrors[n],F=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${O}/${F+1} times to append segment in "${n}" sourceBuffer with error: ${x.message}`),O>=F&&(G.fatal=!w);const M=(K=this.mediaSource)==null?void 0:K.readyState;(M==="ended"||M==="closed"||B)&&(this.warn(`MediaSource readyState "${M}" during SourceBuffer${zc(G.fatal,B)}`),G.details=D.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=G,this.hls.trigger(v.ERROR,G),w&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${n}" append sn: ${p}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${m} offset: ${u} bytes: ${s.byteLength}`),this.append(A,n,this.isPending(this.tracks[n]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{var s;const n=(s=this.tracks[e])==null?void 0:s.buffer;this.log(`Remove request ${t}-${i} from ${e} Source Buffer complete > buffer: ${n?$s(le.getBuffered(n)):"(detached)"}`),this.hls.trigger(v.BUFFER_FLUSHED,{type:e,start:t,end:i})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s),this.hls.trigger(v.BUFFER_FLUSHED,{type:e,start:0,end:0,error:s})}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:n}=t;(!i||i==="audio")&&this.unblockAudio(),i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,s,n),a)})}onFragParsed(e,t){const{frag:i,part:s,chunkMeta:n}=t,a=[],o=s?s.elementaryStreams:i.elementaryStreams;o[_e.AUDIOVIDEO]?a.push("audiovideo"):(o[_e.AUDIO]&&a.push("audio"),o[_e.VIDEO]&&a.push("video"));const l=()=>{const c=self.performance.now();i.stats.buffering.end=c,s&&(s.stats.buffering.end=c);const u=s?s.stats:i.stats;this.checkAppendProgress(i,s,n,a),this.hls&&(this.hls.trigger(v.FRAG_BUFFERED,{frag:i,part:s,stats:u,id:i.type,chunkMeta:n}),!s&&i.gap&&u.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${u.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${s?`part: ${s.index} of `:""}sn: ${i.sn}`),this.blockBuffers(l,a).catch(c=>{this.warn(`Fragment buffered callback ${c.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var i,s;const n=(i=this.hls)==null?void 0:i.config;if(!n)return;const{backBufferLength:a,frontBufferFlushThreshold:o}=n;this.trimBuffers(o,a,t.frag,t.previousFrag);const l=t.frag.elementaryStreams,{appendErrors:c}=this,u=(s=this.appendError)==null?void 0:s.sourceBufferName;Object.keys(l).forEach(h=>{l[h]&&(c[h]=0,h===u&&(this.appendError=void 0),h==="audio"||h==="video"?(c.audiovideo=0,u==="audiovideo"&&(this.appendError=void 0)):(c.audio=0,c.video=0,u!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?(this.unblockAudio(),s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if((a==null?void 0: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(v.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(v.BUFFERED_TO_END,void 0))):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===D.BUFFER_APPEND_ERROR&&t.frag){var i;const s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;q(s)&&s!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,i){const{media:s}=this;return s?this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,i,t):0}getFragmentAppendProgress(e){var t;const i=Xc(e);let s=this.fragmentAppendProgress[i];return((t=s)==null?void 0:t.stats)!==e.stats&&(s={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=s),s}checkAppendProgress(e,t,i,s){if(t||!Ne(e)||e.gap||i.iframe||i.partial)return;const n=Xc(e),a=this.fragmentAppendProgress[n];delete this.fragmentAppendProgress[n];const o=e.stats.buffering;if(o.start&&!o.first)return;const l=(a==null?void 0:a.stats)===e.stats?a:void 0;if(l!=null&&l.errored)return;const c=s.length>0&&s.every(g=>(l==null?void 0:l.fullyBuffered[g])===!0);if(l!=null&&l.progressed||c){delete this.appendsWithoutProgress[n];return}if(!l&&s.length===0)return;const u=(this.appendsWithoutProgress[n]||0)+1,h=this.hls;u>=h.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=u,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${u} time${u>1?"s":""} without buffered range growth`),h.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:i,parent:e.type,appendsWithoutProgress:u,error:new Error(`Fragment append did not increase buffered coverage (${u})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,i,s){const{hls:n,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;const l=n.config,c=o.currentTime,u=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let h=-1/0;if(q(t)&&t>=0){const d=Math.max(t,u);h=Math.floor(c/u)*u-d}if(i){const d=this.getLoopBackBufferFlushEnd(i,s??null);d>0&&(h=Math.max(h,d))}if(h>0&&this.flushBackBuffer(c,u,h),q(e)&&e>0){const d=Math.max(l.maxBufferLength,e),g=Math.max(d,u),f=Math.floor(c/u)*u+g;this.flushFrontBuffer(c,u,f)}}getLoopBackBufferFlushEnd(e,t){var i;const{media:s}=this;if(((i=this.hls)==null?void 0:i.config.loopBackBufferFlush)===!1||!(s!=null&&s.loop)||!t||e.level<=t.level)return 0;const{video:n,audiovideo:a}=e.elementaryStreams;if(n!=null&&n.partial||a!=null&&a.partial)return 0;const o=this.getEarliestElementaryStreamStart(e)-Hm;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(e){const{audio:t,video:i,audiovideo:s}=e.elementaryStreams;let n=e.start;return s?n=Math.min(n,s.startDTS):(t&&(n=Math.min(n,t.startDTS)),i&&(n=Math.min(n,i.startDTS))),n}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const c=le.getBuffered(n);if(c.length>0&&i>c.start(0)){var a,o,l;this.hls.trigger(v.BACK_BUFFER_REACHED,{bufferEnd:i});const u=this.tracks[s];if((a=this.details)!=null&&a.live)this.hls.trigger(v.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(u!=null&&u.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const a=le.getBuffered(n),o=a.length;if(o<2)return;const l=a.start(o-1),c=a.end(o-1);if(i>l||e>=l&&e<=c)return;this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const c=Math.max(0,t.fragmentStart),u=Math.max(c,s);return{duration:1/0,start:c,end:u}}return{duration:1/0}}const n=(e=this.overrides)==null?void 0:e.duration;if(n)return q(n)?{duration:n}:null;const a=this.media.duration,o=q(i.duration)?i.duration:0;return s>o&&s>a||!q(a)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;!s||!this.media||s.readyState!=="open"||(s.duration!==e&&(q(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(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Pe(i)}`),this.tracksReady){var s;const n=(s=this.transferData)==null?void 0:s.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const 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(v.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const a=n,o=e[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),c=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${c})${this.currentOp(a)?" Queued":""} ${Pe(o)}`);try{const u=i.addSourceBuffer(c),h=En(a),d=[a,u];t[h]=d,o.buffer=u}catch(u){var s;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[a],this.hls.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:c,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&(t==="video"||t==="audiovideo")&&Vi(i,"video")&&(s=Ug(s,i));const n=Ps(s,e.levelCodec);return n?t.slice(0,5)==="audio"?_s(n,this.appendSource):n:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const 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)=>{const o=a.removedRanges;o!=null&&o.length&&(this.log(`${n} buffer removed ${$s(o)}`),this.hls.trigger(v.BUFFER_FLUSHED,{type:n,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,i;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);if(!s)return;if(s.onComplete(),(i=this.tracks[e])==null||(i=i.buffer)==null?void 0:i.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var i;const s=(i=this.mediaSource)==null?void 0:i.readyState,n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${s}`);this.error(`${n.message}`,t),this.hls.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const a=this.currentOp(e);a&&a.onError(n)}updateTimestampOffset(e,t,i,s,n,a){const 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){const{media:s,mediaSource:n}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!s||!n||!o)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);const l=q(s.duration)?s.duration:1/0,c=q(n.duration)?n.duration:1/0,u=Math.max(0,t);if(u>=c){var h;(h=this.currentOp(e))==null||h.onComplete(),this.shiftAndExecuteNext(e);return}const d=Math.min(i,l,c);if(d>u&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${u},${d}] from the ${e} SourceBuffer`),o.remove(u,d);else throw new Error(`Cannot remove ${d<=u?`invalid range (${u} >= ${d}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){const i=this.tracks[t],s=i==null?void 0:i.buffer;if(!s)throw new qm(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){const n=this.calculateAppendTimeoutTime(s);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,s,n),n)}s.appendBuffer(e)}appendTimeoutHandler(e,t,i){this.log(`Received timeout after ${i}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch{this.log(`Failed to abort append on ${e} source buffer after timeout.`)}const s=this.currentOp(e);s&&s.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=Hl;this.details&&(t=this.details.levelTargetDuration);let i=2*t*1e3;if(this.media===null)return i;const s=le.bufferInfo(e,this.media.currentTime,0);return s.len?(i=Math.max(s.len*1e3,i),Math.max(this.hls.config.appendTimeout,i)):i}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(n).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const s=(i=this.tracks[t])==null?void 0:i.buffer;!s||s.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const n=s.buffer;if(!n)return;const a=i.bind(this,e);s.listeners.push({event:t,listener:a}),xe(n,t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(s=>{Ae(i,s.event,s.listener)}),t.listeners.length=0)}}function Yc(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function jm(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function En(r){return r==="audio"?1:0}function zc(r,e){return`${r?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function Xc(r){return`${r.type}_${r.sn}_${r.level}`}function Sn(r,e){const{start:t,end:i}=e;let s=0;for(let n=0;n<r.length;n++){const a=r[n];if(a.start>=i)break;const o=Math.max(t,a.start),l=Math.min(i,a.end);l>o&&(s+=l-o)}return s}function Qc(r,e){return e.duration-r<=.05}class Tn{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:e}=this;e&&(e.on(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.BUFFER_CODECS,this.onBufferCodecs,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:e}=this;e&&(e.off(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){const i=t.media;this.clientRect=null,this.hls&&(i instanceof HTMLVideoElement?(this.media=i,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls){if((this.timer||this.observer)&&(q(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){const e=this.hls.levels;e.length>1&&e.some(t=>!!t.videoCodec)&&this.startCapping()}}}onBufferCodecs(e,t){t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}const e=this.hls.levels;if(e.length>1){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.observer||(this.clientRect=null),Tn.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){const e=self.ResizeObserver;e&&(this.observer=new e(t=>{var i;const s=(i=t[0])==null?void 0:i.contentRect;s&&(this.clientRect=s,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||!((e=this.hls)!=null&&e.config.capLevelToPlayerSize)||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;const{ignoreDevicePixelRatio:t,maxDevicePixelRatio:i}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,i)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let n=e.length-1;const a=Math.max(t,i);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&s(l,e[o+1])){n=o;break}}return n}}var rt=class Do{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Do?i:new Do(i))),this.value=e,this.params=t}};const Ym="Dict";function zm(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 Xm(r,e,t,i){return new Error(`failed to ${r} "${zm(e)}" as ${t}`,{cause:i})}const Jc="Bare Item",Qm="Boolean",Jm="Byte Sequence",Zm="Decimal",e0="Integer";function t0(r){return r<-999999999999999||999999999999999<r}const i0="String",s0=/[\x00-\x1f\x7f]+/;var Zc=class{constructor(r){this.description=r}};const r0="Token",n0="Key";function Nt(r,e,t){return Xm("serialize",r,e,t)}function a0(r){if(typeof r!="boolean")throw Nt(r,Qm);return r?"?1":"?0"}function o0(r){if(ArrayBuffer.isView(r)===!1)throw Nt(r,Jm);return`:${zf(r)}:`}function eu(r){if(t0(r))throw Nt(r,e0);return r.toString()}function l0(r){return`@${eu(r.getTime()/1e3)}`}function c0(r){const e=Ho(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Nt(r,Zm);const t=e.toString();return t.includes(".")?t:`${t}.0`}function u0(r){if(s0.test(r))throw Nt(r,i0);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function h0(r){return r.description||r.toString().slice(7,-1)}function tu(r){const e=h0(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Nt(e,r0);return e}function bn(r){switch(typeof r){case"number":if(!q(r))throw Nt(r,Jc);return Number.isInteger(r)?eu(r):c0(r);case"string":return u0(r);case"symbol":return tu(r);case"boolean":return a0(r);case"object":if(r instanceof Date)return l0(r);if(r instanceof Uint8Array)return o0(r);if(r instanceof Zc)return tu(r);default:throw Nt(r,Jc)}}function An(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw Nt(r,n0);return r}function xn(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${An(e)}`:`;${An(e)}=${bn(t)}`).join("")}function iu(r){return r instanceof rt?`${bn(r.value)}${xn(r.params)}`:bn(r)}function d0(r){return`(${r.value.map(iu).join(" ")})${xn(r.params)}`}function f0(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw Nt(r,Ym);const t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof rt||(n=new rt(n));let a=An(s);return n.value===!0?a+=xn(n.params):(a+="=",Array.isArray(n.value)?a+=d0(n):a+=iu(n)),a}).join(`,${i}`)}function su(r,e){return f0(r,e)}const g0=["url"],p0=["version","eventTargets","sid","transmissionMode"],m0=["customData","headers"],ru=r=>r instanceof rt?new rt(Math.round(r.value),r.params):Math.round(r),In=r=>Array.isArray(r)?r.map(ru):ru(r),Rn=(r,e)=>Array.isArray(r)?r.map(t=>Rn(t,e)):r instanceof rt&&typeof r.value=="string"?new rt(Rn(r.value,e),r.params):(e.baseUrl&&(r=Zf(r,Jf(e.baseUrl))),e.version===1?encodeURIComponent(r):r),nu=r=>r instanceof rt?new rt(Math.round(r.value/100)*100,r.params):Math.round(r/100)*100,zs=r=>Array.isArray(r)?r.map(nu):nu(r),y0={br:In,d:In,bl:zs,dl:zs,mtp:zs,nor:(r,e)=>{let t=r;return e.version>=2&&(r instanceof rt&&typeof r.value=="string"?t=new rt([r]):typeof r=="string"&&(t=[r])),Rn(t,e)},rtp:zs,tb:In},is=2,au="bc",v0="ps",ou="pr",E0="e",lu="t",S0="c",cu="b",Ln="rr",uu="ce",Xs={BITRATE_CHANGE:au,ERROR:E0,RESPONSE_RECEIVED:Ln,CUSTOM_EVENT:uu},hu=new Map([[v0,"sta"],[ou,"pr"],[S0,"cid"],[cu,"bg"],[au,"br"]]),_n="event",Pn="request",du=["cen","e","h","ts"],fu=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],T0=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Dn(r){return T0.test(r)}const b0=new Set(fu);function gu(r){return b0.has(r)||Dn(r)}const pu=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],A0=new Set(pu);function mu(r){return A0.has(r)}const x0=new Set(du);function I0(r){return gu(r)||mu(r)||x0.has(r)}const R0=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Qs=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],L0=new Set(Qs);function _0(r){return L0.has(r)||Dn(r)}const P0=new Set(["ot","sf","st","e","sta"]);function D0(r){return P0.has(r)}function w0(r){return typeof r=="number"?q(r):r!=null&&r!==""&&r!==!1}const C0={[_n]:I0,[Pn]:gu};function yu(r,e){if(Array.isArray(r)){let t;return e&&(t=r.find(i=>{var s;return((s=i.params)==null?void 0:s.ot)===e})),t||(t=r[0]),yu(t)}return r instanceof rt?r.value:r}function k0(r){const e={};for(const[i,s]of Object.entries(r)){if(s==null){e[i]=s;continue}if(i==="nor"){const n=(Array.isArray(s)?s:[s])[0];if(n instanceof rt){var t;e.nor=n.value,(t=n.params)!=null&&t.r&&(e.nrr=n.params.r)}else e.nor=n}else R0.has(i)?e[i]=yu(s,r.ot):e[i]=s}return e}function vu(r,e={}){const t={};if(r==null||typeof r!="object")return t;const i=e.version||r.v||is,s=e.reportingMode||Pn,n=i===1?k0(r):r,a=i===1?_0:C0[s];let o=Object.keys(n).filter(a);n.e&&n.e!==Ln&&(o=o.filter(g=>!mu(g)));const l=e.filter;typeof l=="function"&&(o=o.filter(l));const c=s===_n;if(c){const g=n.e;!o.includes("e")&&g!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&n.cen!=null&&g===uu&&o.push("cen");const f=g?hu.get(g):void 0;f&&n[f]!=null&&!o.includes(f)&&o.push(f)}if(o.length===0)return t;i>1&&!o.includes("v")&&o.push("v");const u={version:i,reportingMode:s,baseUrl:e.baseUrl};o.sort();for(const g of o){var h,d;let f=n[g];const p=(h=(d=e.formatters)==null?void 0:d[g])!=null?h:y0[g];if(typeof p=="function"&&(f=p(f,u)),g==="v"){if(i===1)continue;f=i}if(g==="pr"&&f===1&&!(c&&n.e===ou))continue;c&&g==="ts"&&!q(f)&&(f=Date.now());const m=c&&f===!1&&g==="bg"&&n.e===cu;!w0(f)&&!m||(D0(g)&&typeof f=="string"&&(f=new Zc(f)),t[g]=f)}return t}const Vt="CMCD-Object",nt="CMCD-Request",xi="CMCD-Session",At="CMCD-Status",O0={REQUEST:nt},F0={ab:Vt,br:Vt,d:Vt,lab:Vt,lb:Vt,ot:Vt,tab:Vt,tb:Vt,tpb:Vt,bl:nt,cs:nt,dfa:nt,dl:nt,ltc:nt,mtp:nt,nor:nt,nrr:nt,pb:nt,sn:nt,sta:nt,su:nt,tbl:nt,cid:xi,msd:xi,sf:xi,sid:xi,st:xi,v:xi,bg:At,bs:At,bsa:At,bsd:At,bsda:At,cdn:At,ec:At,nr:At,pr:At,pt:At,rtp:At};function M0(r){return Object.keys(r).reduce((e,t)=>{var i;return(i=r[t])==null||i.forEach(s=>e[s]=t),e},{})}function N0(r,e){const t={};if(!r)return t;const i=Object.keys(r),s=e?M0(e):{};for(const a of i){var n;const o=F0[a]||s[a]||O0.REQUEST,l=(n=t[o])!=null?n:t[o]={};l[a]=r[a]}return t}function B0(r,e){const t={},i=N0(r,e);for(const[s,n]of Object.entries(i)){const a=su(n,{whitespace:!1});a&&(t[s]=a)}return t}const Eu="CMCD";function Su(r){return su(r,{whitespace:!1})}function U0(r,e={}){return r?Su(vu(r,e)):""}const $0=30,wn=[...Qs,...fu,...pu,...du].filter((r,e,t)=>t.indexOf(r)===e),G0="application/cmcd",V0=1,ze={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},xt={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},Cn="query",Tu="headers";function bu(r,e,t){var i;const s=new Set((i=e.enabledKeys)!=null?i:[]);return{version:e.version||is,reportingMode:r,filter:n=>s.has(n),baseUrl:t}}function H0(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){const i=r[t],s=e[t];if(i===s)continue;if(typeof i=="number"||typeof s=="number"||i.value!==s.value)return!1;const n=i.params,a=s.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l||o!==void 0&&l!==void 0&&n&&a&&n[o]!==a[l])return!1}return!0}const K0=Object.is,q0=r=>r,Au=Array.from(hu,([r,e])=>e==="br"?{event:r,field:e,equal:(t,i)=>t===void 0||i===void 0?t===i:H0(t,i),snapshot:t=>t.slice()}:{event:r,field:e,equal:K0,snapshot:q0}),W0=new Map(Au.map(r=>[r.event,r]));function j0(r){const{url:e}=r,t=vs(r,g0);return fetch(e,t)}function Y0(r){const{version:e=is,eventTargets:t=[],sid:i=Ko(),transmissionMode:s=Cn}=r,n=vs(r,p0);return re(re({},n),{},{version:e,transmissionMode:s,sid:i,eventTargets:t.reduce((a,o)=>{var l,c,u;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||is,enabledKeys:((c=o.enabledKeys)==null?void 0:c.slice())||[],url:o.url,events:o.events.slice(),interval:(u=o.interval)!=null?u:$0,batchSize:o.batchSize||1}),a},[])})}var z0=class{constructor(r,e=j0){var t;this.timeOrigin=performance.timeOrigin||((t=performance.timing)==null?void 0:t.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=Y0(r),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const i of this.config.eventTargets)this.eventTargets.set(i,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((r,e)=>{if(this.disarmInterval(r),e.interval===0||!e.events.includes(lu))return;const t=()=>{this.recordTargetEvent(r,e,lu),this.processEventTargets()};r.intervalId=setInterval(t,e.interval*1e3),t()})}stop(r=!1){r&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(r){r.sid&&r.sid!==this.data.sid&&this.resetSession(),r.msd&&!isNaN(r.msd)&&(this.msd=r.msd),this.data=re(re(re({},this.data),r),{},{msd:void 0});for(const e of Au)e.field in r&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(r,e={}){const t=W0.get(r);if(t){const i=t.field,s=e[i];s!==void 0&&Re(this.data,{[i]:s});const n=this.data[i];if(n===void 0||t.equal(n,this.lastEmitted[i]))return;Re(this.lastEmitted,{[i]:t.snapshot(n)})}this.eventTargets.forEach((i,s)=>{this.recordTargetEvent(i,s,r,e)}),this.processEventTargets()}recordTargetEvent(r,e,t,i={}){var s;if(!e.events.includes(t))return;const n=re(re(re({},this.data),i),{},{e:t,ts:(s=i.ts)!=null?s:Date.now(),sn:r.sn++});!isNaN(this.msd)&&!r.msdSent&&(n.msd=this.msd,r.msdSent=!0),r.queue.push(n)}recordResponseReceived(r,e={}){var t,i,s;const{request:n}=r,a=(t=e.url)!=null?t:n==null?void 0:n.url;if(!a)return;const o=new URL(a);o.searchParams.delete(Eu);const l={url:o.toString(),rc:r.status},c=r.resourceTiming;c&&(c.startTime!=null&&(l.ts=Math.round(this.timeOrigin+c.startTime),c.responseStart!=null&&(l.ttfb=Math.round(c.responseStart-c.startTime))),c.duration!=null&&(l.ttlb=Math.round(c.duration)));const u=(i=(s=n.customData)==null?void 0:s.cmcd)!=null?i:{};this.recordEvent(Ln,re(re(re({},u),l),e))}applyRequestReport(r){var e;return(e=this.createRequestReport(r))!=null?e:r}isRequestReportingEnabled(){var r;return!!((r=this.config.enabledKeys)!=null&&r.length)}createRequestReport(r,e){var t;const{customData:i={},headers:s={}}=r,n=vs(r,m0),a=re(re({},n),{},{headers:re({},s),customData:re(re({},i),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;const o=new URL(a.url),l=re(re(re({},this.data),e),{},{sn:this.requestTarget.sn++}),c=bu(Pn,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);const u=a.customData.cmcd=vu(l,c);switch(this.config.transmissionMode){case Cn:const h=Su(u);h&&(o.searchParams.set(Eu,h),a.url=o.toString());break;case Tu:Re(a.headers,B0(u,c.customHeaderMap));break}return a}processEventTargets(r=!1){let e=!1;this.eventTargets.forEach((t,i)=>{const{queue:s}=t;if(!s.length||s.length<i.batchSize&&!r)return;const n=r?s.length:i.batchSize,a=s.splice(0,n);this.sendEventReport(i,a).catch(()=>{t.queue.unshift(...a)}),e||(e=s.length>0)}),e&&this.processEventTargets()}async sendEventReport(r,e){const t=bu(_n,r),{status:i}=await this.requester({url:r.url,method:"POST",headers:{"Content-Type":G0},body:e.map(s=>U0(s,t)).join(`
28
- `)+`
29
- `});if(i===410)this.disposeEventTarget(r);else if(i===429||i>499&&i<600)throw new Error(`Event report failed with status ${i}`)}disarmInterval(r){clearInterval(r.intervalId),r.intervalId=void 0}disposeEventTarget(r){const e=this.eventTargets.get(r);e&&(this.disarmInterval(e),this.eventTargets.delete(r))}resetSession(){this.eventTargets.forEach(r=>r.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const X0={HLS:"h"},kn={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function Q0(r,e){return new rt(r,e)}new Set(Qs),new Set(wn);const J0=["includeKeys"];function xu(r){return Object.keys(r).every(Dn)}class Z0{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(xt.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(xt.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(xt.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(xt.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(xt.SEEKING)},this.onSeeked=()=>{var s;this.initialized&&(s=this.media)!=null&&s.paused&&this.setPlayerState(xt.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=s=>{try{this.apply(s,{ot:ze.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{const{frag:o,part:l}=s,c=this.hls.levels[o.level],u=this.getObjectType(o,c),h={d:(l||o).duration*1e3,ot:u};if(u===ze.VIDEO||u===ze.AUDIO||u===ze.MUXED||u==null&&(o.type==="main"||o.type==="audio")){var n;const g=c.bitrate/1e3;h.br=[g];const{cmcd:f}=this.config,p=(n=f==null?void 0:f.rtpSafetyFactor)!=null?n:5;if(h.rtp=Math.round(g*p/100)*100,u===ze.MUXED||u==null&&o.type==="main"){const E=this.getTopBandwidth()/1e3;q(E)&&(h.tb=[E]);const S=this.getLowestBandwidth()/1e3;q(S)&&(h.lb=[S])}const m=this.getBufferLength(o);if(q(m)){var a;h.bl=[m];const E=((a=this.media)==null?void 0:a.playbackRate)||1;h.dl=Math.round(m/E/100)*100}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);const y=this.hls.maxAutoLevel;if(y>=0){const E=this.hls.levels[y];E&&(h.tpb=[E.bitrate/1e3])}}const d=l?this.getNextPart(l):this.getNextFrag(o);d!=null&&d.url&&d.url!==o.url&&(d.byteRange.length>0?h.nor=[Q0(d.url,{r:`${d.byteRange[0]}-${d.byteRange[1]}`})]:h.nor=[d.url]),this.apply(s,h)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(s,n,a)=>{var o;const{cmcd:l}=this.config,c=l==null||(o=l.eventTargets)==null?void 0:o.some(u=>{var h;return(h=u.events)==null?void 0:h.includes(Xs.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!c))try{this.reporter.recordResponseReceived({request:{url:s},status:n.code,resourceTiming:{startTime:a.loading.start,responseStart:a.loading.first,duration:a.loading.end-a.loading.start,encodedBodySize:a.total}})}catch(u){this.hls.logger.warn("Could not record fragment response CMCD data.",u)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;const{cmcd:i}=this.config;if(i==null)return;const s=i.version||V0;if(this.reporter=new z0({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:s,transmissionMode:i.useHeaders===!0?Tu:Cn,enabledKeys:(e=i.includeKeys)!=null?e:[...s>=is?wn:Qs],eventTargets:((t=i.eventTargets)!=null?t:[]).map(n=>{let{includeKeys:a}=n,o=vs(n,J0);return re(re({},o),{},{enabledKeys:a??wn})})},i.loader),this.reporter.update({sf:X0.HLS,sta:this.playerState}),i.reporterCallback){const n=this.reporter,a={updateCustomData:o=>{xu(o)&&n.update(o)},recordCustomEvent:(o,l={})=>{xu(l)&&n.recordEvent(Xs.CUSTOM_EVENT,re({cen:o},l))}};i.reporterCallback(a)}this.reporter.start()}registerListeners(){const e=this.hls;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_DETACHED,this.onMediaDetached,this),e.on(v.MEDIA_ENDED,this.onMediaEnded,this),e.on(v.ERROR,this.onError,this),e.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(v.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(v.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(v.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const e=this.hls;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_DETACHED,this.onMediaDetached,this),e.off(v.MEDIA_ENDED,this.onMediaEnded,this),e.off(v.ERROR,this.onError,this),e.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(v.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(v.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(v.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){const i=this.media=t.media;this.setPlayerState(this.media.autoplay?xt.STARTING:xt.PRELOADING),xe(i,"waiting",this.onWaiting),xe(i,"play",this.onPlay),xe(i,"playing",this.onPlaying),xe(i,"pause",this.onPause),xe(i,"seeking",this.onSeeking),xe(i,"seeked",this.onSeeked),xe(i,"ratechange",this.onRateChange)}onMediaDetached(){const e=this.media;e&&(Ae(e,"waiting",this.onWaiting),Ae(e,"play",this.onPlay),Ae(e,"playing",this.onPlaying),Ae(e,"pause",this.onPause),Ae(e,"seeking",this.onSeeking),Ae(e,"seeked",this.onSeeked),Ae(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(xt.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(xt.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(xt.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(Xs.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var i;if(!this.reporter)return;const s={br:[t.bitrate/1e3]},n=(i=t.details)==null?void 0:i.fragments[0];n&&(s.ot=this.getObjectType(n,t)),this.reporter.recordEvent(Xs.BITRATE_CHANGE,s)}onLevelSwitched(e,t){const i=this.hls.levels[t.level];i&&(this.playheadLevel=i)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){const e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?kn.LOW_LATENCY:kn.LIVE:kn.VOD}apply(e,t={}){var i;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(i=this.media)==null?void 0:i.playbackRate,st:this.getStreamType()});const s=t.ot===ze.INIT||t.ot===ze.VIDEO||t.ot===ze.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const n=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=n.url,e.headers=n.headers}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const s=e.sn-i.startSN;return i.fragments[s+1]}}getNextPart(e){var t;const{index:i,fragment:s}=e,n=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(n){const{sn:a}=s;for(let o=n.length-1;o>=0;o--){const l=n[o];if(l.index===i&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e,t){const{type:i}=e;if(i==="subtitle")return ze.TIMED_TEXT;if(e.sn==="initSegment")return ze.INIT;if(i==="audio")return ze.AUDIO;if(i==="main"){if(e.hasStreams){const s=e.elementaryStreams;if(s.audiovideo)return ze.MUXED;if(s.video)return ze.VIDEO;if(s.audio)return ze.AUDIO}if(t){const{audioCodec:s,videoCodec:n}=t;if(!this.hls.audioTracks.length){if(s&&n)return ze.MUXED;if(s)return ze.AUDIO}if(n)return ze.VIDEO}}}getTopBandwidth(){let e=0;const t=this.hls,i=t.maxAutoLevel,s=i>-1?i+1:t.levels.length;return t.levels.slice(0,s).forEach(a=>{a.bitrate>e&&(e=a.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0;const t=this.hls,i=t.maxAutoLevel,s=i>-1?i+1:t.levels.length;return t.levels.slice(0,s).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),q(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;const t=e.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?t.len*1e3:NaN}getEventBufferLength(){if(!this.media)return NaN;const e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return Math.min(e.len,t.len)*1e3;const i=e||t;return i?i.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;const i=this.getEventBufferLength();q(i)&&this.reporter.update({bl:[i]})}createPlaylistLoader(){const{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(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=this.recordFragmentResponse,s=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new s(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,o,l){t(a);const{onSuccess:c}=l;this.loader.load(a,o,re(re({},l),{},{onSuccess:(u,h,d,g)=>{c(u,h,d,g),i(a.url,u,h)}}))}}}}const ey=3e5;class ty extends dt{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(){const e=this.hls;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.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){const 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){const 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){const{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){const{errorAction:i}=t;if((i==null?void 0:i.action)===je.SendAlternateToPenaltyBox&&i.flags&Ke.MoveAllAlternatesMatchingHost){const s=this.levels;let n=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&s?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&s&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a,!i.resolved&&(t.details!==D.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${Pe(n)} penalized: ${Pe(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const 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;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>ey&&delete i[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,fc(t),this.hls.trigger(v.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(t===pe.AUDIO_TRACK&&s[n].hasAudioGroup(e)||t===pe.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(e))return s[n].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(u=>{const h=new Oe(u.attrs);h["PATHWAY-ID"]=a;const d=h.AUDIO&&`${h.AUDIO}_clone_${a}`,g=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(i[h.AUDIO]=d,h.AUDIO=d),g&&(s[h.SUBTITLES]=g,h.SUBTITLES=g);const f=Ru(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new Ki({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let m=1;m<u.audioGroups.length;m++)p.addGroupId("audio",`${u.audioGroups[m]}_clone_${a}`);if(u.subtitleGroups)for(let m=1;m<u.subtitleGroups.length;m++)p.addGroupId("text",`${u.subtitleGroups[m]}_clone_${a}`);return p});t.push(...c),Iu(this.audioTracks,i,l,a),Iu(this.subtitleTracks,s,l,a)})}loadSteeringManifest(e){const 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:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;Wt(s,"_HLS_pathway",this.pathwayId),Wt(s,"_HLS_throughput",""+u)}const n={type:pe.STEERING_MANIFEST,responseType:"json",url:s.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,h,d,g)=>{this.log(`Loaded steering manifest: "${s}"`);const f=u.data;if((f==null?void 0:f.VERSION)!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":y}=f;if(p)try{this.uri=new self.URL(p,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||d.url),m&&this.clonePathways(m);const E={steeringManifest:f,url:s.toString()};this.hls.trigger(v.STEERING_MANIFEST_LOADED,E),y&&this.updatePathwayPriority(y)},onError:(u,h,d,g)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let f=this.timeToLoad*1e3;if(u.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const m=p.getResponseHeader("Retry-After");m&&(f=parseFloat(m)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,f)},onTimeout:(u,h,d)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const 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 Iu(r,e,t,i){r&&Object.keys(e).forEach(s=>{const n=r.filter(a=>a.groupId===s).map(a=>{const o=Re({},a);return o.details=void 0,o.attrs=new Oe(o.attrs),o.url=o.attrs.URI=Ru(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 Ru(r,e,t,i){if(e){const{[t]:o}=i;if(o){const l=o[e];if(l)return l}}const{HOST:s,PARAMS:n}=i,a=new self.URL(r);return s&&(a.hostname=s),n&&Object.keys(n).sort().forEach(o=>{o&&Wt(a,o,n[o])}),a.href}class iy{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new cn,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((e,t)=>{this.emitter.on("error",t),this.emitter.on("resolved",e)})}reset(){this.emitter.removeAllListeners();const e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}class It 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}}class Ii extends dt{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=Ii.CDMCleanupPromise?[Ii.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:i,initData:s}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.log(n),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=ji(this.config));const o=a.map(tn).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o;const l=Bs(a),c=this.activeLevelKeys();if(l===we.FAIRPLAY&&i==="sinf")try{const f=bt(new Uint8Array(s)),p=Nr(JSON.parse(f).sinf),m=sl(p);if(!m)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(m.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}else if(l===we.PLAYREADY)o=sn(new Uint8Array(s));else if(l===we.WIDEVINE){const f=ll(s).filter(p=>p.systemId===jl.WIDEVINE);if(f.length){var u;const p=f[0];o=(u=p.kids)!=null&&u.length?p.kids[0]:null}}let h;if(o){const f=Ge(o);for(let p=0;p<c.length;p++){const m=c[p];if(m.keyId&&(Ms(o,m.keyId)||m.uri.replace(/-/g,"").indexOf(f)!==-1)){m.pssh||(m.scheme=i,m.pssh=new Uint8Array(s),m.keyId=o,Ut.setKeyIdForUri(m.uri,o)),h=this.getSessionForKey(m,"encrypted-event-key-match");break}}}if(!h){if(c.length){var d,g;return(d=c[0]).scheme||(d.scheme=i),(g=c[0]).pssh||(g.pssh=new Uint8Array(s)),this.getSessionForKey(c[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${Ge(o)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return h}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:e}=this;e&&(e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHED,this.onMediaDetached,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHED,this.onMediaDetached,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));const t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const u=c.shift();this.getMediaKeysPromise(u,s,n).then(h=>a({keySystem:u,mediaKeys:h})).catch(h=>{c.length?l(c):h instanceof It?o(h):o(new It({type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Yl===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;const n=xp(e,t,i,this.config.drmSystemOptions||{});let 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: ${Pe(n)}`),o=this.requestMediaKeySystemAccess(e,n);const l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),o.then(c=>{this.throwIfDestroyed(),this.log(`Access for key-system "${c.keySystem}" obtained`);const u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const h=l.mediaKeys=c.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,u.then(g=>g?this.setMediaKeysServerCertificate(d,e,g):d)));return h.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),h})}return o.then(()=>a.mediaKeys)}getMediaKeySessionContext(e,t,i,s){const{mediaKeySessions:n}=this,a=` key-session "${e}" keyId: ${Ge(i.keyId||[])} keyUri: ${i.uri} for "${s}"`;for(let c=0;c<n.length;c++){const u=n[c];if(!u.initialized&&u.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${a}`),u}this.log(`Creating${a}`);const o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:s},initialized:!1};return n.push(l),l}resetMediaKeys(){var e;const t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,i=this.keySystemAccessPromises[t];i&&(this.log("reset mediaKeys"),this.mediaKeys=null,i.hasMediaKeys=!1,delete i.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,i){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Ge(t.keyId||[])}
30
- } (data length: ${i.byteLength})`),s.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>tn(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{const i=tn(t);if(!i)throw new Error(`Unable to find format for key-system "${t}"`);return i})}selectKeySystemFormat(e){const 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){const t=ji(this.config),i=e.map(Bs).filter(s=>!!s&&t.indexOf(s)!==-1);return this.selectKeySystem(i)}loadClear(e,t,i){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,n=t.length;s<n;s++){const a=t[s];if(e.cc<=a.cc&&(!Ne(e)||!Ne(a)||e.sn<a.sn)||!i&&s==n-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);const l=Bs(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const s=ji(this.config);if(s.length)return this.getKeySystemAccess(s)}}return null}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){const s=On(e,t[i]);if(s)return s}}loadKey(e){const t=e.decryptdata,i=this.getKeyStatus(t);if(i==="internal-error"){const o=Lu(i,t);return o.data.frag=e,this.error(`${o.message} (${Ge(t.keyId||[])})`),Promise.reject(o)}const s=e.type,n=this.activeKeys,a=n[s];a&&!t.matches(a.decryptdata)&&(n.previous||(n.previous=[]),n.previous.push(a),delete n[s]),n[s]||(n[s]=e);for(let o=this.mediaKeySessions.length;o--;){const l=this.mediaKeySessions[o];if(t.keyId&&l.keyStatuses[Ge(t.keyId)]==="expired")return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,i){const s=this.getSessionForKey(e,t);return s.catch(n=>this.handleError(n,i)),s.then(n=>e)}getSessionForKey(e,t){const i=this.findContextForKey(e);if(i!==void 0)return Promise.resolve(i);const s=e.uri,n=this.sessionSetupByUri[s];let a;n===void 0?a=this.resolveSessionForKey(e,t):a=n.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[s]=a;const o=()=>{this.sessionSetupByUri[s]===a&&delete this.sessionSetupByUri[s]};return a.then(o,o),a}findContextForKey(e){const{mediaKeySessions:t}=this;for(let i=t.length;i--;){const s=t[i];if(On(e,s))return s}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:i,mediaKeys:s})=>{this.throwIfDestroyed();for(let n=this.mediaKeySessions.length;n--;){const a=this.mediaKeySessions[n];if(On(e,a))return a;const o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,s,e,t))).then(n=>{this.throwIfDestroyed();const a=e.scheme||"cenc",o=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(n,e,a,o,t)})})}getUsableKeyPromise(e,t,i){const s=e.keyRequests[t.uri];if(s)return this.log(`Waiting for usable key (${i} keyId: ${ny(t)} format: "${t.keyFormat}" URI: ${t.uri})`),s.useable.then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof It){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${Ge(i.keyId||[])})`:""}`),this.hls.trigger(v.ERROR,e.data)}else this.error(e.message),this.hls.trigger(v.ERROR,{type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Bs(e.keyFormat),i=t?[t]:ji(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(e){if(e.length||(e=ji(this.config)),e.length===0)throw new It({type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Pe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){const e=this.activeKeys,t=(e.previous||[]).map(i=>i.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}filterInitData(e,t,i,s,n){var a;const o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const c=o.call(this.hls,i,s,Re({},e,{decryptdata:t,reason:n}),n);if(!c)throw new Error("Invalid response from configured generateRequest filter");t.scheme=c.initDataType?c.initDataType:"cenc";const u=c.initData?c.initData:null;return t.pssh=u?new Uint8Array(u):null,c}catch(c){var l;if(this.warn(c.message),(l=this.hls)!=null&&l.config.debug)throw c}return{initDataType:i,initData:s}}generateRequestWithPreferredKeySession(e,t,i,s,n){const a=this.getUsableKeyPromise(e,t,n);if(a)return a;const o=this.filterInitData(e,t,i,s,n);if(o&&(s=o.initData?o.initData:null,i=o.initDataType),s===null)return n.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${n}"`)):(this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e));const l=t.uri,c=new iy;e.keyRequests[l]=c;const u=d=>{const g=e.mediaKeysSession;if(!g){const m=new Error("invalid state");c.errored=m;return}const{messageType:f,message:p}=d;c.status=f,this.log(`"${f}" message event for session "${g.sessionId}" message size: ${p.byteLength}`),f==="license-request"||f==="license-renewal"?this.renewLicense(e,t,p).catch(m=>{c.errored=m,c.hasListeners||this.handleError(m),this.removeSession(e)}):f==="license-release"?e.keySystem===we.FAIRPLAY&&this.updateKeySession(e,t,en("acknowledged")).then(()=>this.removeSession(e)).catch(m=>this.handleError(m)):this.warn(`unhandled media key message type "${f}"`)};return c.onmessage=u,xe(e.mediaKeysSession,"message",u),this.generateRequest(e,t,i,s,n,!1)}generateRequest(e,t,i,s,n,a){if(a){const g=this.filterInitData(e,t,i,s,n);g&&(s=g.initData?g.initData:s,i=g.initDataType)}const o=t.uri,l=e.keyRequests[o],c=Ge(t.keyId||[]),u=g=>{let f;g.startsWith("usable")?l.resolve():g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?f=Lu(g,t):g==="expired"?f=new Error(`key expired (keyId: ${c})`):g==="released"?f=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${c})`),f&&(l.errored=f,l.hasListeners||this.handleError(f))},h=g=>{if(!e.mediaKeysSession){const b=new Error("invalid state");l.errored=b;return}const p=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(p).some(b=>p[b]!=="status-pending"))return;const y=this.activeLevelKeys();for(let b=0;b<y.length;b++){const R=Ge(y[b].keyId||[]);if(p[R]==="expired"){var E;this.log(`Expired key ${Pe(p)} in key-session "${(E=e.mediaKeysSession)==null?void 0:E.sessionId}"`),this.renewKeySession(t,e).catch(I=>this.handleError(I));break}}let S=p[c];if(S)u(S);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[c]||(T[c]=self.setTimeout(()=>{var R;if(!e.mediaKeysSession)return;const I=this.getKeyStatus(t);if(I&&I!=="status-pending"){var L;return this.log(`No status for keyId ${c} in key-session "${(L=e.mediaKeysSession)==null?void 0:L.sessionId}". Using session key-status ${I} from other session.`),u(I)}this.log(`key status for ${c} in key-session "${(R=e.mediaKeysSession)==null?void 0:R.sessionId}" timed out after 1000ms`),S="internal-error",u(S)},1e3)),this.log(`No status for keyId ${c} (${Pe(p)}).`)}};l.onkeystatuseschange=h,xe(e.mediaKeysSession,"keystatuseschange",h);const d=l.useable;return this.log(`Generating key-session request for "${n}" keyId: ${c} URI: ${o} (init data type: ${i} length: ${s.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(i,s).then(()=>{var g;l.status="generated",this.log(`Request generated for key-session "${(g=e.mediaKeysSession)==null?void 0:g.sessionId}" keyId: ${c} URI: ${o}`)}).catch(g=>{throw this.log(`mediaKeysSession.generateRequest failed: ${g}`),new It({type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:t,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>d).catch(g=>{var f;this.log(`mediaKeysSession.generateRequest failed: ${g}`);const p=(f=g.data)==null?void 0:f.details;return(p===D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||p===D.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(m=>e.keyStatuses[m]==="usable")?(this.handleError(g),e):this.removeSession(e).then(()=>{throw g})}).then(()=>e)}getKeyStatuses(e){const t={},i=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((s,n)=>{if(typeof n=="string"&&typeof s=="object"){const l=n;n=s,s=l}const a="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===we.PLAYREADY&&a.length===16){const l=Ge(a);t[l]=s,ql(a)}const o=Ge(a);this.log(`key status change "${s}" for keyStatuses keyId: ${o} key-session "${i}"`),t[o]=s}),t}fetchServerCertificate(e){const t=this.config,i=t.loader,s=new i(t),n=ry(e,t);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={type:pe.SERVER_CERTIFICATE,responseType:"arraybuffer",url:n},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,g,f,p)=>{a(d.data)},onError:(d,g,f,p)=>{o(new It({type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:re({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,g,f)=>{o(new It({type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(d,g,f)=>{o(new Error("aborted"))}};s.load(l,u,h)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(a=>{n(new It({type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,i){return this.requestLicense(e,t,new Uint8Array(i)).then(s=>this.updateKeySession(e,t,new Uint8Array(s)).catch(n=>{throw new It({type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){const i=bt(new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const s=new DOMParser().parseFromString(i,"application/xml"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let h=0,d=n.length;h<d;h++){var a,o;u=n[h];const g=(a=u.querySelector("name"))==null?void 0:a.textContent,f=(o=u.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}const l=s.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return en(atob(c))}setupLicenseXHR(e,t,i,s,n){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,re(re({},i),{},{decryptdata:s}),n))).catch(o=>{if(!i.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,re(re({},i),{},{decryptdata:s}),n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t,i){return new Promise((s,n)=>{const a=sy(e.keySystem,this.config);if(!a)return n(new Error(`no license server URL configured for key-system "${e.keySystem}"`));const o=e.keyRequests[t.uri];if(!o)return n(new Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);const l=this.config.keyLoadPolicy.default,c=new XMLHttpRequest;c.responseType="arraybuffer",c.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(c.readyState===4)if(c.status===200){o.requestErrors=[];let u=c.response;this.log(`License received ${u instanceof ArrayBuffer?u.byteLength:u}`);const h=this.config.licenseResponseCallback;if(h)try{u=h.call(this.hls,c,a,re(re({},e),{},{decryptdata:t}))}catch(d){this.error(d)}s(u)}else{const u=l.errorRetry,h=u?u.maxNumRetry:0;if(o.requestErrors.push({status:c.status,message:c.statusText}),o.requestErrors.length>h||c.status>=400&&c.status<500)n(new It({type:se.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:c,response:{url:a,data:void 0,code:c.status,text:c.statusText}},`License Request XHR failed (${a}). Status: ${c.status} (${c.statusText})`));else{const d=h-o.requestErrors.length;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t,i).then(s,n)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=c,this.setupLicenseXHR(c,a,e,t,i).then(({xhr:u,licenseChallenge:h})=>{e.keySystem==we.PLAYREADY&&(h=this.unpackPlayReadyKeyMessage(u,h)),u.send(h)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,xe(i,"encrypted",this.onMediaEncrypted),xe(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(Ae(e,"encrypted",this.onMediaEncrypted),Ae(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ut.clearKeyUriToKeyIdMap();const n=s.length;Ii.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(v.ERROR,{type:se.OTHER_ERROR,details:D.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(v.ERROR,{type:se.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i),this.keyFormatPromise.catch(()=>{})}}removeSession(e){const{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(o=>{const l=e.keyRequests[o];l.onmessage&&t.removeEventListener("message",l.onmessage),l.onkeystatuseschange&&t.removeEventListener("keystatuseschange",l.onkeystatuseschange),l.reset(),e.keyRequests[o]=void 0}),e.mediaKeysSession=void 0;const i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:s}=e;s&&Object.keys(s).forEach(o=>self.clearTimeout(s[o]));const{drmSystemOptions:n}=this.config;return(Rp(n)?new Promise((o,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o).catch(l)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(v.ERROR,{type:se.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).then(()=>t.closed).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(v.ERROR,{type:se.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}}Ii.CDMCleanupPromise=void 0;function sy(r,e){const{drmSystems:t,widevineLicenseUrl:i}=e,s=t==null?void 0:t[r];if(s)return s.licenseUrl;if(r===we.WIDEVINE&&i)return i}function ry(r,e){const{drmSystems:t}=e,i=t==null?void 0:t[r];if(i)return i.serverCertificateUrl}function ny(r){if(r.keyFormat===Ye.FAIRPLAY)return r.uri;if(r.keyId===null)throw new Error("keyId is null");return Ge(r.keyId)}function On(r,e){const t=r.keyId,i=e.mediaKeysSession;if(t&&i){const s=e.mediaKeysSession.keyStatuses;if(s.size)return s.has(t)?s.get(t):e.keyStatuses[Ge(t)]}}function Lu(r,e){const t=r==="output-restricted",i=t?D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:D.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new It({type:se.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}class ay{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(v.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(v.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const 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){const s=performance.now();if(t){if(this.lastTime){const n=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,c=this.hls;if(c.trigger(v.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let u=c.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(v.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}var Fn=(function(){if(Ns!=null&&Ns.VTTCue)return self.VTTCue;const r=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function i(o){return t(r,o)}function s(o){return t(e,o)}function n(o,...l){let c=1;for(;c<arguments.length;c++){const u=arguments[c];for(const h in u)o[h]=u[h]}return o}function a(o,l,c){const u=this,h={enumerable:!0};u.hasBeenReset=!1;let d="",g=!1,f=o,p=l,m=c,y=null,E="",S=!0,T="auto",b="start",R=50,I="middle",L=50,A="middle";Object.defineProperty(u,"id",n({},h,{get:function(){return d},set:function(x){d=""+x}})),Object.defineProperty(u,"pauseOnExit",n({},h,{get:function(){return g},set:function(x){g=!!x}})),Object.defineProperty(u,"startTime",n({},h,{get:function(){return f},set:function(x){if(typeof x!="number")throw new TypeError("Start time must be set to a number.");f=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},h,{get:function(){return p},set:function(x){if(typeof x!="number")throw new TypeError("End time must be set to a number.");p=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},h,{get:function(){return m},set:function(x){m=""+x,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},h,{get:function(){return y},set:function(x){y=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},h,{get:function(){return E},set:function(x){const _=i(x);if(_===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=_,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",n({},h,{get:function(){return S},set:function(x){S=!!x,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},h,{get:function(){return T},set:function(x){if(typeof x!="number"&&x!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");T=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},h,{get:function(){return b},set:function(x){const _=s(x);if(!_)throw new SyntaxError("An invalid or illegal string was specified.");b=_,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},h,{get:function(){return R},set:function(x){if(x<0||x>100)throw new Error("Position must be between 0 and 100.");R=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},h,{get:function(){return I},set:function(x){const _=s(x);if(!_)throw new SyntaxError("An invalid or illegal string was specified.");I=_,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},h,{get:function(){return L},set:function(x){if(x<0||x>100)throw new Error("Size must be between 0 and 100.");L=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},h,{get:function(){return A},set:function(x){const _=s(x);if(!_)throw new SyntaxError("An invalid or illegal string was specified.");A=_,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class oy{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function _u(r){function e(i,s,n,a){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(a||0)}const 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}class ly{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)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function Pu(r,e,t,i){const s=i?r.split(i):[r];for(const n in s){if(typeof s[n]!="string")continue;const a=s[n].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const Mn=new Fn(0,0,""),Js=Mn.align==="middle"?"middle":"center";function cy(r,e,t){const i=r;function s(){const o=_u(r);if(o===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const c=new ly;Pu(o,function(d,g){let f;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===g){c.set(d,t[p].region);break}break;case"vertical":c.alt(d,g,["rl","lr"]);break;case"line":f=g.split(","),c.integer(d,f[0]),c.percent(d,f[0])&&c.set("snapToLines",!1),c.alt(d,f[0],["auto"]),f.length===2&&c.alt("lineAlign",f[1],["start",Js,"end"]);break;case"position":f=g.split(","),c.percent(d,f[0]),f.length===2&&c.alt("positionAlign",f[1],["start",Js,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,g);break;case"align":c.alt(d,g,["start",Js,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let u=c.get("line","auto");u==="auto"&&Mn.line===-1&&(u=-1),l.line=u,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Js);let h=c.get("position","auto");h==="auto"&&Mn.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function a(){r=r.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),a(),e.endTime=s(),a(),n(r,e)}function Du(r){return r.replace(/<br(?: \/)?>/gi,`
31
- `)}class uy{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new oy,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,a=0;for(n=Du(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
32
- `;)++a;const o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
33
- `&&++a,t.buffer=n.slice(a),o}function s(n){Pu(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();const 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 Fn(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{cy(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const 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(){const 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}}function ss(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}const hy=/\r\n|\n\r|\n|\r/g,wu="Missing initPTS for VTT ",dy=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!q(t)||!q(i)||!q(s)||!q(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=3600*1e3*n,t};function Nn(r,e,t){return ss(r.toString())+ss(e.toString())+ss(t)}function fy(r,e,t,i,s,n,a){const o=new uy,l=ft(new Uint8Array(r)).trim().replace(hy,`
37
- `).split(`
38
- `),c=[],u=e?Lm(e.baseTime,e.timescale):0;let h="00:00.000",d=0,g=0,f=!1,p,m=!0;o.oncue=function(y){const E=t[i];let S=t.ccOffset;const T=(d-u)/9e4;if(f){if(E!=null&&E.new&&(S=t.ccOffset=E.start),T){if(!e){p=new Error(wu+"MPEGTS");return}S=T-t.presentationOffset}}else if(e)S=-e.baseTime/e.timescale;else{p=new Error(wu+"without X-TIMESTAMP-MAP");return}const b=y.endTime-y.startTime,R=gt((y.startTime+S-g)*9e4,s*9e4)/9e4;y.startTime=Math.max(R,0),y.endTime=Math.max(R+b,0);const I=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(I)),y.id?i&&(y.id=`hlsjscc${i}_${y.id}`):y.id=Nn(y.startTime,y.endTime,I),y.endTime>0&&c.push(y)},o.onparsingerror=function(y){p=y},o.onflush=function(){if(p){a(p);return}n(c)},l.forEach(y=>{if(m)if(y.startsWith("X-TIMESTAMP-MAP=")){m=!1,f=!0,y.slice(16).split(",").forEach(E=>{E.startsWith("LOCAL:")?h=E.slice(6):E.startsWith("MPEGTS:")&&(d=parseInt(E.slice(7)))});try{g=dy(h)/1e3}catch(E){p=E}return}else y===""&&(m=!1);o.parse(y+`
39
- `)}),o.flush()}const Bn="stpp.ttml.im1t",Cu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,ku=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,gy={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ou(r,e,t,i){const s=fe(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(o=>ft(o)),a=Rm(e.baseTime,1,e.timescale);try{n.forEach(o=>t(py(o,a)))}catch(o){i(o)}}function py(r,e){const s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(n).reduce((h,d)=>(h[d]=s.getAttribute(`ttp:${d}`)||n[d],h),{});!s.getAttribute("ttp:tickRate")&&s.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));const o=s.getAttribute("xml:space")!=="preserve",l=Fu(Un(s,"styling","style")),c=Fu(Un(s,"layout","region")),u=Un(s,"body","[begin]");return[].map.call(u,h=>{const d=Mu(h,o);if(!d||!h.hasAttribute("begin"))return null;const g=Gn(h.getAttribute("begin"),a),f=Gn(h.getAttribute("dur"),a);let p=Gn(h.getAttribute("end"),a);if(g===null)throw Nu(h);if(p===null){if(f===null)throw Nu(h);p=g+f}const m=new Fn(g-e,p-e,d);m.id=Nn(m.startTime,m.endTime,m.text);const y=c[h.getAttribute("region")],E=l[h.getAttribute("style")],S=my(y,E,l),{textAlign:T}=S;if(T){const b=gy[T];b&&(m.lineAlign=b),m.align=T}return Re(m,S),m}).filter(h=>h!==null)}function Un(r,e,t){const i=r.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Fu(r){return r.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Mu(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?Mu(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function my(r,e,t){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,l)=>{const c=$n(e,i,l)||$n(r,i,l)||$n(s,i,l);return c&&(o[l]=c),o},{})}function $n(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Nu(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Gn(r,e){if(!r)return null;let t=_u(r);return t===null&&(Cu.test(r)?t=yy(r,e):ku.test(r)&&(t=vy(r,e))),t}function yy(r,e){const t=Cu.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 vy(r,e){const t=ku.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i/1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}function Vn(r,e,t,i="",s="disabled"){const n=r.ownerDocument.createElement("track");return n.kind=e,n.label=t,i&&(n.srclang=i),n.src="data:,WEBVTT",n.track.mode=s,r.appendChild(n),n}function Ey(r){return r.forced&&Fg()?"forced":r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function Hn(r,e){const 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){be.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,r.addCue(s)}catch(s){be.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(r.mode=t)}function Kn(r,e,t,i){const s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=Ty(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 Sy(r,e){if(e<=r[0].startTime)return 0;const 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 Ty(r,e,t){const i=[],s=Sy(r,e);if(s>-1)for(let n=s,a=r.length;n<a;n++){const o=r[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}class by extends vn{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,i=!1;if(this.currentTrack){var s;const o=(s=this.currentTrack.trackNode)==null?void 0:s.track.mode;o==="showing"?(t=this.trackId,i=!0):o==="hidden"&&(t=this.trackId)}if(!i)for(let o=0;o<this.tracksInGroup.length;o++){var n;const l=(n=this.tracksInGroup[o].trackNode)==null?void 0:n.track.mode;if(l==="showing"){t=o;break}else t<0&&l==="hidden"&&(t=o)}if(t>-1){var a;this._subtitleDisplay=((a=this.tracksInGroup[t].trackNode)==null?void 0:a.track.mode)==="showing"}this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVEL_LOADING,this.onLevelLoading,this),e.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(v.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(i=>{i.trackNode||(i.trackNode=Vn(this.media,Ey(i),i.name,i.lang))});const t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;(t==null?void 0:t.mode)==="disabled"&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){const i=t.media;this.media=i;let s=this.trackId;this.queuedDefaultTrack>-1&&(s=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(s),this.createTracksInGroup(),this.useTextTrackPolling=!(i.textTracks&&"onchange"in i.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):i.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!s&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(n=>{const a=n.trackNode;a&&(a.track.mode="hidden",a.remove(),n.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{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==null?void 0:a.groupId}`);return}const 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){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,s=this.groupIds;let n=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(s==null?void 0:s.indexOf(a))===-1)){this.groupIds=i;const a=[];if(this.tracks.forEach(u=>{(u.textCodec===Bn?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!i||i.indexOf(u.groupId)>-1?(u.id=a.length,a.push(u)):u.trackNode&&(u.trackNode.remove(),u.trackNode=void 0))}),a.length===this.tracksInGroup.length){let u=!1;for(let h=0;h<a.length;h++)if(a[h]!==this.tracksInGroup[h]){u=!0;break}if(!u)return}a.length&&this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=a,this.trackId=-1,this.currentTrack=null;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const u=kt(o,a);if(u>-1)n=a[u];else{const h=kt(o,this.tracks);n=this.tracks[h]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(v.SUBTITLE_TRACKS_UPDATED,c),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const n=t[s];if(!(i&&!n.default||!i&&!e)&&(!e||ti(n,e)))return s}if(e){for(let s=0;s<t.length;s++){const n=t[s];if(ts(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const n=t[s];if(ts(e.attrs,n.attrs,["LANGUAGE"]))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===pe.SUBTITLE_TRACK&&t.context.id===this.trackId&&qi(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&ti(e,i))return i;const s=kt(e,this.tracksInGroup);if(s>-1){const n=this.tracksInGroup[s];return this.setSubtitleTrack(s,!0),n}else{if(i)return null;{const n=kt(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);const i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${(t==null?void 0: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(v.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){const i=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",s=t.trackNode.track;s.mode!==i&&(s.mode=i)}})}setSubtitleTrack(e,t=!1){const i=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=i.length||!q(e)){this.warn(`Invalid subtitle track id: ${e}`);return}const s=this.currentTrack,n=i[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),!n){s&&this.hls.trigger(v.SUBTITLE_TRACK_SWITCH,{id:e});return}const a=!!n.details&&!n.details.live;if(n===s&&a)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:l="",name:c,type:u,url:h}=n;this.hls.trigger(v.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:c,type:u,url:h});const d=this.switchParams(n.url,s==null?void 0:s.details,n.details);this.loadPlaylist(d)}}const Zs=2,Ay=100;class xy extends Nl{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.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(Ay),this.mediaSource=t.mediaSource;const i=this.media=t.media;xe(i,"playing",this.onMediaPlaying),xe(i,"waiting",this.onMediaWaiting),xe(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{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}getCurrentTime(){var e;const t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var i,s;const n=(i=this.hls)==null?void 0:i.config;if(!n)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,c=!this.seeking&&o,u=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(c||l){l&&this.stallResolved(e);return}if(u){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!1}));return}if(!le.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}const h=le.bufferInfo(a,e,0),d=this.fragmentTracker;d&&this.hls&&$u(h,e,d,this.hls);const g=h.nextStart||0;if(o&&d&&this.hls){const R=Bu(this.hls.inFlightFragments,e),I=h.len>Zs,L=!g||R||g-e>Zs&&!d.getPartialFragment(e);if(I||L)return;this.moved=!1}const f=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&d){if(!(h.len>0)&&!g)return;const I=Math.max(g,h.start||0)-e,A=!!(f!=null&&f.live)?f.targetduration*2:Zs,x=rs(e,d);if(I>0&&(I<=A||x)){a.paused||this._trySkipBufferHole(x);return}}const p=n.detectStallWithCurrentTimeMs,m=self.performance.now(),y=this.waiting;let E=this.stalled;if(E===null)if(y>0&&m-y<p)E=this.stalled=y;else{this.stalled=m;return}const S=m-E;if(!o&&(S>=p||y&&this.moved)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-((f==null?void 0:f.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return;if(a.currentTime!==e){const R=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${R} > ${e}`);return}}const b=le.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(b,S,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const 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(v.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const 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)){const n=le.bufferedInfo(le.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=le.timeRangesToArray(s),o=le.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=le.bufferedInfo(a,e,0).bufferedIndex,c=a[o].end,u=a[o+1].start;if((l===-1||l>o)&&u-c<1&&e-c<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${u} buffered index: ${l}`);this.warn(h.message),this.media.currentTime+=1e-6;let d=rs(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const g=le.bufferInfo(this.media,e,0);this.hls.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:d,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,i){var s,n;const{fragmentTracker:a,media:o}=this,l=(s=this.hls)==null?void 0:s.config;if(!o||!a||!l)return;const c=(n=this.hls)==null?void 0:n.latestLevelDetails,u=rs(i,a);if((u||c!=null&&c.live&&i<c.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const h=e.buffered,d=this.adjacentTraversal(e,i);(h&&h.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||d))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,s=e.nextStart;if(i&&s){const n=i.getFragAtPos(t,te.MAIN),a=i.getFragAtPos(s,te.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Pe(e)})`);this.warn(a.message),t.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){const{fragmentTracker:t,media:i,hls:s}=this,n=s==null?void 0:s.config;if(!i||!t||!n)return 0;const a=i.currentTime,o=le.bufferInfo(i,a,0);$u(o,a,t,s);const l=a<o.start?o.start:o.nextStart;if(l){const u=o.len<=n.maxBufferHole,h=o.len>0&&o.len<1&&i.readyState<3,d=l-a;if(d>0&&(u||h)){if(d>n.maxBufferHole){let y=!1;if(a===0){const E=t.getAppendedFrag(0,te.MAIN);E&&l<E.end&&(y=!0)}if(!y&&e){var c;if(!((c=s.loadLevelObj)!=null&&c.details)||Bu(s.inFlightFragments,l))return 0;let S=!1,T=e.end;for(;T<l;){const b=rs(T,t),R=b?b.duration:0;if(R>0)T+=R;else{S=!0;break}}if(S)return 0}}const{nudgeMaxRetry:g,skipBufferHolePadding:f}=n,p=++this.skipRetry>g,m=Math.max(l,a)+f;if(p||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${m}`),this.moved=!0,i.currentTime=m),!(e!=null&&e.gap)||p){const y=new Error(p?`Playhead still not moving after seeking over buffer hole from ${a} to ${m} after ${n.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${m}`),E={type:se.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:p,error:y,reason:y.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?E.part=e:E.frag=e),s.trigger(v.ERROR,E)}return m}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,n=t==null?void 0:t.config;if(!i||!n)return 0;const a=i.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){const o=a+(s+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Bu(r,e){const t=Uu(r.main);if(t&&t.start<=e)return t;const i=Uu(r.audio);return i&&i.start<=e?i:null}function Uu(r){if(!r)return null;switch(r.state){case U.IDLE:case U.STOPPED:case U.ENDED:case U.ERROR:return null}return r.frag}function rs(r,e){return e.getAppendedFrag(r,te.MAIN)||e.getPartialFragment(r)}function $u(r,e,t,i){const s=i.latestLevelDetails,n=rs(e,t);if(Gs(i.config)&&!r.nextStart&&s&&n&&i.interstitialsManager){const a="type"in n?n:n.fragment,o=Pl(s,a.sn);(o==null?void 0:o.level)===a.level&&yc(o,i.interstitialsManager.playerQueue,e)&&(r.nextStart=o.start)}}const Iy=.25;function qn(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Wn(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,Pe(s?re({type:s},i):i))}return n}const er=(()=>{const r=qn();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Ry{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(v.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(){const{hls:e}=this;e&&(e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return Vn(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=qn();if(a)for(let o=0;o<n.length;o++){const l=n[o].type;if(l===st.emsg&&!i||!s)continue;const c=Wo(n[o].data),u=n[o].pts;let h=u+n[o].duration;h>er&&(h=er),h-u<=0&&(h=u+Iy);for(let g=0;g<c.length;g++){const f=c[g];if(!jo(f)){this.updateId3CueEnds(u,l);const p=Wn(a,u,h,f,l);p&&this.id3Track.track.addCue(p)}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.track.cues;if(s)for(let n=s.length;n--;){const a=s[n];a.type===t&&a.startTime<e&&a.endTime===er&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let c;s==="audio"?c=u=>u.type===st.audioId3&&l:s==="video"?c=u=>u.type===st.emsg&&o:c=u=>u.type===st.audioId3&&l||u.type===st.emsg&&o,Kn(n.track,t,i,c)}}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;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=qn();if(i&&s&&!a){const{fragmentStart:p,fragmentEnd:m}=e;let y=this.assetCue;y?(y.startTime=p,y.endTime=m):o&&(y=this.assetCue=Wn(o,p,m,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),y&&(y.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(y),y.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:c}=e,u=Object.keys(c);let h=this.dateRangeCuesAppended;if(l&&t){var d;if((d=l.track.cues)!=null&&d.length){const p=Object.keys(h).filter(m=>u.indexOf(m)===-1);for(let m=p.length;m--;){var g;const y=p[m],E=(g=h[y])==null?void 0:g.cues;delete h[y],E&&Object.keys(E).forEach(S=>{const T=E[S];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(T)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(u.length===0||!q(f==null?void 0:f.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<u.length;p++){const m=u[p],y=c[m],E=y.startTime,S=h[m],T=(S==null?void 0:S.cues)||{};let b=(S==null?void 0:S.durationKnown)||!1,R=er;const{duration:I,endDate:L}=y;if(L&&I!==null)R=E+I,b=!0;else if(y.endOnNext&&!b){const x=u.reduce((_,w)=>{if(w!==y.id){const G=c[w];if(G.class===y.class&&G.startDate>y.startDate&&(!_||y.startDate<_.startDate))return G}return _},null);x&&(R=x.startTime,b=!0)}const A=Object.keys(y.attr);for(let x=0;x<A.length;x++){const _=A[x];if(!Sp(_))continue;const w=T[_];if(w)b&&!(S!=null&&S.durationKnown)?w.endTime=R:Math.abs(w.startTime-E)>.01&&(w.startTime=E,w.endTime=R);else if(o){let G=y.attr[_];Tp(_)&&(G=Yo(G));const K=Wn(o,E,R,{key:_,data:G},st.dateRange);K&&(K.id=m,this.id3Track.track.addCue(K),T[_]=K,a&&(_==="X-ASSET-LIST"||_==="X-ASSET-URL")&&K.addEventListener("enter",this.onEventCueEnter))}}h[m]={cues:T,dateRange:y,durationKnown:b}}}}}function Gu(){return self.SourceBuffer||self.WebKitSourceBuffer}function Vu(){if(!qt())return!1;const e=Gu();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Ly(){if(!Vu())return!1;const r=qt();return typeof(r==null?void 0:r.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(Hi(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(Hi(e,"audio"))))}function _y(){var r;const e=Gu();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}var Bt={DISABLED:0,SWITCHING:1,SWITCHED:2};const Py=100;class Hu extends on{constructor(e,t,i){super(e,t,i,"stream-controller",te.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Bt.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,n=s?s.currentTime:null;if(n===null||!q(n)||(this.log(`Media seeked to ${n}`),!this.getBufferedFrag(n)))return;const a=this.getFwdBufferInfoAtPos(s,n,te.MAIN,0);if(!a||a.len===0){this.log(`Main buffer empty at ${n} on "seeked" event: ${a&&a.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(Py),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i}`),e=i),this.state=U.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=U.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case U.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e==null?void 0:e[t],s=i==null?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=U.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=U.IDLE;break}break}case U.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===U.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(){const{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;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;const a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const p={type:this.targetBufferType()};this.hls.trigger(v.BUFFER_EOS,p),this.state=U.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;const c=a.details;if(!c||this.state===U.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=U.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&g&&Ne(g)&&this.fragmentTracker.getState(g)!==ke.OK){var f;const m=((f=this.backtrackFragment)!=null?f:g).sn-c.startSN,y=c.fragments[m-1];y&&g.cc===y.cc&&(g=y,this.fragmentTracker.removeFragment(y))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(g&&this.isLoopLoading(g,d)){if(!g.gap){const m=this.audioOnly&&!this.altAudio?_e.AUDIO:_e.VIDEO,y=(m===_e.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m)}g=this.getNextFragmentLoopLoading(g,c,o,te.MAIN,h)}g&&(this.exceedsMaxBuffer(o,h,g)||this.loadFragment(g,a,d))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===ke.NOT_LOADED||s===ke.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Bt.DISABLED){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===Bt.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const i=this.fragPlaying;if(i){const s=i.level;this.hls.trigger(v.FRAG_CHANGED,{frag:i,previousFrag:e}),(e==null?void 0:e.level)!==s&&this.hls.trigger(v.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===Bt.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;xe(i,"playing",this.onMediaPlaying),xe(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(Ae(i,"playing",this.onMediaPlaying),Ae(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(v.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Bt.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let n=0;n<t.levels.length;n++){const 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&&!_y(),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){const{levels:i}=this;if(!i||this.state!==U.IDLE)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=U.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const c=t.levelInfo,u=this.fragCurrent;u&&(this.state===U.FRAG_LOADING||this.state===U.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let h=0;if(o.live||(i=c.details)!=null&&i.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,c.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(c.details=o,this.levelLastLoaded=c,n||this.setStartPosition(o,h),this.hls.trigger(v.LEVEL_UPDATED,{details:o,level:a}),this.state===U.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=U.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((g,f)=>{if(f>=o.startCC)return!0;delete this.initPTS[f]}),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=this.playhead,a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!l)){const u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s}`),this.config.liveSyncMode==="buffered"){var c;const h=le.bufferInfo(i,s,0);if(!((c=h.buffered)!=null&&c.length)){i.currentTime=s;return}if(h.start<=n){i.currentTime=s;return}const{nextStart:g}=le.bufferedInfo(h.buffered,n,0);g&&(i.currentTime=g)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const 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}const o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=o.videoCodec,u=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new Hc(this.hls,te.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,p=f!==-1,{decryptRange:m,byteRange:y}=Os(i,s,this.iframesOnly),E=new Xr(i.level,i.sn,i.stats.chunkCount,y?y.end-y.start:n.byteLength,f,p,i.duration,this.iframesOnly,m),S=this.initPTS[i.cc];g.push(n,h,d,c,i,s,l.totalduration,u,E,S)}onAudioTrackSwitching(e,t){const i=this.hls,s=this.altAudio!==Bt.DISABLED;if(Cs(t.url,i))this.altAudio=Bt.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const 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=Bt.DISABLED,this.fragmentTracker.removeAllFragments(),i.once(v.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(v.AUDIO_TRACK_SWITCHED,t)}),i.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(v.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=Cs(t.url,this.hls);if(i){const 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?Bt.SWITCHED:Bt.DISABLED,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,n,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(n=o,s=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.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){const{frag:i,part:s}=t,n=i.type===te.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===U.PARSED&&(this.state=U.IDLE);return}let l=!1;if(Ne(i)&&(l=!!i.gap&&!i.tagList.some(c=>c[0]==="GAP")),this.fragBufferedComplete(i,s),l){var a;i.stats.retry++;const c=(a=this.levels)==null?void 0:a[i.level];c&&c.fragmentError++}}const o=this.media;o&&(!this._hasEnoughToStart&&le.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=U.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(te.MAIN,t);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===U.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===pe.LEVEL&&(this.state=U.IDLE);break;case D.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case D.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 D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=U.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==_e.AUDIO||!this.altAudio){const i=(t===_e.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=this.timelineOffset;s&&i&&(i+=s);const n=this.getLevelDetails(),a=le.getBuffered(e),o=a.length?a.start(0):0,l=o-i,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<c||this.loadingParts&&l<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this,n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=U.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(v.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===U.STOPPED||this.state===U.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:l,level:c}=a,{video:u,text:h,id3:d,initSegment:g}=s,{details:f}=c,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=U.PARSING,g){const m=g.tracks;if(m){const T=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(c,m,T,n),i.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:m})}const y=g.initPTS,E=g.timescale,S=this.initPTS[o.cc];if(q(y)&&(!S||S.baseTime!==y||S.timescale!==E)){const T=g.trackId;this.initPTS[o.cc]={baseTime:y,timescale:E,trackId:T};const b=this.initPTS.slice(0);i.trigger(v.INIT_PTS_FOUND,{timestampOffsets:b,frag:o,id:t,initPTS:y,timescale:E,trackId:T})}}if(u&&f){p&&u.type==="audiovideo"&&this.logMuxedErr(o);const m=f.fragments[o.sn-1-f.startSN],y=o.sn===f.startSN,E=!m||o.cc>m.cc;if(s.independent!==!1){const{startPTS:S,endPTS:T,startDTS:b,endDTS:R}=u;if(l)l.elementaryStreams[u.type]={startPTS:S,endPTS:T,startDTS:b,endDTS:R};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!E&&(this.couldBacktrack=!0),u.dropped&&u.independent){const I=this.getMainFwdBufferInfo(),L=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,A=u.firstKeyFramePTS?u.firstKeyFramePTS:S;if(!y&&L<A-this.config.maxBufferHole&&!E){this.backtrack(o);return}else E&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,T,o.start,R,!0)}else y&&S-(f.appliedTimelineOffset||0)>Zs&&(o.gap=!0);o.setElementaryStreamInfo(u.type,S,T,b,R),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,y||E)}else if(y||E)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:m,endPTS:y,startDTS:E,endDTS:S}=p;l&&(l.elementaryStreams[_e.AUDIO]={startPTS:m,endPTS:y,startDTS:E,endDTS:S}),o.setElementaryStreamInfo(_e.AUDIO,m,y,E,S),this.bufferFragmentData(p,o,l,n)}if(f&&d!=null&&d.samples.length){const m={id:t,frag:o,details:f,samples:d.samples};i.trigger(v.FRAG_PARSING_METADATA,m)}if(f&&h){const m={id:t,frag:o,details:f,samples:h.samples};i.trigger(v.FRAG_PARSING_USERDATA,m)}}logMuxedErr(e){this.warn(`${Ne(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==U.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:n,video:a,audiovideo:o}=t;if(n){const c=e.audioCodec;let u=Ps(n.codec,c);if(u==="mp4a"&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&!Og()&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&Mg()&&n.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),c&&c!==u&&this.log(`Swapping manifest audio codec "${c}" for "${u}"`),n.levelCodec=u,n.id=te.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${u||""}/${c||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=te.MAIN;const c=a.codec;if((c==null?void 0:c.length)===4)switch(c){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||""}/${c}]${a.codec!==c?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(i),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const l=Object.keys(t);if(l.length){if(this.hls.trigger(v.BUFFER_CODECS,t),!this.hls)return;l.forEach(c=>{const h=t[c].initSegment;h!=null&&h.byteLength&&this.hls.trigger(v.BUFFER_APPENDING,{type:c,data:h,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.getBufferOutput();return this.getFwdBufferInfo(e,te.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e==null?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=U.IDLE}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(q(t)){const i=this.getLevelDetails(),s=this.currentFrag||(i?Ei(null,i.fragments,t):null);if(s){const n=s.programDateTime;if(n!==null){const a=n+(t-s.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Ku extends Hu{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const t=this.media;t!=null&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;const{seekOnAppend:i}=t,s=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=s,this.startPosition=e,this.state){case U.STOPPED:case U.ENDED:case U.ERROR:this.state=U.IDLE}this.state===U.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[s,t]):this.nextOp=[s,t],this.hls.off(v.BUFFERED_TO_END,this.onBufferedToEnd);const n=this.media;i&&n&&this.seekTo(s)&&(this.currentOp=[s,t],this.nextOp=void 0,this.flushPipeline(s,!0))}seekTo(e){const t=this.media;if(t){var i;const s=(i=this.getLevelDetails())==null?void 0:i.edge,n=s!==void 0?s:t.duration;if(e>=n&&(e=n-.01),le.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,te.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;const i=this.cached;i.push(e),this.cachedSize+=t.buffer.byteLength;const s=this.hls.config.iframeCacheLimit;for(;this.cachedSize>s&&i.length>1;){const n=i.shift();if(n.data)this.cachedSize-=n.data.byteLength,n.data=void 0;else{this.cached=i.filter(a=>!!a.data),this.cachedSize=i.reduce((a,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){const t=e.frag,{part:i,payload:s}=e;this.cacheFragmentData&&!i&&s!=null&&s.byteLength&&!t.data&&Ne(t)&&this.cacheSet(t,new Uint8Array(s.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if((s===ke.NOT_LOADED||s===ke.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,i)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;const i=e.decryptdata;return(i==null?void 0:i.keyFormat)!=="identity"||!!i.key}replayCachedFragment(e){const t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;const i=e.stats=new _r;i.loading.start=i.loading.first=i.loading.end=self.performance.now(),i.loaded=i.total=t.byteLength,i.chunkCount=1,this.state=U.FRAG_LOADING;const s={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(s),this.hls.trigger(v.FRAG_LOADED,s),this._handleFragmentLoadComplete(s)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);const{currentOp:i,nextOp:s}=this;this.currentOp=this.nextOp=void 0,this.state=U.STOPPED,i!=null&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!s),this.seekTo(i[0])||this.log(`Could not seek to ${i[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?$s(le.getBuffered(this.media)):"none"}`)),s&&this.loadMediaAt.apply(this,s)}flushPipeline(e,t){if(t){const i=this.media;if(i){const s=le.bufferInfo(i,e,0),n=s.len?s.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,te.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(v.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(v.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,i){const s=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,i||s||void 0)}getMainFwdBufferInfo(){const e=this.playhead,t=this.getBufferedAt(e);if(t){const i=t.duration;return{len:i,start:e,end:e+i,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){const e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,te.MAIN);return!!(t!=null&&t.endList)}}class Dy extends Ku{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;const i=(t=this._img)==null?void 0:t.src;i&&self.URL.revokeObjectURL(i),this._img=e}loadMediaAt(e){if(!this.hls)return;const t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case U.STOPPED:case U.ENDED:case U.ERROR:this.state=U.IDLE}if(this.state===U.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===U.IDLE){const i=this.getBufferedAt(e);i&&(this.fragCurrent=i,this.updateImage(i,null))}}else{const i=this.fragCurrent;(!i||e>=i.start&&e<i.end)&&(this.queued=[t])}}updateImage(e,t,i){const s=e.data;s||this.fragmentTracker.removeFragment(e);const n=this._img;if(n&&s){const a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,n.onload=()=>{if(!this.hls)return;const u=this.hls.levels[e.level];u!=null&&u.fragmentError&&(u.fragmentError=0,e.stats.retry=0);const h=self.performance.now(),d=t?t.stats:e.stats;d.buffering.end=e.stats.buffering.end=h,this.hls.trigger(v.FRAG_BUFFERED,{frag:e,part:t,stats:d,id:e.type,chunkMeta:i})},n.onerror=()=>{this.handleError("Image decode error",e,t,i)};const l=n.src;l&&self.URL.revokeObjectURL(l);const c=new Blob([s],{type:"image/jpeg"});n.src=self.URL.createObjectURL(c)}else this.state=U.STOPPED,this.processQueued()}processQueued(){const e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,i,s){if(!this.hls)return;const n=new Error(e);this.hls.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,chunkMeta:s,frag:t,part:i,fatal:!1,error:n,err:n})}_bufferInitSegment(){}bufferFragmentData(e,t,i,s){super.bufferFragmentData(e,t,i,s,!0);const n=fe(new Uint8Array(e.data1),["mdat"]);if(n.length===0){this.handleError("Could not find I-Frame mdat",t,i,s);return}const a=t;this.cacheSet(a,n[0]),this.updateImage(a,i,s)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;const t=(e=this.fragPrevious)==null?void 0:e.start;if(t!==void 0){const i=this.getAppendedFrag(t);if(i&&!Fi(i,this.fragPlaying))return this.fragPlaying=i,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const wy=10,Cy="Image I-Frame player does not accept HTMLMediaElements",qu={seekOnAppend:!0};let tr,jn;class ky extends dt{constructor(e,t){super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,tr||(tr=Oy(t)),jn||(jn=Fy(tr)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(v.MANIFEST_LOADING,this.clearAsset,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(v.MANIFEST_LOADING,this.clearAsset,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var i;const s=(i=this.hls)==null?void 0:i.pathwayPriority;t.length&&s&&this.iframeInstances.forEach(n=>{n.pathwayPriority=s})}onInitPtsFound(e,{id:t,timestampOffsets:i}){t===te.MAIN&&(this.initPTS=i)}onFragBuffered(e,t){var i;const s=this.hls;s&&s.hasEnoughToStart&&(((i=s.mainForwardBufferInfo)==null?void 0:i.len)||0)>wy&&this.iframeInstances.forEach(n=>{if(!n.loadingEnabled){var a;n.startLoad(((a=this.hls)==null||(a=a.media)==null?void 0:a.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(tr,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;const i=(t=this.hls)==null?void 0:t.iframeVariants.filter(s=>s.imageCodec);return this.createInstance(jn,i,e,"image-")}createInstance(e,t,i,s){const{hls:n}=this;if(!n)return null;const{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:c,loadLevel:u,bandwidthEstimate:h,sessionId:d}=n,{stats:g,variableList:f}=this;if(!(t!=null&&t.length)||!g||!a)return null;const p=`${s||""}iframe-player-${this.instanceCounter++}`,m=n.levels,y=c||m[u],E=Il(y,o.videoPreference),S=(y==null?void 0:y.pathwayId)||".",T=re(re({},o),{},{loggerId:p,primarySessionId:d,videoPreference:E,abrEwmaDefaultEstimate:h,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},i),b=new e(T,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(R=>!R.url),this.iframeInstances.push(b),b.trigger(v.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:S},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:g,networkDetails:null,url:a,variableList:f}),b}}function Oy(r){return class extends r{constructor(t,i,s,n){t.streamController||(t.streamController=Ku),super(t),this._url=i,this.streamController.setInitPts(s),this.streamController.initDetails=n}loadSource(){}loadMediaAt(t,i=qu){if(t<0)return;const s=re(re({},qu),i);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,s)}}}function Fy(r){return class extends r{constructor(t,i,s,n){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=Dy),t.capLevelController=void 0,t.bufferController=void 0,super(t,i,s,n)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(Cy)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}const zt=.025;let ir=(function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r})({});function My(r,e,t){return`${r.identifier}-${t+1}-${ss(e)}`}class Ny{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;const 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(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Wu(t,e)?sr(e,t):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=sr(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=q(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Wu(t,e)?sr(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<zt))}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(){const e=this.playoutLimit;let 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"?ir.Range:ir.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 By(this)}}function sr(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<zt)?e.start:e.start+e.duration}function Wu(r,e){return e>r.start-zt&&e<r.start+r.duration+zt}function ju(r,e,t){const i=new self.URL(r,t);return i.protocol!=="data:"&&Wt(i,"_HLS_primary_id",e),i}function Yn(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function By(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function Ri(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Uy{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(v.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new e(t);this.interstitial=i,this.assetItem=s;const a=()=>{this.hasDetails=!0};n.once(v.LEVEL_LOADED,a),n.once(v.AUDIO_TRACK_LOADED,a),n.once(v.SUBTITLE_TRACK_LOADED,a),n.on(v.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(v.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,n.trigger(v.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const 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=ju(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var i;if(!this.appendInPlace)return!1;if((i=this.hls)!=null&&i.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset+(t||0),a=le.bufferInfo(e,n,.02);return this.getAssetTime(a.end)>=s-.02}reachedPlayout(e){const 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(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=le.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){const 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){const t=this.timelineOffset;if(e!==t){const 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){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const 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(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const 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: ${Ri(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const zn=.033;class $y extends dt{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(){const 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);const 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){const i=this.items;if(i)for(let s=0;s<i.length;s++){let n=i[s];t&&t!=="primary"&&(n=n[t]);const a=n.start,o=i[s].event,l=o!=null&&o.cue.pre?o.duration:n.end;if(e===a||e>a&&e<l)return s}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){const n=i[s].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return s}return-1}findEventIndex(e){const 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){const i=e.assetList,s=i.length;if(s>1)for(let n=0;n<s;n++){const a=i[n];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===s-1))return n}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const i=t.assetList,s=i[i.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t,i=0){const s=e.main.details,{dateRanges:n}=s,a=this.events,o=this.parseDateRanges(n,{url:s.url},t),l=Object.keys(n),c=a?a.filter(u=>l.indexOf(u.identifier)===-1):[];o.length&&o.sort((u,h)=>{const d=u.cue.pre,g=u.cue.post,f=h.cue.pre,p=h.cue.post;if(d&&!f)return-1;if(f&&!d||g&&!p)return 1;if(p&&!g)return-1;if(!d&&!f&&!g&&!p){const m=u.startTime,y=h.startTime;if(m!==y)return m-y}return u.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=o,c.forEach(u=>{this.removeEvent(u)}),this.updateSchedule(e,c,i)}updateSchedule(e,t=[],i=0,s=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const a=this.items,o=this.parseSchedule(n,e,i);(s||t.length||(a==null?void 0:a.length)!==o.length||o.some((c,u)=>Math.abs(c.playout.start-a[u].playout.start)>.005||Math.abs(c.playout.end-a[u].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,i){const s=[],n=Object.keys(e);for(let a=0;a<n.length;a++){const o=n[a],l=e[o];if(l.isInterstitial){let c=this.eventMap[o];c?c.setDateRange(l):(c=new Ny(l,t),this.eventMap[o]=c,i===!1&&(c.appendInPlace=i)),s.push(c)}}return s}parseSchedule(e,t,i=0){const s=[],n=t.main.details,a=n.live?1/0:n.edge;let o=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,u=0;if(e.forEach((h,d)=>{const g=h.cue.pre,f=h.cue.post,p=e[d-1]||null,m=h.appendInPlace,y=f?a:h.startOffset,E=h.duration,S=h.timelineOccupancy===ir.Range?E:0,T=g&&n.live?i+(h.resumeOffset||0):0,b=T||h.resumptionOffset,R=(p==null?void 0:p.startTime)===y,I=y+h.cumulativeDuration;let L=m?I+E:y+b;if(g||!f&&y<=0){const x=u;u+=S,h.timelineStart=I;const _=o;o+=E,s.push({event:h,start:I,end:L,playout:{start:_,end:o},integrated:{start:x,end:u}})}else if(y<=a){if(!R){const w=y-c;if(w>zn){const G=c,B=u;u+=w;const K=o;o+=w;const O={previousEvent:e[d-1]||null,nextEvent:h,start:G,end:G+w,playout:{start:K,end:o},integrated:{start:B,end:u}};s.push(O)}else w>0&&p&&(p.cumulativeDuration+=w,s[s.length-1].end=y)}f&&(L=I),h.timelineStart=I;const x=u;u+=S;const _=o;o+=E,s.push({event:h,start:I,end:L,playout:{start:_,end:o},integrated:{start:x,end:u}})}else return;const A=T||h.resumeTime;f||A>a?c=a:!g&&L&&h.appendInPlaceStarted&&A-L>zn?c=L:c=A}),c<a){var l;const h=c,d=u,g=a-c;u+=g;const f=o;o+=g,s.push({previousEvent:((l=s[s.length-1])==null?void 0:l.event)||null,nextEvent:null,start:c,end:h+g,playout:{start:f,end:o},integrated:{start:d,end:u}})}this.setDurations(a,o,u)}else s.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return s}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,s=i.live?1/0:i.edge;let n=0,a=-1;e.forEach((o,l)=>{const c=o.cue.pre,u=o.cue.post,h=c?0:u?s:o.startTime;this.updateAssetDurations(o),a===h?o.cumulativeDuration=n:(n=0,a=h),!u&&o.snapOptions.in&&(o.resumeAnchor=Ei(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<zn&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const g=q(o.resumeOffset)?o.resumeOffset:o.duration;n+=g})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(i-s)>zt?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),!1;const c=Ei(null,o.fragments,i);if(!c)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=a==="audio"?.175:0;return Math.abs(c.start-i)<zt+u||Math.abs(c.end-i)<zt+u?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,s=!1,n=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,s||(s=o.duration===null),n||(n=!!o.error);const c=o.error?0:o.duration||0;i+=c}s&&!n?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function pt(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class Gy{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=ju(i,this.hls.sessionId,e.baseUrl)}catch(d){const g=this.assignAssetListError(e,D.ASSET_LIST_LOAD_ERROR,d,i);this.hls.trigger(v.ERROR,g);return}t&&s.protocol!=="data:"&&Wt(s,"_HLS_start_offset",""+t);const n=this.hls.config,a=n.loader,o=new a(n),l={type:pe.INTERSTITIAL_ASSET_LIST,responseType:"json",url:s.href},c=n.interstitialAssetListLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,g,f,p)=>{const m=d.data,y=m==null?void 0:m.ASSETS;if(!Array.isArray(y)){const E=this.assignAssetListError(e,D.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,g,p);this.hls.trigger(v.ERROR,E);return}e.assetListResponse=m,this.hls.trigger(v.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:p})},onError:(d,g,f,p)=>{const m=this.assignAssetListError(e,D.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${g.url})`),g.url,p,f);this.hls.trigger(v.ERROR,m)},onTimeout:(d,g,f)=>{const p=this.assignAssetListError(e,D.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,d,f);this.hls.trigger(v.ERROR,p)}};return o.load(l,u,h),this.hls.trigger(v.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,s,n,a){return e.error=i,{type:se.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:a,stats:n}}}function Yu(r){var e;r==null||(e=r.play())==null||e.catch(()=>{})}function ri(r,e){return`[${r}] Advancing timeline position to ${e}`}class Vy extends dt{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;const a=s<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=i,this.bufferedPos=i;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(!0),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;const g=this.findItemIndex(o);let f=this.schedule.findItemIndexAtTime(i);if(f===-1&&(f=g+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${g} to ${f})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&f>g){const p=this.schedule.findJumpRestrictedIndex(g+1,f);if(p>g){this.setSchedulePosition(p);return}}this.setSchedulePosition(f);return}const c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(o)){const g=o.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,g))}return}const u=c.timelineStart,h=c.duration||0;if(a&&i<u||i>=u+h){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,c)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const s=this.playingItem;if(!s||this.playingLastItem)return;if(i>=s.end){this.timelinePos=s.end;const o=this.findItemIndex(s);this.setSchedulePosition(o+1)}const n=this.playingAsset;if(!n)return;const a=n.timelineStart+(n.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,n)},this.onScheduleUpdate=(i,s)=>{const n=this.schedule;if(!n)return;const a=this.playingItem,o=n.events||[],l=n.items||[],c=n.durations,u=i.map(p=>p.identifier),h=!!(o.length||u.length);(h||s)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
41
- Schedule: ${l.map(p=>pt(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let d=null,g=null;a&&(d=this.updateItem(a,this.timelinePos),this.itemsMatch(a,d)?this.playingItem=d:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const f=this.bufferingItem;if(f&&(g=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,g)?this.bufferingItem=g:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),i.forEach(p=>{p.assetList.forEach(m=>{this.clearAssetPlayer(m.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const m=p.assetItem.timelineStart,y=p.timelineOffset-m;if(y)try{p.timelineOffset=m}catch(E){Math.abs(y)>zt&&this.warn(`${E} ("${p.assetId}" ${p.timelineOffset}->${m})`)}}}),h||s){if(this.hls.trigger(v.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:c,removedIds:u}),this.isInterstitial(a)&&u.indexOf(a.event.identifier)>-1){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(d,a),f&&g!==d&&this.trimInPlace(g,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Gy(e),this.schedule=new $y(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(v.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(v.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(v.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(v.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(v.BUFFER_APPENDED,this.onBufferAppended,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(v.MEDIA_ENDED,this.onMediaEnded,this),e.on(v.ERROR,this.onError,this),e.on(v.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(v.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(v.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(v.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(v.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(v.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.BUFFER_APPENDED,this.onBufferAppended,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(v.MEDIA_ENDED,this.onMediaEnded,this),e.off(v.ERROR,this.onError,this),e.off(v.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const 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){const i=this.media=t.media;xe(i,"seeking",this.onSeeking),xe(i,"timeupdate",this.onTimeupdate),xe(i,"play",this.onPlay),xe(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!s){this.clearScheduleState();const 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){const i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const 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;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=h=>h&&e.getAssetPlayer(h.identifier),s=(h,d,g,f,p)=>{if(h){let m=h[d].start;const y=h.event;if(y){if(d==="playout"||y.timelineOccupancy!==ir.Point){const E=i(g);(E==null?void 0:E.interstitial)===y&&(m+=E.assetItem.startOffset+E[p])}}else{const E=f==="bufferedPos"?a():e[f];m+=E-h.start}return m}return 0},n=(h,d)=>{var g;if(h!==0&&d!=="primary"&&(g=e.schedule)!=null&&g.length){var f;const p=e.schedule.findItemIndexAtTime(h),m=(f=e.schedule.items)==null?void 0:f[p];if(m){const y=m[d].start-m.start;return h+y}}return h},a=()=>{const h=e.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var d,g;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[h])||0},l=(h,d)=>{var g,f;const p=e.effectivePlayingItem;if(p!=null&&(g=p.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${d}"`);const m=e.effectivePlayingItem,y=e.schedule.findItemIndexAtTime(h,d),E=(f=e.schedule.items)==null?void 0:f[y],S=e.getBufferingPlayer(),T=S==null?void 0:S.interstitial,b=T==null?void 0:T.appendInPlace,R=m&&e.itemsMatch(m,E);if(m&&(b||R)){const I=i(e.playingAsset),L=(I==null?void 0:I.media)||e.primaryMedia;if(L){const A=d==="primary"?L.currentTime:s(m,d,e.playingAsset,"timelinePos","currentTime"),x=h-A,_=(b?A:L.currentTime)+x;if(_>=0&&(!I||b||_<=I.duration)){L.currentTime=_;return}}}if(E){let I=h;if(d!=="primary"){const A=E[d].start,x=h-A;I=E.start+x}const L=!e.isInterstitial(E);if((!e.isInterstitial(m)||m.event.appendInPlace)&&(L||E.event.appendInPlace)){const A=e.media||(b?S==null?void 0:S.media:null);A&&(A.currentTime=I)}else if(m){const A=e.findItemIndex(m);if(y>A){const _=e.schedule.findJumpRestrictedIndex(A+1,y);if(_>A){e.setSchedulePosition(_);return}}let x=0;if(L)e.timelinePos=I,e.checkBuffer();else{const _=E.event.assetList,w=h-(E[d]||E).start;for(let G=_.length;G--;){const B=_[G];if(B.duration&&w>=B.startOffset&&w<B.startOffset+B.duration){x=G;break}}}e.setSchedulePosition(y,x)}}},c=()=>{const h=e.effectivePlayingItem;if(e.isInterstitial(h))return h;const d=t();return e.isInterstitial(d)?d:null},u={get bufferedEnd(){const h=t(),d=e.bufferingItem;if(d&&d===h){var g;return s(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const h=c(),d=e.effectivePlayingItem;return d&&d===h?s(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(h){const d=c(),g=e.effectivePlayingItem;g&&g===d&&l(h+g.playout.start,"playout")},get duration(){const h=c();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const d=(h=c())==null?void 0:h.event.assetList;return d?d.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var h;const d=(h=c())==null?void 0:h.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};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 c()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const h=t();return e.findItemIndex(h)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const h=e.effectivePlayingItem;return e.findItemIndex(h)},primary:{get bufferedEnd(){return a()},get currentTime(){const h=e.timelinePos;return h>0?h:0},set currentTime(h){l(h,"primary")},get duration(){return o("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){l(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){return n(e.seekableStart,"integrated")}},skip:()=>{const h=e.effectivePlayingItem,d=h==null?void 0:h.event;if(d&&!d.restrictions.skip){const g=e.findItemIndex(h);if(d.appendInPlace){const f=h.playout.start+h.event.duration;l(f+.001,"playout")}else e.advanceAfterAssetEnded(d,g,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const 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;const 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);const n=(t=s)==null?void 0:t.currentTime;if(!(n===void 0||!q(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){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const 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}const n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Pe(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;const a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,c=(i=this.detachedData)==null?void 0:i.mediaSource;let u;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),u="Primary";else{const f=this.getBufferingPlayer();f?(n=f.transferMedia(),this.detachedData=n,u=`${f}`):c?u="detached MediaSource":u="detached media"}if(!n){if(c)n=this.detachedData,this.log(`using detachedData: MediaSource ${Pe(n)}`);else if(!this.detachedData||a.media===t){const f=this.playerQueue;f.length>1&&f.forEach(p=>{if(o&&p.interstitial.appendInPlace!==l){const m=p.interstitial;this.clearInterstitial(p.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}}}const h=n&&"mediaSource"in n&&((s=n.mediaSource)==null?void 0:s.readyState)!=="closed";if(this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`),!h&&!o){e.attachMedia(t);return}const d=h&&n?re({},n):{media:t},g=this.schedule;if(g&&o){const f=e.assetId===g.assetIdAtEnd;d.overrides={duration:g.duration,endOfStream:f||e.appendInPlace===!1}}if(!h&&l){const f=e,p=f.assetItem.timelineStart;if(p){const m=f.hls,y=Math.max(this.timelinePos-p,Number.EPSILON);m.startPosition!==y&&(this.log(`Set ${f} startPosition: ${y}`),m.config.startPosition=y,m.loadingEnabled&&m.startLoad(y))}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events,i=this.hls;if(!t||this.playbackDisabled||!this.media||!i)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,n=this.effectivePlayingItem;if(s===-1){if(!i.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}const a=i.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(ri("checkStart (preroll)",a));const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(ri("checkStart",a));const o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else i.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(ri("checkStart (playing item)",n.start));const a=e.findItemIndex(n);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){const i=e.event,s=i.findAssetIndex(t),n=Yn(i,s);if(!i.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;const o=this.getNextItemIndex(e,!0),l=(a=this.schedule.items)==null?void 0:a[o];l&&this.bufferedToItem(l)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!q(e.resumeOffset)&&this.hls){const i=this.getLiveStartPos();if(t){const s=this.getBufferingPlayer(),n=s!=null&&s.interstitial.cue.pre?s.remaining:0;return i+n}return i}}getNextItemIndex(e,t){if(this.schedule){const i=this.livePrerollResumption(e.event,t);if(i!==void 0)return this.log(`find next item index @${i}`),this.schedule.findItemIndexAtTime(i)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,i){const s=Yn(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const n=this.schedule.items;if(n){const a=n[t],o=a.event?this.getNextItemIndex(a):t+1,l=n.length;if(o>=l){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(ri("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&!n[o].event&&this.hls.startLoad(c+.01),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){const n=e.assetList[s];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const s=t.parentIdentifier,n=i.getEvent(s);if(n){const a=i.findEventIndex(s),o=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;if(!s||this.playbackDisabled)return;const n=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&pt(n)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const h=a.event,d=this.playingAsset,g=d==null?void 0:d.identifier,f=g?this.getAssetPlayer(g):null;if(f&&g&&(!this.eventItemsMatch(a,n)||t!==void 0&&g!==h.assetList[t].identifier)){var l;const p=h.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${h.assetList.length} ${Ri(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(v.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:p,event:h,schedule:s.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(g,n),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${pt(a)}`),h.hasPlayed=!0,this.hls.trigger(v.INTERSTITIAL_ENDED,{event:h,schedule:s.slice(0),scheduleIndex:e}),h.cue.once&&this.hls)){var c;this.updateSchedule();const p=(c=this.schedule)==null?void 0:c.items;if(n&&p){const m=this.findItemIndex(n),y=this.livePrerollResumption(h);if(y!==void 0){let E=y;const S=this.getNextItemIndex(a);if(!this.isInterstitial(s[S])){var u;const T=(u=this.primaryDetails)==null?void 0:u.fragments;if(h.snapOptions.in&&T){const b=Ei(null,T,y);b&&(E=Math.min(Math.max(s[S].start,sr(E,b)),s[S].end))}}if(this.log(ri("live join (preroll)",E)),this.timelinePos=E,S!==m&&(S||S===0)){this.advanceSchedule(S,p,void 0,a,o);return}}this.advanceSchedule(m,p,t,a,o)}return}}this.advanceSchedule(e,s,t,a,o)}advanceSchedule(e,t,i,s,n){const a=this.schedule;if(!a)return;const o=t[e]||null,l=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(u=>{const h=u.interstitial,d=a.findEventIndex(h.identifier);(d<e||d>e+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(i===void 0){i=u.cue.pre?0:a.findAssetIndex(u,this.timelinePos);const f=Yn(u,i-1);if(u.isAssetPastPlayoutLimit(f)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,i);return}i=f}const h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let d=this.preloadAssets(u,i);if(this.eventItemsMatch(o,h||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${pt(o)} ${u.appendInPlace?"append in place":""}`),u.hasPlayed=!1,this.hls.trigger(v.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const g=u.assetList[i];if(!g){this.advanceAfterAssetEnded(u,e,i||0);return}if(d||(d=this.getAssetPlayer(g.identifier)),d===null||d.destroyed){const f=u.assetList.length;this.warn(`asset ${i+1}/${f} player destroyed ${u}`),d=this.createAssetPlayer(u,g,i),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(d,i,t,e,l),this.shouldPlay&&Yu(d.media)}else o?(this.resumePrimary(o,e,s),this.shouldPlay&&Yu(this.hls.media)):n&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var s,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${pt(e)}`);let a=this.timelinePos;if((s=this.detachedData)!=null&&s.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(ri("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!i)return;const o=(n=this.schedule)==null?void 0:n.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${pt(e)}`),this.hls.trigger(v.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&((e=this.primaryDetails)==null?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,i){const s=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;const n=this.endedItem||this.playingItem,a=n!=null&&n.event?this.livePrerollResumption(n.event,i):void 0;if(a!==void 0)return a;const o=this.primaryDetails;if(o){const{fragmentStart:l,edge:c}=o;if(s<l||s>c&&!i){const u=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${s} [${l}-${c}]) snapping to liveSync ${u}`),u||l}}}return this.log(`primary resumption itemStart: ${s}`),s}getLiveStartPos(){var e;const t=this.hls.startPosition,i=this.hls.liveSyncPosition||0,s=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||i&&i-t<s?i||0:t}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:le.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;const s=this.primaryMedia;if(!s)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(ri("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){const i=this.hls,{loadingEnabled:s,bufferingEnabled:n,startPosition:a}=i,o=i.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${s} bufferingEnabled: ${n}`),!t&&o||!s||Math.abs(a-e)>.1){const l=this.primaryDetails;if(l!=null&&l.live&&e+.5>=l.edge){const c=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${c?pt(c):null}`),i.pauseBuffering(),this.bufferPastEdge=!0;return}i.startLoad(e,t)}else n||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(v.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(v.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const s=re(re({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s;const n=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace,n===-1?0:n),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){const o=this.primaryDetails,l=this.bufferedPos;if(o!=null&&o.live&&l+.5<o.edge){this.bufferPastEdge=!1;const c=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${c?pt(c):null}`),(c==null?void 0:c.end)===1/0){const h=this.playingItem,d=this.isInterstitial(h)&&h.event.appendInPlace;this.hls.startLoad(Math.max(l,c.start),d)}else{const h=this.getBufferingPlayer();h&&h.bufferedInPlaceToEnd(this.primaryMedia,h.currentTime)&&h.hls&&h.hls.trigger(v.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=re(re({},this.altSelection),{},{audio:i});return}const n=re(re({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=re(re({},this.altSelection),{},{subtitles:i});return}const n=re(re({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(e,t){const i=Al(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=Al(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const s=t[i];if(s.cue.post){const n=this.getEventItem(s.identifier);n&&this.eventItemsMatch(n,this.bufferingItem)&&this.bufferedToItem(n,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;if(e&&s){const 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)});const i=e.end+.25,s=le.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${pt(e)} (was ${pt(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;const i=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(i)&&i.event.identifier===e)return i}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,i;const s=this.mediaSelection;if(!s)return;const n=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(i=this.schedule)==null||i.updateSchedule(s,[],n,e)}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const s=le.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){const 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}const a=this.playingItem,o=this.findItemIndex(a);let l=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;const u=this.findItemIndex(n),h=Math.min(u+1,t.length-1),d=t[h];if((l===-1&&n&&e>=n.end||(c=d.event)!=null&&c.appendInPlace&&e+.01>=d.start)&&(l=h),this.isInterstitial(n)){const g=n.event;if(h-o>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,l>u&&l>o)this.bufferedToItem(d);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&d.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else i&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(s=>{const n=this.getAssetPlayer(s.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:s,events:n}=i;if(!s||!n)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${pt(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const c=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,h)=>{const d=this.getAssetPlayer(u.identifier);d&&(h===c&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(c=>c.pauseBuffering());this.hls.trigger(v.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){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const s=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(s,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(n,e,!0):this.startLoadingPrimaryAt(n);else{const o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(n,l)}}}}bufferedToEvent(e,t){const i=e.event,s=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(s||!n){const a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,n=s===0&&!e.assetListLoader,a=e.cue.once;if(n){const l=e.timelineStart,c=this.playingItem,u=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(c)&&(c==null||(o=c.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let h,d=0;if((!u||u.interstitial.cue.pre)&&this.primaryLive&&(d=this.getLiveStartPos(),u&&(d+=u.remaining)),d&&!(e.cue.pre||e.cue.post)){const f=d-l;f>0&&(h=Math.round(f*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${d?` live-start: ${d} start-offset: ${h} (timeline-start: ${l})`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);const g=this.assetListLoader.loadAssetList(e,h);g&&(e.assetListLoader=g)}else if(!a&&s){for(let c=t;c<s;c++){const u=e.assetList[c],h=this.getAssetPlayerQueueIndex(u.identifier);(h===-1||this.playerQueue[h].destroyed)&&!u.error&&this.createAssetPlayer(e,u,c)}const l=e.assetList[t];if(l){const c=this.getAssetPlayer(l.identifier);return c&&c.loadSource(),c}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;const i=this.primaryDetails;if(i&&e>=i.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{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){const o={parentIdentifier:e.identifier,identifier:My(e,a,t),duration:n,startOffset:i,timelineStart:s,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){const s=this.hls,n=s.userConfig,a=s.loadLevelObj||s.levels[s.currentLevel],o=Il(a,n.videoPreference),l=s.audioTracks[s.audioTrack],c=s.subtitleTracks[s.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const T=this.timelinePos-t.timelineStart;if(T>=0){const b=t.duration;b&&T<b&&(u=T)}}const h=t.identifier,d=re(re({},n),{},{maxMaxBufferLength:Math.min(15,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||n.audioPreference,subtitlePreference:c||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const g=d.cmcd;g!=null&&g.sessionId&&g.contentId&&(d.cmcd=Re({},g,{contentId:ss(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const f=new Uy(this.HlsPlayerClass,d,e,t);this.playerQueue.push(f),e.assetList[i]=t;let p=!0;const m=T=>{if(T.live){const I=new Error(`Interstitials MUST be VOD assets ${e}`),L={fatal:!0,type:se.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},A=this.findEventIndex(e.identifier);this.handleAssetItemError(L,e,A,i,I.message);return}const b=T.edge-T.fragmentStart,R=t.duration;(p||R===null||b>R)&&(p=!1,this.log(`Interstitial asset "${h}" duration change ${R} > ${b}`),t.duration=b,this.updateSchedule())};f.on(v.LEVEL_UPDATED,(T,{details:b})=>m(b)),f.on(v.LEVEL_PTS_UPDATED,(T,{details:b})=>m(b)),f.on(v.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const y=(T,b)=>{const R=this.getAssetPlayer(h);if(R&&b.tracks){R.off(v.BUFFER_CODECS,y),R.tracks=b.tracks;const I=this.primaryMedia;this.bufferingAsset===R.assetItem&&I&&!R.media&&this.bufferAssetPlayer(R,I)}};f.on(v.BUFFER_CODECS,y);const E=()=>{const T=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;const b=this.getEventItem(e.identifier);b&&this.advanceAssetBuffering(b,T.assetItem)};f.on(v.BUFFERED_TO_END,E);const S=T=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const R=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,R,T)};return f.once(v.MEDIA_ENDED,S(i)),f.once(v.PLAYOUT_LIMIT_REACHED,S(1/0)),f.on(v.ERROR,(T,b)=>{if(!this.schedule)return;const R=this.getAssetPlayer(h);if(b.details===D.BUFFER_STALLED_ERROR){if(R!=null&&R.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(b.details===D.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(b,e,this.findEventIndex(e.identifier),i,`Asset player error ${b.error} ${e}`)}),f.on(v.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const b=new Error(`Asset player destroyed unexpectedly ${h}`),R={fatal:!0,type:se.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:b};this.handleAssetItemError(R,e,this.findEventIndex(e.identifier),i,b.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ri(t)}`),this.hls.trigger(v.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const s=this.playerQueue[i];this.log(`clear ${s} toSegment: ${t&&pt(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){const{interstitial:a,assetItem:o,assetId:l}=e,c=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(u==null?void 0:u.identifier)!==l&&(u&&(this.clearAssetPlayer(u.identifier,i[s]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${Ri(o)}`),this.hls.trigger(v.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var i;if(!this.schedule)return;const{interstitial:s,assetItem:n}=e,a=this.getEventItem(s.identifier);if(!a)return;if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=n,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(a,n);return}const o=this.getBufferingPlayer();if(o===e)return;const l=s.appendInPlace;if(l&&(o==null?void 0:o.interstitial.appendInPlace)===!1)return;const c=(o==null?void 0:o.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(l&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Go(c,e.tracks)){const u=new Error(`Asset ${Ri(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),h={fatal:!0,type:se.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},d=s.findAssetIndex(n);this.handleAssetItemError(h,s,this.findEventIndex(s.identifier),d,u.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const s=i.currentTime,n=t.findAssetIndex(e,s),a=e.assetList[n];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||s-a.timelineStart,c=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${o} ${e} (media.currentTime: ${s})`),l&&(c/i.playbackRate<.5||o.bufferedInPlaceToEnd(i,o.currentTime))&&o.hls){const u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}advanceInPlace(e){const t=this.primaryMedia;if(t&&t.currentTime<e){const i=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(i),t.currentTime=e):this.log(`Cannot ${i}`)}}handleAssetItemError(e,t,i,s,n){if(e.details===D.BUFFER_STALLED_ERROR)return;const a=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Ri(a)} ${e.error}`),!this.schedule)return;const o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[l]||null,u=this.schedule.items,h=Re({},e,{fatal:!1,errorAction:Wi(!0),asset:a,assetListIndex:s,event:t,schedule:u,scheduleIndex:i,player:c});if(this.hls.trigger(v.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;const d=this.playingAsset,g=this.bufferingAsset,f=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=f),!t.assetList.some(p=>!p.error))t.error=f;else for(let p=s;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):(d==null?void 0:d.identifier)===o?this.advanceAfterAssetEnded(t,i,s):(g==null?void 0:g.identifier)===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem,s=this.playingItem,n=this.seekableStart,a=this.hls.startPosition;let o=this.timelinePos;if(this.isInterstitial(i)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${pt(i)} startPosition: ${a} seekableStart: ${n} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,n);const c=this.updateItem(i,o);this.itemsMatch(i,c)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||!this.isInterstitial(s))return;const l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var i,s;const n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;const l=n.timelineStart,c=n.duration;let u=0;o.forEach((f,p)=>{const m=parseFloat(f.DURATION);this.createAsset(n,p,u,l+u,m,f.URI),u+=m}),n.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${c}) ${n}`);const h=this.waitingItem,d=(h==null?void 0:h.event.identifier)===a;this.updateSchedule();const g=(s=this.bufferingItem)==null?void 0:s.event;if(d){const f=this.findEventIndex(a),p=this.getEventItem(a);if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==f){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(p)}this.setSchedulePosition(f)}else if((g==null?void 0:g.identifier)===a){const f=n.assetList[0];if(f){const p=this.getAssetPlayer(f.identifier);if(g.appendInPlace){const m=this.primaryMedia;p&&m&&this.bufferAssetPlayer(p,m)}else p&&p.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case D.ASSET_LIST_PARSING_ERROR:case D.ASSET_LIST_LOAD_ERROR:case D.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case D.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}const s=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${s==null?void 0:s.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}class Hy{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;const{media:i}=this,s=this.levelDetails;if(!i||!s||!this.hls)return;this.currentTime=i.currentTime;const n=this.hls.config,a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=n;if(!o||l===1||!s.live)return;const c=this.targetLatency;if(c===null)return;const u=a-c,h=Math.min(this.maxLatency,c+s.targetduration),d=u<h,g=Gs(n)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(d&&u>.05&&this.forwardBufferLength>1&&!g){const f=Math.min(2,Math.max(1,l)),p=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,m=Math.min(f,Math.max(1,p));this.changeMediaPlaybackRate(i,m)}else i.playbackRate!==1&&i.playbackRate!==0&&this.changeMediaPlaybackRate(i,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;const t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const i=this.levelDetails;return i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||!this.hls)return null;const t=this.hls.config,{holdBack:i,partHoldBack:s,targetduration:n}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,c=this.hls.userConfig;let u=l&&s||i;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||u===0)&&(u=a!==void 0?a:o*n);const h=n;return u+Math.min(this.stallCount*t.liveSyncOnStallIncrease,h)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,n=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null||!this.hls)return 0;const t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.ERROR,this.onError,this),e.on(v.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.ERROR,this.onError,this),e.off(v.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var i;const s=this.hls,n=this.media||t.event.appendInPlace&&(s==null||(i=s.interstitialsManager)==null?void 0:i.playerQueue.reduce((a,o)=>a||o.media,null));s&&n&&n.playbackRate>1&&n.playbackRate<=s.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)}onError(e,t){var i;t.details===D.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(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const zu=500;class Ky extends on{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",te.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(v.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(v.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=U.IDLE,this.setInterval(zu),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){const{frag:i,part:s,success:n}=t;if(!n)return;const a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o;const l=(s||i).start;for(let u=0;u<a.length;u++)if(l>=a[u].start&&l<=a[u].end){o=a[u];break}const c=l+(s||i).duration;if(o?o.end=c:(o={start:l,end:c},a.push(o)),!s||c>=i.end){const u=this.fragmentTracker.fragBuffered(i);s&&u&&(u.range.subs={time:[{startPTS:i.start,endPTS:c}],partial:!0}),Ne(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const n=s-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{if(a)for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,n,te.SUBTITLE)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===te.SUBTITLE&&(t.details===D.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==U.STOPPED&&(this.state=U.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&qc(this.levels,t)){this.levels=t.map(i=>new Ki(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new Ki(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,te.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const s=this.levels[this.currentTrackId];if(!(s!=null&&s.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==U.STOPPED&&this.setInterval(zu)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const c=this.mainDetails;let u=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;if(!c){this.startFragRequested=!1;return}if(l.details){var h;u=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}a.alignedSliding||(Us(c,a,this),u=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,c&&!this.startFragRequested&&this.setStartPosition(c,u),o===s&&(this.hls.trigger(v.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){const{frag:t,part:i,payload:s}=e;!i||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(s,t,i)}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e;this.fragContextChanged(t)||!(i!=null&&i.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(i,t,null)}shouldDecrypt(e){const t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&Ti(t.method))}decryptPayload(e,t,i){const s=t.decryptdata,n=performance.now();this.decrypter.decrypt(new Uint8Array(e),s.key.buffer,s.iv.buffer,Zr(s.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(v.FRAG_DECRYPTED,{frag:t,part:i,payload:a,stats:{tstart:n,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:i}),i||(this.warn(`${a.name}: ${a.message}`),this.state=U.IDLE)})}doTick(){if(this.state===U.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:i,levels:s}=this,n=s[i],a=n==null?void 0:n.details;if(!a||this.waitForLive(n)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}const{config:o}=this,l=this.playhead,c=le.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:u,len:h}=c,d=Math.max(this.hls.maxBufferLength+a.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(h>d||h&&!this.buffering)return;let g=this.getNextFragment(u,a);if(!g)return;if(Ne(g)){var t;const f=g.sn-a.startSN,p=a.fragments[f-1];g.cc===(p==null?void 0:p.cc)&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(p)===ke.NOT_LOADED&&(g=p)}this.loadFragment(g,n,u)}}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);(s===ke.NOT_LOADED||s===ke.PARTIAL)&&super.loadFragment(e,t,i)}get mediaBufferTimeRanges(){return new qy(this.tracksBuffered[this.currentTrackId]||[])}}class qy{constructor(e){this.buffered=void 0;const 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)}}}}const Wy={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},Xu=r=>String.fromCharCode(Wy[r]||r),Rt=15,Lt=42,jy={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Yy={17:2,18:4,21:6,22:8,23:10,19:13,20:15},zy={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Xy={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Qy=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Jy{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;be.log(`${this.time} [${e}] ${i}`)}}}const ni=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},Xn=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class Qu{constructor(){this.styles=Xn}get foreground(){return this.styles.foreground}set foreground(e){const t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){const t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=Xn}setStyles(e){const t=this.styles,i=Object.prototype.hasOwnProperty;this.styles={foreground:i.call(e,"foreground")?e.foreground:t.foreground,underline:i.call(e,"underline")?e.underline:t.underline,italics:i.call(e,"italics")?e.italics:t.italics,background:i.call(e,"background")?e.background:t.background,flash:i.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Zy{constructor(){this.uchar=" ",this.penState=new Qu}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}class ev{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Qu,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Lt;t++)this.chars.push(new Zy);this.logger=e}equals(e){const t=this.chars,i=e.chars;for(let s=0;s<Lt;s++){const n=t[s],a=i[s];if(n.uchar!==a.uchar)return!1;const o=n.penState.styles,l=a.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(e){for(let t=0;t<Lt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){const e=this.chars;for(let t=0;t<Lt;t++){const i=e[t];if(i.uchar!==" ")return!1;const s=i.penState.styles;if(s!==Xn&&(s.foreground!=="white"||s.underline||s.italics||s.background!=="black"||s.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=Lt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Lt-1)}moveCursor(e){const t=Math.min(this.pos+e,Lt);if(e>1)for(let i=this.pos+1;i<t;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Xu(e);if(this.pos>=Lt){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<Lt;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Lt;i++){const 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)}}class Qn{constructor(e){this.rows=[],this.currRow=Rt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Rt;t++)this.rows.push(new ev(e));this.logger=e}reset(){for(let e=0;e<Rt;e++)this.rows[e].clear();this.currRow=Rt-1}equals(e){let t=!0;for(let i=0;i<Rt;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<Rt;t++){const i=this.rows[t].chars,s=e.rows[t].chars;for(let n=0;n<Lt;n++){const a=i[n],o=s[n];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<Rt;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 = "+Pe(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<Rt;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[n+c])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Pe(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());const 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;const t=[];let i="",s=-1;for(let n=0;n<Rt;n++){const a=this.rows[n].getTextString();a&&(s=n+1,e?t.push("Row "+s+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
42
- `)),i}getTextAndFormat(){return this.rows}}class tv{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 Qn(i),this.nonDisplayedMemory=new Qn(i),this.lastOutputScreen=new Qn(i),this.currRollUpRow=this.displayedMemory.rows[Rt-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[Rt-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]);const 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"){const 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){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+Pe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const 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))}}class Ju{constructor(e,t,i){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=sv(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Jy,this.field=e,this.outputFilters=[null,t,i]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var i;this.outputFilters[e]=t,(i=this.channels[e])==null||i.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new tv(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const s=t[i]&127,n=t[i+1]&127;let a=!1,o=null;if(s===0&&n===0)continue;this.logger.log(3,()=>"["+ni([t[i],t[i+1]])+"] -> ("+ni([s,n])+")");const l=this.cmdHistory;if(s>=16&&s<=31){if(iv(s,n,l)){rr(null,null,l),this.logger.log(3,()=>"Repeated command ("+ni([s,n])+") is dropped");continue}rr(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 rr(null,null,l);if(!a&&(o=this.parseChars(s,n),o)){const u=this.currentChannel;u&&u>0?this.getChannel(u).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+ni([s,n])+" orig: "+ni([t[i],t[i+1]]))}}parseCmd(e,t){const 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;const n=e===20||e===21||e===23?1:2,a=this.getChannel(n);return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+ni([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const 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;const a=e<=23?1:2;return t>=64&&t<=95?i=a===1?jy[e]:zy[e]:i=a===1?Yy[e]:Xy[e],this.getChannel(a).setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0}interpretPAC(e,t){let i;const 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 '"+Xu(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 = "+ni(s).join(",")),s}parseBackgroundAttributes(e,t){const 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;const a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=Qy[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.getChannel(o).setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}rr(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function rr(r,e,t){t.a=r,t.b=e}function iv(r,e,t){return t.a===r&&t.b===e}function sv(){return{a:null,b:null}}class nr{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}}class rv{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Zu(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(v.BUFFER_APPENDED,this.onBufferAppended,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(v.BUFFER_APPENDED,this.onBufferAppended,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new nr(this,"textTrack1"),t=new nr(this,"textTrack2"),i=new nr(this,"textTrack3"),s=new nr(this,"textTrack4");this.cea608Parser1=new Ju(1,e,t),this.cea608Parser2=new Ju(3,i,s)}addCues(e,t,i,s,n){let a=!1;for(let l=n.length;l--;){const c=n[l],u=nv(c[0],c[1],t,i);if(u>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),a=!0,u/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){const l=this.cueCache[e];if(l){const c=this.Cues.newCue(null,t,i,s);c.length&&l.push.apply(l,c)}else{const c=this.captionsTracks[e].track;this.Cues.newCue(c,t,i,s)}}else{var o;const l=this.Cues.newCue(null,t,i,s),c=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(v.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:c})}}onInitPtsFound(e,{id:t,timestampOffsets:i}){const{unparsedVttFrags:s}=this;t===te.MAIN&&(this.initPTS=i),s.length&&(this.unparsedVttFrags=[],s.forEach(n=>{this.initPTS[n.frag.cc]?this.onFragLoaded(v.FRAG_LOADED,n):this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,cueCache:s,media:n}=this,{label:a,languageCode:o}=t[e];n&&(s[e]=[],i[e]=Vn(n,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const 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(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,!i){if(this.config.renderTextTracksNatively){const{captionsTracks:s,cueCache:n}=this;for(const a in s)s[a].remove(),delete n[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Zu(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[];if(i.length&&!this.config.renderTextTracksNatively&&!qc(this.tracks,i)){const s=i.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:s})}this.tracks=i}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===te.MAIN){var i,s;const{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,u=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&a&&(c!==o+1||c===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.level<this.tracks.length&&i.type===te.SUBTITLE){var n;if(s.byteLength||(n=i.initSegment)!=null&&(n=n.data)!=null&&n.byteLength){const a=i.decryptdata,o="stats"in t;if(a==null||!a.encrypted||o){const l=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),(l==null?void 0:l.textCodec)===Bn?this._parseIMSC1(t):this._parseVTTs(t)}}else{const a="part"in t?t.part:null;this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:a,error:new Error("Empty subtitle payload")})}}}_parseIMSC1(e){const{frag:t,payload:i}=e,s="part"in e?e.part:null,n=this.hls;Ou(i,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:s})},a=>{n.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),n.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:s,error:a})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,n="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:o}=this,l=a.length-1;if(!a[i.cc]&&l===-1){o.push(e);return}const c=this.hls,u=(t=i.initSegment)==null?void 0:t.data,h=u?Et(u,new Uint8Array(s)).buffer:s;fy(h,this.initPTS[i.cc],this.vttCCs,i.cc,(n&&!u?n:i).start,d=>{this._appendCues(d,i.level),c.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:n})},d=>{const g=d.message.startsWith("Missing initPTS");if(c.logger.log(`${g?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${i.sn} @${i.start}): ${d}`),g){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);c.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:n,error:d})})}_fallbackToIMSC1(e){const{frag:t,payload:i}=e,s=this.tracks[t.level];s.textCodec||Ou(i,this.initPTS[t.cc],()=>{s.textCodec=Bn,this._parseIMSC1(e)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){var s;const n=(s=this.tracks[t].trackNode)==null?void 0:s.track;if(!n||n.mode==="disabled")return;e.forEach(a=>Hn(n,a))}else{const n=this.tracks[t];if(!n)return;const a=n.default?"default":"subtitles"+t;i.trigger(v.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:n})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===te.SUBTITLE&&this.onFragLoaded(v.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(!(i.type===te.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<s.length;n++){const a=s[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(s[n].pts,o[0]),this.cea608Parser2.addData(s[n].pts,o[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var i;const{type:s,timeRanges:n}=t;if(s==="video"&&(i=n[s])!=null&&i.length){const{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var c;const u=(c=a[l])==null?void 0:c.track;if(u){const h=o[l];for(let d=0;d<h.length;d++)Hn(u,h[d])}delete o[l]})}}}onBufferFlushing(e,t){const{startOffset:i,endOffset:s,endOffsetSubtitles:n,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<s)){if(!a||a==="video"){const{captionsTracks:l,cueCache:c}=this;Object.keys(l).forEach(u=>Kn(l[u].track,i,s)),Object.keys(c).forEach(u=>{const h=c[u];for(let d=h.length;d--;){const g=h[d];g.startTime>=i&&g.endTime<=s&&h.splice(d,1)}})}this.config.renderTextTracksNatively&&i===0&&n!==void 0&&this.tracks.forEach(l=>{var c;const u=(c=l.trackNode)==null?void 0:c.track;u&&Kn(u,i,n)})}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let n=0;n<i;n++){const a=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&a)!==0){const u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}}function nv(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function Zu(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const av=/\s/,ov={newCue(r,e,t,i){const s=[];let n,a,o,l,c;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(n=i.rows[d],o=!0,l=0,c="",!n.isEmpty()){var h;for(let p=0;p<n.chars.length;p++)av.test(n.chars[p].uchar)&&o?l++:(c+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const g=Du(c.trim()),f=Nn(e,t,g);r!=null&&(h=r.cues)!=null&&h.getCueById(f)||(a=new u(e,t,g),a.id=f,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((d,g)=>d.line==="auto"||g.line==="auto"?0:d.line>8&&g.line>8?g.line-d.line:d.line-g.line),s.forEach(d=>Hn(r,d))),s}};class eh{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new _r}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Mi(e,t,!0))this.retry(e);else{var i;be.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Dr(e,i.retry),i.retry++,be.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}function lv(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const cv=/(\d+)-(\d+)\/(\d+)/;class th extends eh{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||fv}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:e,context:t,stats:i}=this;if(!e||!t)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;const s=uv(t,this.controller.signal),n=t.responseType==="arraybuffer",a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),e.timeout=o&&q(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(es(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var h;this.response=u;const d=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(d-i.loading.start)),!u.ok){const{status:f,statusText:p}=u;throw new gv(p||"fetch, bad network response",f,u)}i.loading.first=d,i.total=dv(u.headers)||i.total;const g=(h=this.callbacks)==null?void 0:h.onProgress;return g&&q(e.highWaterMark)?this.loadProgressively(u,i,t,e.highWaterMark,g):n?u.arrayBuffer():t.responseType==="json"?u.json():u.text()}).then(u=>{var h,d;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const f=u[a];f&&(i.loaded=i.total=f);const p={url:g.url,data:u,code:g.status},m=(h=this.callbacks)==null?void 0:h.onProgress;m&&!q(e.highWaterMark)&&m(i,t,u,g),(d=this.callbacks)==null||d.onSuccess(p,i,t,g)}).catch(u=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const h=u&&u.code||0,d=u?u.message:null,g=e.loadPolicy.errorRetry,f=i.retry,p={url:t.url,data:void 0,code:h};if(Mi(g,f,!1,p))this.retry(g);else{var m;be.error(`${h} while loading ${t.url}`),(m=this.callbacks)==null||m.onError({code:h,text:d},t,u?u.details:null,i)}})}getCacheAge(){let e=null;if(this.response){const 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){const a=new vc,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=c.value,h=u.length;return t.loaded+=h,h<s||a.dataLength?(a.push(u),a.dataLength>=s&&n(t,i,a.flush().buffer,e)):n(t,i,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function uv(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Re({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function hv(r){const e=cv.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function dv(r){const e=r.get("Content-Range");if(e){const i=hv(e);if(q(i))return i}const t=r.get("Content-Length");if(t)return parseInt(t)}function fv(r,e){return new self.Request(r.url,e)}class gv extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const pv=(r,e,t)=>Math.max(e,Math.min(r,t)),mv=/^age:\s*[\d.]+\s*$/im;class ih extends eh{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n.call(this,i,t.url,t)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n.call(this,i,t.url,t)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const 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&&q(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const 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;const c=t.status,u=t.responseType==="text"?t.responseText:null;if(c>=200&&c<300){const f=u??t.response;if(f!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=t.responseType==="arraybuffer"?f.byteLength:f.length;i.loaded=i.total=p,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const m=(a=this.callbacks)==null?void 0:a.onProgress;m&&m(i,e,f,t);const y={url:t.responseURL,data:f,code:c};e.rangeEnd&&p!==e.rangeEnd-e.rangeStart&&be.warn(`Payload length ${p} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(y,i,e,t);return}}const h=n.loadPolicy.errorRetry,d=i.retry,g={url:e.url,data:void 0,code:c};if(Mi(h,d,!1,g))this.retry(h);else{var l;be.error(`${c} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:c,text:t.statusText},e,t,i)}}}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&mv.test(this.loader.getAllResponseHeaders())){const 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}}const yv={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},vv=re(re({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:ih,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Yl,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:yv},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:Hu,abrController:rp,bufferController:Wm,capLevelController:Tn,errorController:lp,fpsController:ay,id3TrackController:Ry,gapController:xy,latencyController:Hy},Ev()),{},{subtitleStreamController:Ky,subtitleTrackController:by,timelineController:rv,audioStreamController:$m,audioTrackController:Gm,emeController:Ii,cmcdController:Z0,contentSteeringController:ty,iframeController:ky,interstitialsController:Vy});function Ev(){return{cueHandler:ov,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 Sv(r,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){const a=e.liveMaxUnchangedPlaylistRefresh,o=pv(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}const i=Jn(r),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,c=[];n.forEach(u=>{const h=`${a}Loading${u}`,d=e[h];if(d!==void 0&&l){c.push(h);const g=i[o].default;switch(e[o]={default:g},u){case"TimeOut":g.maxLoadTimeMs=d,g.maxTimeToFirstByteMs=d;break;case"MaxRetry":g.errorRetry.maxNumRetry=d,g.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":g.errorRetry.retryDelayMs=d,g.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=d,g.timeoutRetry.maxRetryDelayMs=d;break}}}),c.length&&t.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${o}": ${Pe(e[o])}`)}),re(re({},i),e)}function Jn(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(Jn):Object.keys(r).reduce((e,t)=>(e[t]=Jn(r[t]),e),{}):r}function Tv(r,e){const t=r.loader;t!==th&&t!==ih?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):lv()&&(r.loader=th,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}class bv extends vn{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],n={},a={};let o=!1,l=!1,c=!1,u=!1;t.levels.forEach(h=>{const d=h.attrs,g=nh(h,i),{audioCodec:f,videoCodec:p,imageCodec:m,width:y,height:E}=h;if(!g){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}o||(o=!!(y&&E)),l||(l=!!p),c||(c=!!f),u||(u=!!m);const{CODECS:S,"FRAME-RATE":T,"HDCP-LEVEL":b,"PATHWAY-ID":R,RESOLUTION:I,"VIDEO-RANGE":L}=d,x=`${`${R||"."}-`}${h.bitrate}-${I}-${T}-${S}-${L}-${b}`;if(n[x])if(n[x].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const _=a[x]+=1;h.attrs["PATHWAY-ID"]=new Array(_+1).join(".");const w=this.createLevel(h);n[x]=w,s.push(w)}else h.iframes||(n[x].addGroupId("audio",d.AUDIO),n[x].addGroupId("text",d.SUBTITLES));else{const _=this.createLevel(h);n[x]=_,a[x]=1,s.push(_)}}),this.filterAndSortMediaOptions(s,t,o,l,c,u)}createLevel(e){const t=new Ki(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!rh(i.videoCodec,this.hls.config.preferManagedMediaSource)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=pl(s,[])}return t}filterAndSortMediaOptions(e,t,i,s,n,a){var o;let l=[],c=[],u=e;const h=((o=t.stats)==null?void 0:o.parsing)||{},d=this.hls.config.preferManagedMediaSource;if((i||s)&&n&&(u=u.filter(({videoCodec:b,videoRange:R,width:I,height:L})=>(!!b||!!(I&&L))&&zg(R))),s&&a&&(u=u.filter(b=>!b.imageCodec)),u.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",R=b;t.levels.length&&(R=`one or more CODECS in variant not supported: ${Pe(t.levels.map(L=>L.attrs.CODECS).filter((L,A,x)=>x.indexOf(L)===A))}`,this.warn(R),b+=` (${R})`);const I=new Error(b);this.hls.trigger(v.ERROR,{type:se.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:I,reason:R})}}),h.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(b=>!b.audioCodec||sh(b.audioCodec,d)),ah(l)),t.subtitles&&(c=t.subtitles,ah(c));const g=u.slice(0);u.sort((b,R)=>{if(b.attrs["HDCP-LEVEL"]!==R.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(R.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&b.height!==R.height)return b.height-R.height;if(b.frameRate!==R.frameRate)return b.frameRate-R.frameRate;if(b.videoRange!==R.videoRange)return Ds.indexOf(b.videoRange)-Ds.indexOf(R.videoRange);if(b.videoCodec!==R.videoCodec){const I=hl(b.videoCodec),L=hl(R.videoCodec);if(I!==L)return L-I}if(b.uri===R.uri&&b.codecSet!==R.codecSet){const I=Ls(b.codecSet),L=Ls(R.codecSet);if(I!==L)return L-I}return b.averageBitrate!==R.averageBitrate?b.averageBitrate-R.averageBitrate:0});let f=g[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==g.length)){for(let b=0;b<g.length;b++)if(g[b].pathwayId===u[0].pathwayId){f=g[b];break}}this._levels=u;for(let b=0;b<u.length;b++)if(u[b]===f){var p;this._firstLevel=b;const R=f.bitrate,I=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${R}`),((p=this.hls.userConfig)==null?void 0:p.abrEwmaDefaultEstimate)===void 0){const L=Math.min(R,this.hls.config.abrEwmaDefaultEstimateMax);L>I&&I===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=L)}break}const m=t.iframeVariants.filter(b=>nh(b,d));this._iframeVariants=m;const y=n&&!s,E=this.hls.config,S=!!(E.audioStreamController&&E.audioTrackController),T={levels:u,audioTracks:l,subtitleTracks:c,iframeVariants:m,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:S&&!y&&l.some(b=>!!b.url)};h.end=performance.now(),this.hls.trigger(v.MANIFEST_PARSED,T)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(v.ERROR,{type:se.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const 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:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(v.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const u=this.switchParams(a.uri,s==null?void 0:s.details,c);this.loadPlaylist(u)}}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){const 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){const 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===pe.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===te.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;const 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;const{level:s,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(s,t,l)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${s}${(t==null?void 0: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(v.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){const t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){const s=this.hls.config.abrSwitchInterval;if(s>0){const n=performance.now(),a=n-this.lastABRSwitchTime,o=s*1e3;if(this.lastABRSwitchTime>-1&&a<o){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms < ${o}ms / ${s}s)`);return}this.lastABRSwitchTime=n,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms >= ${o}ms / ${s}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const 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));fc(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);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(v.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(v.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function sh(r,e){return Vi(r,"audio",e)}function rh(r,e){return Vi(r,"video",e)}function nh(r,e){let{audioCodec:t,videoCodec:i}=r;t&&(r.audioCodec=t=_s(t,e)||void 0),i&&(i=r.videoCodec=$g(i));const{unknownCodecs:s}=r;return!((s==null?void 0:s.length)||0||t&&!sh(t,e)||i&&!rh(i,e))}function ah(r){const e={};r.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class Av extends dt{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyLoaderInfo){const s=this.keyLoaderInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}destroy(){for(const e in this.keyLoaderInfo){const t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,i){return this.emeController?this.emeController.loadClear(e,t,i):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(i=>this.loadInternal(e,t,i)):this.loadInternal(e,t)}loadInternal(e,t,i){i&&e.setKeyFormat(i);const s=e.decryptdata;if(!s){const a=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Xt(e,D.KEY_LOAD_ERROR,a))}const n=e;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(n):t?t.then(()=>this.loadKeyEME(n)):this.loadKeyEME(n);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(n);default:return Promise.reject(Xt(e,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){const i=Sg(e.initSegment.data);if(i.length){let s=i[0];const n=e.decryptdata.uri;if(s.some(a=>a!==0))this.log(`Using keyId found in init segment ${Ge(s)} keyUri: ${n}`),Ut.setKeyIdForUri(n,s);else{const a=Ut.addKeyIdForUri(n);this.log(`Patching empty keyId with ${Ge(a)} keyUri: ${n}`),s=a}e.decryptdata.keyId=s}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Xt(e,D.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){const t=e.decryptdata,i=t.uri;if(!i)return Promise.reject(Xt(e,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));const s=this.keyLoaderInfo[i];if(s){if(s.decryptdata.key)return t.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then(c=>(t.key=s.decryptdata.key,re(re({},c),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Ge(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);const n=this.config,a=n.loader,o=new a(n);e.keyLoader=o;const l=this.keyLoaderInfo[i]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((c,u)=>{const h={type:pe.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:i},d=n.keyLoadPolicy.default,g={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},f={onSuccess:(p,m,y,E)=>{const{frag:S,keyInfo:T,url:b}=y;if(!S.decryptdata||T!==this.keyLoaderInfo[b])return u(Xt(S,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),E));T.decryptdata.key=S.decryptdata.key=new Uint8Array(p.data),S.keyLoader=T.loader=T.keyLoadPromise=null,c({frag:S,keyInfo:T})},onError:(p,m,y,E)=>{this.resetLoader(m),u(Xt(e,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${p.code} loading key ${p.text}`),y,re({url:i,data:void 0},p)))},onTimeout:(p,m,y)=>{this.resetLoader(m),u(Xt(e,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),y))},onAbort:(p,m,y)=>{this.resetLoader(m),u(Xt(e,D.INTERNAL_ABORTED,new Error("key loading aborted"),y))}};o.load(h,g,f)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[s],n&&n.destroy()}}function Xt(r,e=D.KEY_LOAD_ERROR,t,i,s){return new Ot({type:se.NETWORK_ERROR,details:e,fatal:!1,frag:r,response:s,error:t,networkDetails:i||null})}function oh(r){const{type:e}=r;switch(e){case pe.AUDIO_TRACK:return te.AUDIO;case pe.SUBTITLE_TRACK:return te.SUBTITLE;default:return te.MAIN}}function Zn(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class xv{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(){const{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_LOADING,this.onLevelLoading,this),e.off(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const 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(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:pe.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:pe.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:pe.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:pe.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const i=this.loaders[pe.LEVEL];if(i){const s=i.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[pe.LEVEL])}}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const c=this.hls.logger,u=s.context;if((u==null?void 0:u.levelOrTrack)===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?c.log(`[playlist-loader]: ignore ${e.url} ongoing request`):c.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===pe.MANIFEST?n=i.manifestLoadPolicy.default:n=Re({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),q((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===pe.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===pe.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===pe.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const u=c.partTarget,h=c.targetduration;if(u&&h){const d=Math.max(u*3,h*.8)*1e3;n=Re({},n,{maxTimeToFirstByteMs:Math.min(d,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,u,h,d)=>{const g=this.getInternalLoader(h);this.resetInternalLoader(h.type);const f=c.data;u.parsing.start=performance.now(),Ft.isMediaPlaylist(f)||h.type!==pe.MANIFEST?this.handleTrackOrLevelPlaylist(c,u,h,d||null,g):this.handleMasterPlaylist(c,u,h,d)},onError:(c,u,h,d)=>{this.handleNetworkError(u,h,!1,c,d)},onTimeout:(c,u,h)=>{this.handleNetworkError(u,h,!0,void 0,c)}};s.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;const{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){const n=this.hls,a=e.data,o=Zn(e,i),l=Ft.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}const{contentSteering:c,levels:u,iframeVariants:h,sessionData:d,sessionKeys:g,startTimeOffset:f,variableList:p}=l;this.variableList=p,u.forEach(S=>{const{unknownCodecs:T}=S;if(T){const{preferManagedMediaSource:b}=this.hls.config;let{audioCodec:R,videoCodec:I}=S;for(let L=T.length;L--;){const A=T[L];Vi(A,"audio",b)?(S.audioCodec=R=R?`${R},${A}`:A,vi.audio[R.substring(0,4)]=2,T.splice(L,1)):Vi(A,"video",b)&&(S.videoCodec=I=I?`${I},${A}`:A,vi.video[I.substring(0,4)]=2,T.splice(L,1))}}});const{AUDIO:m=[],SUBTITLES:y,"CLOSED-CAPTIONS":E}=Ft.parseMasterPlaylistMedia(a,o,l);m.length&&!m.some(T=>!T.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Oe({}),bitrate:0,url:""})),n.trigger(v.MANIFEST_LOADED,{levels:u,audioTracks:m,subtitles:y,iframeVariants:h,captions:E,contentSteering:c,url:o,stats:t,networkDetails:s,sessionData:d,sessionKeys:g,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(e,t,i,s,n){const a=this.hls,{id:o,level:l,type:c}=i,u=Zn(e,i),h=q(l)?l:q(o)?o:0,d=oh(i),g=Ft.parseLevelPlaylist(e.data,u,h,d,0,this.variableList);if(c===pe.MANIFEST){const f={attrs:new Oe({}),bitrate:0,details:g,name:"",url:u};g.requestScheduled=t.loading.start+cc(g,0),a.trigger(v.MANIFEST_LOADED,{levels:[f],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=g,this.handlePlaylistLoaded(g,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(v.ERROR,{type:se.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:t.type===pe.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===pe.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===pe.AUDIO_TRACK||e.type===pe.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=D.UNKNOWN,c=!1;const u=this.getInternalLoader(e);switch(e.type){case pe.MANIFEST:l=i?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,c=!0;break;case pe.LEVEL:l=i?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,c=!1;break;case pe.AUDIO_TRACK:l=i?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case pe.SUBTITLE_TRACK:l=i?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);const h={type:se.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(s){let d=e.url;t&&"url"in t&&(d=t.url),h.response=re({url:d,data:void 0},s)}this.hls.trigger(v.ERROR,h)}handlePlaylistLoaded(e,t,i,s,n,a){const o=this.hls,{type:l,level:c,levelOrTrack:u,id:h,groupId:d,deliveryDirectives:g}=s,f=Zn(t,s),p=oh(s);let m=typeof s.level=="number"&&p===te.MAIN?c:void 0;u&&"iframes"in u&&u.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);const y=e.playlistParsingError;if(y){if(this.hls.logger.warn(`${y} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(v.ERROR,{type:se.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:s,level:m,parent:p,networkDetails:n,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(v.ERROR,{type:se.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:s,level:m,parent:p,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case pe.MANIFEST:case pe.LEVEL:if(m){if(!u)m=0;else if(u!==o.levels[m]){const E=o.levels.indexOf(u);E>-1&&(m=E)}}o.trigger(v.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:m||0,id:h||0,stats:i,networkDetails:n,deliveryDirectives:g,withoutMultiVariant:l===pe.MANIFEST,context:s});break;case pe.AUDIO_TRACK:o.trigger(v.AUDIO_TRACK_LOADED,{details:e,track:u,id:h||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:g,context:s});break;case pe.SUBTITLE_TRACK:o.trigger(v.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:h||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:g,context:s});break}}}class Je{static get version(){return zi}static isMSESupported(){return Vu()}static isSupported(){return Ly()}static getMediaSource(){return qt()}static get Events(){return v}static get MetadataSchema(){return st}static get ErrorTypes(){return se}static get ErrorDetails(){return D}static get DefaultConfig(){return Je.defaultConfig?Je.defaultConfig:vv}static set DefaultConfig(e){Je.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new cn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=jf(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),i=this.config=Sv(Je.DefaultConfig,e,t);this.userConfig=e,i.progressive&&Tv(i,t);const{streamController:s,abrController:n,bufferController:a,capLevelController:o,errorController:l,fpsController:c,id3TrackController:u,iframeController:h,gapController:d}=i,g=new l(this),f=this.abrController=new n(this),p=new cp(this),m=i.interstitialsController,y=m?this.interstitialsController=new m(this,Je):null,E=a?this.bufferController=new a(this,p):null,S=o?this.capLevelController=new o(this):null,T=c?new c(this):null,b=i.cmcdController,R=b?this.cmcdController=new b(this):null,I=new xv(this),L=i.contentSteeringController,A=L?new L(this):null,x=this.levelController=new bv(this,A),_=u?new u(this):void 0,w=new Av(this.config,this.logger),G=this.streamController=new s(this,p,w),B=this.gapController=d?new d(this,p):void 0;S&&S.setStreamController(G);const K=[I,x,G];y&&K.splice(1,0,y),A&&K.splice(1,0,A),this.networkControllers=K;const O=[f];E&&O.push(E),B&&O.push(B),S&&O.push(S),T&&(T.setStreamController(G),O.push(T)),_&&O.push(_),O.push(p),this.audioTrackController=this.createController(i.audioTrackController,K);const F=i.audioStreamController;F&&K.push(this.audioStreamController=new F(this,p,w)),this.subtitleTrackController=this.createController(i.subtitleTrackController,K);const M=i.subtitleStreamController;M&&K.push(this.subtititleStreamController=new M(this,p,w)),this.createController(i.timelineController,O),w.emeController=this.emeController=this.createController(i.emeController,O),R&&O.push(R),this.latencyController=this.createController(i.latencyController,O),this.coreComponents=O,this.iframeController=h?new h(this,Je):void 0,K.push(g);const V=g.onErrorOut;typeof V=="function"&&this.on(v.ERROR,V,g),this.on(v.MANIFEST_LOADED,I.onManifestLoaded,I)}createController(e,t){if(e){const 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;const s=e===v.ERROR;this.trigger(v.ERROR,{type:se.OTHER_ERROR,details:D.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(v.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0,this.iframeController=void 0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(v.ERROR,{type:se.OTHER_ERROR,details:D.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());const t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(v.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");const e={};this.trigger(v.MEDIA_DETACHING,e),this._media=null,this.trigger(v.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;const t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,i={transferMedia:t};return this.trigger(v.MEDIA_DETACHING,i),this.trigger(v.MEDIA_DETACHED,i),t}loadSource(e){var t;this.stopLoad();const i=this.media,s=this._url,n=this._url=Lr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),i&&s&&(s!==n||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(v.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==U.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[te.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[te.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[te.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=this.started,i=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(i?this.startLoad(i):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Ko()),e}get levels(){const 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(){const 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){const t=this.capLevelController,i=!!e;t&&i!==this.config.capLevelToPlayerSize&&(i?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{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){Yg(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(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){const{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const e=this.levelController.iframeVariants;return e||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=bl(t);return ml(e,i,navigator.mediaCapabilities)}}Je.defaultConfig=void 0;const ea=/iPhone|iPad|iPod|iOS/i.test(navigator.userAgent),lh=()=>{if(typeof navigator>"u")return!1;const r=navigator.userAgent||"",e=navigator.platform||"",t=typeof navigator.maxTouchPoints=="number"?navigator.maxTouchPoints:0;return!!(/iPad/i.test(r)||/Macintosh/i.test(r)&&t>1||e==="MacIntel"&&t>1)},ch=()=>ea||lh(),Iv=()=>typeof navigator>"u"?!1:/Android/i.test(navigator.userAgent||""),ta=()=>{if(typeof navigator>"u")return!1;const r=navigator.userAgent||"";return/UCBrowser|UCWEB|UBrowser|Quark|AliApp|QHBrowser/i.test(r)},Rv=()=>{if(typeof navigator>"u")return!1;const r=navigator.userAgent||"";return!!(/MiuiBrowser|XiaoMi|Xiaomi|MiBrowser|XMSDK|Redmi|POCO|MIUI/i.test(r)||typeof window<"u"&&(window.miui||window.MIUI))},uh=["hvc1.1.6.L93.B0","hev1.1.6.L93.B0","hvc1","hev1"];function ia(r){return r==="probably"||r==="maybe"}const Lv=()=>{if(typeof document>"u")return{supported:!1,detail:""};const r=document.createElement("video");if(!r||typeof r.canPlayType!="function")return{supported:!1,detail:""};for(let e=0;e<uh.length;e++){const t=uh[e],i=`video/mp4; codecs="${t}"`,s=r.canPlayType(i);if(ia(s))return{supported:!0,detail:s,codec:t,mime:i}}return{supported:!1,detail:""}},_v=()=>{if(typeof navigator>"u")return!1;const r=navigator.userAgent||"";return ch()?!0:/Safari/i.test(r)&&!/Chrome|Chromium|CriOS|Edg|Android/i.test(r)},Pv=()=>{if(typeof document>"u")return!1;const r=document.createElement("video");return!r||typeof r.canPlayType!="function"?!1:ia(r.canPlayType("application/vnd.apple.mpegurl"))||ia(r.canPlayType("application/x-mpegURL"))},Dv=(r={})=>{const e=!!r.isEncrypt,t=_v(),i=Pv(),s=Lv(),n=s.supported;return e?{supported:!1,reason:"encrypted",nativeHls:i,nativeHevc:n,isSafariLike:t}:!i||!t?{supported:!1,reason:"no_native_hls",nativeHls:i,nativeHevc:n,isSafariLike:t}:n?{supported:!0,reason:"ok",nativeHls:i,nativeHevc:n,isSafariLike:t,nativeHevcDetail:s}:{supported:!1,reason:"no_native_hevc",nativeHls:i,nativeHevc:n,isSafariLike:t}},wv=()=>{const r=navigator.userAgent.toLowerCase(),e=/android|webos|iphone|ipod|blackberry|iemobile|opera mini/.test(r);return/ipad/.test(r)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?"ipad":e?"h5":"pc"},Cv=".ylc-player-container,.ylc-live-player-container{position:relative;width:100%;height:100%;background:#000;overflow:hidden;isolation:isolate;transform:translateZ(0);-webkit-transform:translateZ(0)}.ylc-video-player,.ylc-live-player-video{position:relative;z-index:0;width:100%;height:100%;background:#000;overflow:hidden;object-fit:contain;pointer-events:none;-webkit-appearance:none;-moz-appearance:none;appearance:none}.ylc-video-player::-webkit-media-controls,.ylc-video-player::-webkit-media-controls-enclosure,.ylc-video-player::-webkit-media-controls-overlay-enclosure,.ylc-video-player::-webkit-media-controls-panel,.ylc-video-player::-webkit-media-controls-start-playback-button,.ylc-video-player::-webkit-media-controls-overlay-play-button,.ylc-video-player::-webkit-media-controls-timeline,.ylc-video-player::-webkit-media-controls-current-time-display,.ylc-video-player::-webkit-media-controls-time-remaining-display,.ylc-video-player::-webkit-media-controls-mute-button,.ylc-video-player::-webkit-media-controls-toggle-closed-captions-button,.ylc-video-player::-webkit-media-controls-volume-slider,.ylc-video-player::-webkit-media-controls-fullscreen-button,.ylc-video-player::-webkit-media-controls-play-button,.ylc-video-player::-internal-media-controls-overflow-button{display:none!important;opacity:0!important;pointer-events:none!important;-webkit-appearance:none!important;visibility:hidden!important;width:0!important;height:0!important;max-height:0!important}.ylc-video-canvas-mirror{position:absolute;left:0;top:0;width:100%;height:100%;z-index:1;background:#000;pointer-events:none;display:block}.ylc-video-touch-mask{position:absolute;left:0;top:0;width:100%;height:100%;z-index:2;background:transparent}.ylc-video-player-loading{display:none;position:absolute;left:50%;top:50%;z-index:3;width:48px;height:48px;margin:-24px 0 0 -24px;pointer-events:none}.ylc-video-player-loading.is-show{display:block}.ylc-video-player-loading-spinner{width:100%;height:100%;box-sizing:border-box;border:3px solid rgba(255,255,255,.25);border-top-color:#fff;border-radius:50%;animation:ylc-player-spin .7s linear infinite}@keyframes ylc-player-spin{to{transform:rotate(360deg)}}.ylc-video-player-control{position:absolute;bottom:0;left:0;width:100%;height:65px;z-index:2147483646;padding:8px;background:linear-gradient(180deg,#08090d00,#08090dcc);box-sizing:border-box;pointer-events:auto}.ylc-video-player-progerss{display:flex;align-items:center;position:relative;width:100%;height:30px}.ylc-video-player-progress-hover-time{display:none;position:absolute;bottom:calc(100% - 4px);left:0;z-index:100;padding:2px 6px;background:#000000bf;color:#fff;font-size:12px;line-height:16px;border-radius:2px;white-space:nowrap;pointer-events:none;transform:translate(-50%)}.ylc-video-player-progress-hover-time.is-show{display:block}.ylc-video-player-progress-line-bg{position:absolute;left:0;width:100%;height:3px;z-index:9;background:#e9e2e266;cursor:pointer}.ylc-video-player-progress-line{position:absolute;left:0;width:0;height:3px;z-index:99;background:#fff;cursor:pointer}.ylc-video-player-progress-line-dot{position:absolute;left:0;width:15px;height:15px;z-index:99;border-radius:50%;background:#fff;cursor:pointer}.ylc-video-player-btn-bar-container{display:flex;justify-content:space-between;position:relative;width:100%}.ylc-video-player-btn-bar-left,.ylc-video-player-btn-bar-right{display:flex;align-items:center}.ylc-video-player-play-button,.ylc-video-player-pause-button{display:block;width:20px;height:20px;cursor:pointer}.ylc-video-player-pause-button{display:none}.ylc-video-player-current-time,.ylc-video-player-total-time,.ylc-video-player-time-split{color:#fff;font-size:12px}.ylc-video-player-current-time{margin-left:10px}.ylc-video-player-time-split{padding:0 5px}.ylc-video-player-rate-button,.ylc-video-player-line-button{position:relative;color:#fff;font-size:12px;margin-left:10px;cursor:pointer;-webkit-user-select:none;user-select:none}.ylc-video-player-volume-button,.ylc-video-player-mute-button,.ylc-video-player-exit-full-screen-button{width:20px;height:20px;cursor:pointer;margin-left:10px}.ylc-video-player-full-screen-button{width:16px;height:16px;cursor:pointer;margin-left:10px}.ylc-video-player-mute-button,.ylc-video-player-exit-full-screen-button{display:none}.ylc-video-player-rate-list,.ylc-video-player-line-panel{display:none;position:absolute;left:50%;bottom:100%;transform:translate(-50%);z-index:20;min-width:72px;margin:0;padding:6px 0;list-style:none;background:#000000d9;border-radius:4px}.ylc-video-player-line-panel{padding:0 0 12px;background:transparent;min-width:auto}.ylc-video-player-line-list{min-width:72px;margin:0;padding:6px 0;list-style:none;background:#000000d9;border-radius:4px}.ylc-video-player-rate-item,.ylc-video-player-line-item{padding:8px 14px;text-align:center;white-space:nowrap;cursor:pointer}.ylc-video-player-rate-item.active,.ylc-video-player-line-item.active{font-weight:600}.ylc-live-player-badge{position:absolute;top:12px;left:12px;padding:2px 8px;border-radius:2px;background:#e53935;color:#fff;font-size:12px;font-weight:600;letter-spacing:1px;z-index:2}.ylc-live-player-status{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);color:#ffffffd9;font-size:14px;z-index:2;pointer-events:none}.ylc-live-player-controls{position:absolute;left:0;right:0;bottom:0;height:48px;display:flex;align-items:center;padding:0 12px;box-sizing:border-box;background:linear-gradient(transparent,#000000a6);z-index:2}.ylc-live-player-controls img{width:28px;height:28px;margin-right:10px;cursor:pointer;-webkit-user-select:none;user-select:none}.ylc-live-pause-button,.ylc-live-exit-full-screen-button{display:none}";let sa=!1;function ra(){if(sa||typeof document>"u")return;if(document.querySelector("[data-hx-player-style]")){sa=!0;return}sa=!0;const r=document.createElement("style");r.setAttribute("data-hx-player-style","1"),r.textContent=Cv,document.head.appendChild(r)}const kv=/quark-video-controls|browser-video-controls|uc-video-controls|ucbrowser|ali-video-controls|qh-video-controls|miui-video|mi-video-controls|xiaomi-video|video-overlay-controls|mibrowser|mi-browser|video-player-controller|native-video-controls|sys-video-controls/i,Ov=/^ylc-/,hh=/^(SCRIPT|STYLE|LINK|META)$/;let dh=!1;function fh(){if(ra(),!(dh||typeof document>"u")){if(dh=!0,!document.querySelector('meta[name="x5-video-player-type"]')){const r=document.createElement("meta");r.setAttribute("name","x5-video-player-type"),r.setAttribute("content","h5"),document.head.appendChild(r)}if(!document.querySelector('meta[name="x5-video-player-fullscreen"]')){const r=document.createElement("meta");r.setAttribute("name","x5-video-player-fullscreen"),r.setAttribute("content","false"),document.head.appendChild(r)}}}function gh(r){if(!r||r.nodeType!==1)return!1;if(r.getAttribute&&r.getAttribute("data-ylc"))return!0;const e=r.className&&String(r.className);return e?String(e).split(/\s+/).some(t=>Ov.test(t)):!1}function ph(r){if(!r||r.nodeType!==1||gh(r)||hh.test(r.tagName))return!1;const e=r.className&&String(r.className),t=r.id&&String(r.id),i=`${e||""} ${t||""}`;return!!(kv.test(i)||r.getAttribute&&r.getAttribute("data-browser-controls"))}function Fv(r){if(ph(r))return!0;if(!r||r.nodeType!==1||gh(r)||hh.test(r.tagName))return!1;const e=r.className&&String(r.className),t=r.id&&String(r.id),i=`${e||""} ${t||""}`;return/video|media|player/i.test(i)&&/control|toolbar|bar|overlay|panel/i.test(i)}function mh(r){if(!(!r||r.nodeType!==1)){try{r.remove();return}catch{}try{r.style.setProperty("display","none","important"),r.style.setProperty("opacity","0","important"),r.style.setProperty("pointer-events","none","important"),r.style.setProperty("visibility","hidden","important")}catch{}}}function ai(r){r&&(r.controls=!1,r.setAttribute("controlsList","nodownload nofullscreen noremoteplayback noplaybackrate"),r.hasAttribute("controls")&&r.removeAttribute("controls"))}class na{static injectStyle(){fh()}static stripNativeControls(e){ai(e)}static attach(e){fh(),ai(e);const t=f=>{ph(f)&&mh(f)},i=f=>{Fv(f)&&mh(f)},s=new MutationObserver(f=>{f.forEach(p=>{if(p.type==="attributes"){ai(e);return}p.addedNodes.forEach(m=>{i(m),ai(e)})})});s.observe(e,{attributes:!0,attributeFilter:["controls"],childList:!0,subtree:!0});const n=new MutationObserver(f=>{f.forEach(p=>{p.addedNodes.forEach(i)})}),a=new MutationObserver(f=>{f.forEach(p=>{p.addedNodes.forEach(m=>{!m||m.nodeType!==1||t(m)})})}),o=Iv()?50:200,l=setInterval(()=>{ai(e);const f=e.parentElement;f&&Array.from(f.children).forEach(p=>{p!==e&&t(p)})},o),c=setTimeout(()=>{if(e.parentElement){n.observe(e.parentElement,{childList:!0,subtree:!1});const f=e.closest(".ylc-player-container");f&&a.observe(f,{childList:!0})}},0),u=["play","playing","pause","loadedmetadata","loadeddata","canplay","seeking","seeked"],h=()=>ai(e);u.forEach(f=>e.addEventListener(f,h));const d=f=>{f&&typeof f.preventDefault=="function"&&f.preventDefault();try{e.webkitExitFullScreen&&e.webkitExitFullScreen()}catch{}ai(e)};e.addEventListener("webkitbeginfullscreen",d);const g=e.remove;return e.remove=function(){clearInterval(l),clearTimeout(c),s.disconnect(),n.disconnect(),a.disconnect(),u.forEach(f=>e.removeEventListener(f,h)),e.removeEventListener("webkitbeginfullscreen",d),g.call(this)},ta()&&e.setAttribute("airplay","allow"),e}}const St="https://shanhu-live-user-1317978474.cos.accelerate.myqcloud.com/web/shplayer_icon";function Mv({showControls:r=!0,currentLine:e=1}={}){const t=Number(e)===2?2:1;return`
43
- <div class="ylc-player-container">
44
- <div class="ylc-video-touch-mask" data-ylc="touch-mask"></div>
45
- <div class="ylc-video-player-loading" aria-hidden="true">
46
- <div class="ylc-video-player-loading-spinner"></div>
47
- </div>
48
- ${r?`
49
- <div class="ylc-video-player-control">
50
- <div class="ylc-video-player-progerss">
51
- <div class="ylc-video-player-progress-hover-time">00:00</div>
52
- <div class="ylc-video-player-progress-line-dot"></div>
53
- <div class="ylc-video-player-progress-line-bg"></div>
54
- <div class="ylc-video-player-progress-line"></div>
55
- </div>
56
- <div class="ylc-video-player-btn-bar-container">
57
- <div class="ylc-video-player-btn-bar-left">
58
- <img class="ylc-video-player-play-button" src="${St}/play_pause.png" alt="">
59
- <img class="ylc-video-player-pause-button" src="${St}/new_play_pause.png" alt="">
60
- <span id="ylcCurrentTime" class="ylc-video-player-current-time">00:00 </span>
61
- <span class="ylc-video-player-time-split">/</span>
62
- <span id="ylcTotalTime" class="ylc-video-player-total-time">00:00</span>
63
- </div>
64
- <div class="ylc-video-player-btn-bar-right">
65
- <!-- 切线路 UI 暂时关闭
66
- <div class="ylc-video-player-line-button">
67
- <span class="ylc-video-player-line-label">${t===2?"线路2":"线路1"}</span>
68
- <div class="ylc-video-player-line-panel">
69
- <ul class="ylc-video-player-line-list">
70
- <li class="ylc-video-player-line-item${t===1?" active":""}" data-value="1">线路1</li>
71
- <li class="ylc-video-player-line-item${t===2?" active":""}" data-value="2">线路2</li>
72
- </ul>
73
- </div>
74
- </div>
75
- -->
76
- <div class="ylc-video-player-rate-button">
77
- <span>倍数</span>
78
- <ul class="ylc-video-player-rate-list">
79
- <li class="ylc-video-player-rate-item" data-value="3">3.0X</li>
80
- <li class="ylc-video-player-rate-item" data-value="2">2.0X</li>
81
- <li class="ylc-video-player-rate-item active" data-value="1">1.0X</li>
82
- <li class="ylc-video-player-rate-item" data-value="0.5">0.5X</li>
83
- </ul>
84
- </div>
85
- <img class="ylc-video-player-volume-button" src="${St}/yinliang.png" alt="">
86
- <img class="ylc-video-player-mute-button" src="${St}/jingyin.png" alt="">
87
- <img class="ylc-video-player-full-screen-button" src="${St}/ylc_full_screen.png" alt="">
88
- <img class="ylc-video-player-exit-full-screen-button" src="${St}/ylc_exit_screen.png" alt="">
89
- </div>
90
- </div>
91
- </div>`:""}
92
- </div>
93
- `}function Nv({showControls:r=!0,muted:e=!1}={}){return`
94
- <div class="ylc-live-player-container">
95
- <div class="ylc-live-player-badge">LIVE</div>
96
- <div class="ylc-live-player-status"></div>
97
- ${r?`
98
- <div class="ylc-live-player-controls">
99
- <img class="ylc-live-play-button" src="${St}/play_pause.png" title="播放" alt="">
100
- <img class="ylc-live-pause-button" src="${St}/new_play_pause.png" title="暂停" alt="">
101
- <img class="ylc-live-volume-button" src="${St}/yinliang.png" title="声音" alt="" style="${e?"display:none":""}">
102
- <img class="ylc-live-mute-button" src="${St}/jingyin.png" title="静音" alt="" style="${e?"":"display:none"}">
103
- <img class="ylc-live-full-screen-button" src="${St}/ylc_full_screen.png" title="全屏" alt="">
104
- <img class="ylc-live-exit-full-screen-button" src="${St}/ylc_exit_screen.png" title="退出全屏" alt="">
105
- </div>`:""}
106
- </div>
107
- `}function yh(r){const e=document.createElement("div");return e.innerHTML=r.trim(),e.firstElementChild}class ar{static injectStyle(){ra(),na.injectStyle()}static createVideoElement(e={}){const t=document.createElement("video");t.className="ylc-video-player",t.muted=!!e.muted,e.poster&&(t.poster=e.poster),na.stripNativeControls(t),t.setAttribute("x5-video-player-type","h5"),t.setAttribute("x5-video-player-fullscreen","false"),t.setAttribute("x5-video-orientation","portrait"),t.setAttribute("x5-playsinline","true"),t.setAttribute("crossorigin","anonymous"),t.crossOrigin="anonymous",t.setAttribute("playsinline","true"),t.setAttribute("webkit-inline","true"),t.setAttribute("webkit-playsinline","true"),t.setAttribute("x-webkit-airplay","allow"),t.setAttribute("preload","metadata"),t.setAttribute("disablePictureInPicture","true"),t.setAttribute("controlsList","nodownload nofullscreen noremoteplayback noplaybackrate"),t.playsInline=!0,t.disablePictureInPicture=!0,"disableRemotePlayback"in t&&(t.disableRemotePlayback=!0),t.setAttribute("t7-video-player-type","inline"),t.setAttribute("t7-video-player-fullscreen","false"),ta()&&t.setAttribute("airplay","allow");const i=t.play.bind(t);return t.play=function(){return t.setAttribute("t7-video-player-type","inline"),t.setAttribute("x5-video-player-type","h5"),t.setAttribute("x5-video-player-fullscreen","false"),t.controls=!1,t.removeAttribute("controls"),i()},na.attach(t),t}static mount(e){ar.injectStyle();const t=yh(Mv({showControls:!!(e.options&&e.options.controls),currentLine:e.currentLine})),i=ar.createVideoElement(e.options||{});return i.controls=!1,i.removeAttribute("controls"),t.insertBefore(i,t.firstChild),e.container=t,e.videoElm=i,e.touchMask=t.querySelector(".ylc-video-touch-mask"),e.loadingElm=t.querySelector(".ylc-video-player-loading"),t}}let Bv=class{constructor(e){this.target=e,this.eventsQueue={}}on(e,t,i=!1){this.eventsQueue[e]||(this.eventsQueue[e]={methods:[],onceFlags:[]}),!this.eventsQueue[e].methods.includes(t)&&(this.eventsQueue[e].methods.push(t),this.eventsQueue[e].onceFlags.push(!!i))}once(e,t){this.on(e,t,!0)}emit(e,...t){const i=this.eventsQueue[e];if(!i)return;const{methods:s,onceFlags:n}=i,a=[],o=[];s.forEach((l,c)=>{try{l.apply(this.target,t)}catch(u){console.error("[VideoPlayer Events]",e,u)}n[c]||(a.push(l),o.push(!1))}),i.methods=a,i.onceFlags=o}off(e,t){const i=this.eventsQueue[e];if(!i)return;if(!t){delete this.eventsQueue[e];return}const s=i.methods.indexOf(t);s>=0&&(i.methods.splice(s,1),i.onceFlags.splice(s,1)),i.methods.length||delete this.eventsQueue[e]}removeAll(){this.eventsQueue={}}};const vh="wss://log-reporting.huaxiacloud.net/ws",Eh=1e4,Sh=2e3,Uv=5,He=class He{static getInstance(e={}){return He._instance?e&&Object.keys(e).length&&(He._instance.options={...He._instance.options,...e},e.userId!=null&&(He._instance.userId=String(e.userId)),e.terminal&&(He._instance.terminal=e.terminal)):He._instance=new He(e),He._instance}static connect(e={}){return He.getInstance(e).connect(e)}static report(e){return He.getInstance().report(e)}static getSessionId(){return He._instance&&He._instance.sessionId||""}static disconnect(e,t){He._instance&&He._instance.disconnect(e,t)}static isConnected(){return!!(He._instance&&He._instance.connected)}constructor(e={}){this.options={baseUrl:vh,connectTimeoutMs:Eh,reconnectDelayMs:Sh,maxReconnect:Uv,autoReconnect:!0,...e},this.ws=null,this.userId=this.options.userId!=null?String(this.options.userId):"",this.terminal=this.options.terminal||He.detectTerminal(),this.sessionId="",this._manualClose=!1,this._connecting=!1,this._reconnectCount=0,this._connectTimer=null,this._reconnectTimer=null,this._pendingQueue=[],this._connectingPromise=null}static detectTerminal(){return wv()}get connected(){return!!(this.ws&&this.ws.readyState===WebSocket.OPEN)}buildUrl(e=this.userId,t=this.terminal){const i=this.options.baseUrl||vh,s=`user_id=${encodeURIComponent(String(e))}&terminal=${encodeURIComponent(t)}`;return i.includes("?")?`${i}&${s}`:`${i}?${s}`}connect(e={}){return e.userId!=null&&(this.userId=String(e.userId)),e.terminal&&(this.terminal=e.terminal),this.connected?Promise.resolve(this):this._connecting?this._connectingPromise||Promise.resolve(this):(this._manualClose=!1,this._connecting=!0,this.sessionId="",this._connectingPromise=new Promise((t,i)=>{let s=!1,n="";try{n=this.buildUrl()}catch(o){this._connecting=!1,this._logError("连接参数错误",o),i(o);return}this._clearConnectTimer(),this._clearReconnectTimer();try{this.ws=new WebSocket(n)}catch(o){this._connecting=!1,this._logError("创建 WebSocket 失败",o),this._scheduleReconnect(),i(o);return}const a=this.options.connectTimeoutMs||Eh;this._connectTimer=setTimeout(()=>{const o=new Error(`[LogWebSocket] 连接超时(${a}ms): ${n}`);if(this._logError("连接超时",o),typeof this.options.onTimeout=="function")try{this.options.onTimeout(o)}catch{}try{this.ws&&this.ws.close()}catch{}this.ws=null,this._connecting=!1,s||(s=!0,i(o)),this._scheduleReconnect()},a),this.ws.onopen=()=>{if(this._clearConnectTimer(),this._connecting=!1,this._reconnectCount=0,this._logInfo("连接成功",{url:n}),typeof this.options.onOpen=="function")try{this.options.onOpen()}catch{}s||(s=!0,t(this))},this.ws.onmessage=o=>{if(this._handleMessage(o.data),typeof this.options.onMessage=="function")try{this.options.onMessage(o.data,o)}catch{}},this.ws.onerror=o=>{if(this._logError("连接异常",o),typeof this.options.onError=="function")try{this.options.onError(o)}catch{}},this.ws.onclose=o=>{if(this._clearConnectTimer(),this._connecting=!1,this.ws=null,this.sessionId="",this._logInfo("连接关闭",{code:o.code,reason:o.reason}),typeof this.options.onClose=="function")try{this.options.onClose(o)}catch{}s||(s=!0,i(new Error(`[LogWebSocket] 连接关闭 code=${o.code}`))),!this._manualClose&&this.options.autoReconnect!==!1&&this._scheduleReconnect()}}),this._connectingPromise)}report(e){const t=e;if(!this.connected||!this.sessionId)return this._pendingQueue.push(t),!this.connected&&!this._connecting&&!this._manualClose&&this.userId&&this.connect().catch(()=>{}),!1;try{return this.ws.send(this._normalizePayload(t)),!0}catch(i){return this._logError("上报失败",i),this._pendingQueue.push(t),!1}}_handleMessage(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return}if(!t||typeof t!="object")return;const i=t.session_id||t.sessionId;(t.type==="session"||i)&&i&&(this.sessionId=String(i),this._logInfo("收到 session_id",{sessionId:this.sessionId}),this._flushPending())}disconnect(e=1e3,t="client disconnect"){if(this._manualClose=!0,this._connecting=!1,this._clearConnectTimer(),this._clearReconnectTimer(),this._reconnectCount=0,this.sessionId="",this.ws){try{this.ws.close(e,t)}catch(i){this._logError("断开连接失败",i)}this.ws=null}}clearPending(){this._pendingQueue=[]}_normalizePayload(e){if(e==null)return"";if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return JSON.stringify(this._attachSessionId(t))}catch{}return e}if(e instanceof ArrayBuffer||e instanceof Blob)return e;if(typeof e=="object")try{return JSON.stringify(this._attachSessionId(e))}catch{return String(e)}return String(e)}_attachSessionId(e){const t={...e};return this.sessionId&&(t.playSessionId==null&&(t.playSessionId=this.sessionId),t.content&&typeof t.content=="object"&&!Array.isArray(t.content)&&(t.content={...t.content},t.content.playSessionId==null&&(t.content.playSessionId=this.sessionId))),t}_flushPending(){if(!this.connected||!this.sessionId||!this._pendingQueue.length)return;this._pendingQueue.splice(0,this._pendingQueue.length).forEach(t=>{try{this.ws.send(this._normalizePayload(t))}catch(i){this._logError("补发队列失败",i),this._pendingQueue.push(t)}})}_scheduleReconnect(){if(this._manualClose||this.options.autoReconnect===!1)return;const e=this.options.maxReconnect;if(e!==-1&&this._reconnectCount>=e){this._logError("重试次数已达上限,停止重连",{maxReconnect:e,reconnectCount:this._reconnectCount});return}if(this._reconnectTimer)return;this._reconnectCount+=1;const t=this.options.reconnectDelayMs||Sh,i=Math.min(t*Math.pow(1.5,this._reconnectCount-1),3e4);this._logInfo("准备重试连接",{reconnectCount:this._reconnectCount,delay:i}),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=null,this.connect().catch(()=>{})},i)}_clearConnectTimer(){this._connectTimer&&(clearTimeout(this._connectTimer),this._connectTimer=null)}_clearReconnectTimer(){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null)}_logInfo(e,t){t!==void 0?console.log(`[LogWebSocket] ${e}`,t):console.log(`[LogWebSocket] ${e}`)}_logError(e,t){t!==void 0?console.error(`[LogWebSocket] ${e}`,t):console.error(`[LogWebSocket] ${e}`)}};vt(He,"_instance",null);let ns=He;const $v=10,Gv={info:"流程日志",error:"错误日志",click:"点击事件日志",operate:"操作日志",fetch:"接口日志",metric:"指标日志"},lt=class lt{static setAppContext({appId:e}={}){e!=null&&(lt._appId=e)}static info(e,t){lt._report("info",e,t)}static error(e,t){lt._report("error",e,t)}static click(e,t){lt._report("click",e,t)}static operate(e,t){lt._report("operate",e,t)}static fetch(e,t){lt._report("fetch",e,t)}static metric(e,t,{sampleEvery:i=$v}={}){lt._metricCount+=1,!(i>1&&lt._metricCount%i!==1)&&lt._report("metric",e,t)}static _report(e,t,i){ns.report({content:{eventType:e,eventName:Gv[e]||"流程日志",eventCode:"",errorCode:e==="error"?"error":"",message:t,params:i,appId:lt._appId}})}};vt(lt,"_metricCount",0),vt(lt,"_appId","");let me=lt;const Fe=class Fe{static async loadWasm(){return Fe.module?Fe.module:(Fe.loadPromise||(Fe.isLoading=!0,Fe.loadPromise=Fe._loadWasmOnce().then(e=>(Fe.module=e,Fe.isLoading=!1,e)).catch(e=>{throw Fe.isLoading=!1,Fe.loadPromise=null,e})),Fe.loadPromise)}static async _loadWasmOnce(){const e=Date.now(),t=`${Fe.baseUrl}/decryptor/decryptor.js?v=${e}`,i=`${Fe.baseUrl}/decryptor/decryptor.wasm?v=${e}`,s=await fetch(t);if(!s.ok)throw new Error(`Failed to fetch decryptor.js: ${s.status}`);let n=await s.text();const a=await fetch(i);if(!a.ok)throw new Error(`Failed to fetch decryptor.wasm: ${a.status}`);const o=new Uint8Array(await a.arrayBuffer());n=n.replace(/import\.meta\.url/g,JSON.stringify(t)),n=n.replace(/import\.meta/g,"{}"),n=n.replace(/export\s+default\s+Module\s*;?/,"window.__decryptorModuleExport = Module;");const l=document.createElement("script");l.type="text/javascript",l.textContent=n,document.head.appendChild(l);const c=window.__decryptorModuleExport;if(l.remove(),delete window.__decryptorModuleExport,typeof c!="function")throw new Error("Module export not found");return await c({wasmBinary:o,locateFile:h=>h&&String(h).indexOf(".wasm")!==-1?i:h})}static normalizeFileId(e){if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e=="object"){const t=e.fileid,i=e.fileId;if(typeof t=="string"&&t.trim())return t.trim();if(typeof i=="string"&&i.trim())return i.trim()}throw new Error("invalid fileid")}static normalizeAuthCipher(e,t){if(typeof t=="string"&&t.trim())return t.trim();if(e&&typeof e=="object"){const i=e.authCipher,s=e.authToken,n=e.encryptedAuth;if(typeof i=="string"&&i.trim())return i.trim();if(typeof s=="string"&&s.trim())return s.trim();if(typeof n=="string"&&n.trim())return n.trim()}throw new Error("invalid authCipher")}static async decryptSegment(e,t,i){const s=await Fe.loadWasm(),n=s.cwrap("decrypt_ts_segment","number",["number","number","number","number","number","number"]),a=s.cwrap("free_buffer",null,["number"]),o=s.cwrap("last_error","number",[]),l=Fe.normalizeFileId(t),c=Fe.normalizeAuthCipher(t,i),u=s._malloc(e.length);s.HEAPU8.set(e,u);const h=l.length+1,d=s._malloc(h);s.stringToUTF8(l,d,h);const g=c.length+1,f=s._malloc(g);s.stringToUTF8(c,f,g);const p=s._malloc(4),m=s._malloc(4);try{const y=n(u,e.length,d,f,p,m);if(y!==0){const b=o();throw new Error(`decrypt_ts_segment failed(${y}): ${s.UTF8ToString(b)}`)}const E=s.getValue(p,"*"),S=s.getValue(m,"i32"),T=new Uint8Array(S);return T.set(s.HEAPU8.subarray(E,E+S)),a(E),T}finally{s._free(u),s._free(d),s._free(f),s._free(p),s._free(m)}}static async decrypt(e,t,i){const s=typeof t=="string"?t:Array.from(t).map(n=>String.fromCharCode(n)).join("");return Fe.decryptSegment(e,s,i)}static init(){console.log("TsDecrypt initialized")}};vt(Fe,"module",null),vt(Fe,"isLoading",!1),vt(Fe,"loadPromise",null),vt(Fe,"baseUrl","https://wanzibook-res-1317978474.cos.ap-guangzhou.myqcloud.com/web/ffmpeglib");let or=Fe;const Th=new Map,Vv=r=>{var e;return((e=r==null?void 0:r[0])==null?void 0:e.url)||null},bh=r=>{const e=Vv(r);return e&&Th.get(e)||null},Hv=(r,e)=>{const t=[],i=r.split(`
108
- `),s=new URL(e);for(let n=0;n<i.length;n++){const a=i[n].trim();if(!a||a.startsWith("#")||!a.includes(".ts"))continue;let o=a;if(!o.startsWith("http"))if(o.startsWith("/"))o=`${s.protocol}//${s.host}${o}`;else{const l=s.pathname.substring(0,s.pathname.lastIndexOf("/")+1);o=`${s.protocol}//${s.host}${l}${o}`}t.push(o)}return t},Ah=(r,e={})=>{if(!r||!r.length)return{validCdnIndices:[],baseM3u8Url:null};const t=r[0].url,i=[];if(r.forEach((l,c)=>{const u=e[l.url];u&&i.push({index:c,url:l.url,tsUrls:Hv(u,l.url)})}),i.length===0)return{validCdnIndices:[],baseM3u8Url:null};const s=i[0].tsUrls.length,n=i.filter(l=>l.tsUrls.length===s),a={};n.forEach(l=>{a[l.index]=l.tsUrls});const o=n.map(l=>l.index);return Th.set(t,{tsMap:a,validCdnIndices:o,baseM3u8Url:t}),{validCdnIndices:o,baseM3u8Url:t}},Kv=r=>{const e=bh(r);return e&&e.validCdnIndices.length?e.validCdnIndices.slice():!r||!r.length?[]:r.map((t,i)=>i)},qv=(r,e,t)=>{const i=bh(r);if(!i)return null;const s=i.tsMap[t];return!s||e<0||e>=s.length?null:s[e]};class Wv extends Je.DefaultConfig.loader{constructor(e){if(super(e),this.cdnList=e.cdnList||[],this.switchCdn=e.switchCdn||!1,this.isEncrypt=e.isEncrypt||!1,this.encryptedData=e.encryptedData||"",this.fileId=e.fileId||"",this.m3u8Cache=e.m3u8Cache||null,this.switchCdn&&this.cdnList.length>0)try{Ah(this.cdnList,this.m3u8Cache||{})}catch{}}load(e,t,i){const s=e&&e.url,n=e&&e.frag;if(s&&s.match(/\.ts(\?.*)?$/)&&n){this.stats&&this.stats.loading&&(this.stats.loading.start=performance.now()),this.switchCdn?this.loadTsWithCdnFailover(e,t,i):this.loadTsOnce(s,e,t,i);return}super.load(e,t,i)}loadTsWithCdnFailover(e,t,i){const{frag:s,url:n}=e,a=Kv(this.cdnList);if(!a.length){this.loadTsOnce(n,e,t,i);return}const o=l=>{if(l>=a.length){i.onError({code:0,text:"all cdn failed"},e,null,this.stats);return}const c=a[l],u=qv(this.cdnList,s.sn,c)||n;this.customDownload(u,(h,d)=>{if(!d){this.deliverTsData(u,h,e,i);return}o(l+1)})};o(0)}loadTsOnce(e,t,i,s){this.customDownload(e,(n,a)=>{a?s.onError({code:0,text:a.message},t,null,this.stats):this.deliverTsData(e,n,t,s)})}deliverTsData(e,t,i,s){const n=this.stats;n&&n.loading&&(n.loading.first=n.loading.first||performance.now(),n.loading.end=performance.now(),n.loaded=n.total=t.byteLength);const a=o=>{s.onSuccess({url:e,data:o},n,i,null)};if(this.isEncrypt){const o=new Uint8Array(t);or.decrypt(o,this.fileId,this.encryptedData).then(a).catch(()=>{s.onError({code:0,text:"decrypt failed"},i,null,n)});return}a(t)}customDownload(e,t){fetch(e).then(i=>{if(!i.ok)throw new Error(`HTTP ${i.status}`);return i.arrayBuffer()}).then(i=>t(i,null)).catch(i=>t(null,i))}abort(){}abortFragment(){}}class jv{constructor(e){this.config=e||{},this.context=null,this.stats={aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:0,end:0,first:0},parsing:{start:0,end:0},buffering:{start:0,end:0,first:0}}}load(e,t,i){this.context=e;const{url:s}=e;this.stats.loading.start=performance.now(),this.stats.aborted=!1;const n=this.config.m3u8Cache&&this.config.m3u8Cache[s];if(n){this.stats.loading.first=this.stats.loading.start,Promise.resolve().then(()=>{this.deliverPlaylist(s,n,i)});return}fetch(s,{method:"GET",headers:{Accept:"application/vnd.apple.mpegurl, */*"}}).then(a=>{if(!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);return this.stats.loading.first=performance.now(),a.text()}).then(a=>{this.config.m3u8Cache&&(this.config.m3u8Cache[s]=a),this.deliverPlaylist(s,a,i)}).catch(a=>{i.onError({code:a.status||0,text:a.message},e,null,this.stats)})}deliverPlaylist(e,t,i){this.stats.loading.end=performance.now(),this.stats.loaded=t.length,this.stats.total=t.length,this.stats.parsing.start=performance.now();const s=t.replace(/#EXT-X-KEY:[^\r\n]*\r?\n?/g,"");this.stats.parsing.end=performance.now(),i.onSuccess({url:e,data:s,code:200},this.stats,this.context,null)}abort(){}destroy(){this.context=null}getCacheAge(){return null}getResponseHeader(){return null}}class Qt{static createHlsInstance(e,t,i,s){or.loadWasm();const n=new Je({loader:Wv,pLoader:jv,cdnList:i,switchCdn:t,isEncrypt:s.isEncrypt,encryptedData:s.encryptedData,fileId:s.fileId,m3u8Cache:s.m3u8Cache||null,fragLoadingTimeOut:1440*60*1e3,manifestLoadingTimeOut:1440*60*1e3,levelLoadingTimeOut:1440*60*1e3});return n.attachMedia(e),n.on(Je.Events.ERROR,(a,o)=>{if(o&&o.details==="bufferAppendError"&&o.fatal&&n)try{n.recoverMediaError()}catch{}}),n}static startLoad(e,t){if(!e)throw new Error("HLS 实例不存在");e.loadSource(t)}static destroyHlsInstance(e){e&&e.destroy()}}class xh{static changeBtnStatus(e){e.options.controls&&(e.playButton.style.display=e.status==="playing"?"none":"block",e.pauseButton.style.display=e.status==="playing"?"block":"none")}}class as{static timeDouble(e){return e<10?`0${e}`:e}static dealTime(e){const t=Math.floor(e/60),i=Math.floor(e%60);return`${this.timeDouble(t)}:${this.timeDouble(i)}`}static updateDurationTime(e){if(!e.options.controls)return;const t=e.videoElm.duration;e.totalTimeElm.textContent=this.dealTime(t)}static updateCurrentTime(e,t){if(!e.options.controls||!e.timeElm)return;const i=t??e.videoElm.currentTime;Number.isFinite(i)&&(e.timeElm.textContent=this.dealTime(i))}}class lr{static updateLine(e,t){if(!e.options.controls||!e.progressLine)return;let i=t;if(i==null){const s=e.videoElm&&e.videoElm.duration;if(!s||!Number.isFinite(s))return;i=e.videoElm.currentTime/s}Number.isFinite(i)&&(i=Math.max(0,Math.min(1,i)),e.progressLine.style.width=`${i*100}%`,this.updateLineDot(e,i))}static updateLineDot(e,t){!e.options.controls||!e.progressLineDot||(e.progressLineDot.style.left=`${t*100}%`)}}class Li{static getFullscreenTarget(e){const t=e&&e.options&&e.options.fullscreenElement;if(!t)return e.container;if(t instanceof HTMLElement)return t;if(typeof t=="string"){const i=document.querySelector(t);if(i)return i;const s=document.getElementById(t.replace(/^#/,""));if(s)return s}return e.container}static changeFullScreen(e,t){e.isFullScreen=t,t?(e.exitFullScreenButton.style.display="block",e.fullScreenButton.style.display="none"):(e.exitFullScreenButton.style.display="none",e.fullScreenButton.style.display="block")}static fullScreen(e){if(ea||lh()){e.videoElm&&e.videoElm.webkitEnterFullscreen?e.videoElm.webkitEnterFullscreen():console.warn("iOS video fullscreen not supported");return}const t=Li.getFullscreenTarget(e);t.requestFullscreen?t.requestFullscreen():t.mozRequestFullScreen?t.mozRequestFullScreen():t.webkitRequestFullScreen&&(t.webkitRequestFullScreen(),setTimeout(()=>{document.dispatchEvent(new Event("fullscreenchange"))},0))}static exitFullScreen(e){if(ea){e.videoElm&&e.videoElm.webkitExitFullscreen&&e.videoElm.webkitExitFullscreen();return}document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}}class oi{static changeVolume(e,t){oi.sync(e,t)}static sync(e,t){e.videoElm&&(e.videoElm.muted=!t),!(!e.options||!e.options.controls)&&(!e.volumeButton||!e.muteButton||(t?(e.volumeButton.style.display="block",e.muteButton.style.display="none"):(e.volumeButton.style.display="none",e.muteButton.style.display="block")))}}class Yv{constructor(e,t){vt(this,"events",{});this.slider=e,this.track=t,this.isDragging=!1,this.startX=0,this.startLeft=0,this.maxOffset=0,this.init()}init(){this.maxOffset=this.track.offsetWidth,this.bindEvents()}bindEvents(){this.slider.addEventListener("mousedown",e=>{this.startDrag(e)}),document.addEventListener("mousemove",e=>{this.isDragging&&this.onDrag(e)}),document.addEventListener("mouseup",()=>{this.stopDrag()}),this.slider.addEventListener("touchstart",e=>{this.startDragTouch(e)}),document.addEventListener("touchmove",e=>{this.isDragging&&this.onDragTouch(e)}),document.addEventListener("touchend",()=>{this.stopDrag()})}startDrag(e){e.preventDefault(),this.isDragging=!0,this.maxOffset=this.track.offsetWidth,this.startX=e.clientX,this.startLeft=this.slider.offsetLeft,this.slider.classList.add("dragging"),this.emit("dragstart",this.getCurrentValue())}onDrag(e){if(!this.isDragging)return;e.preventDefault();const t=e.clientX-this.startX;let i=this.startLeft+t;i=Math.max(0,Math.min(this.maxOffset,i)),this.slider.style.left=i+"px",this.emit("drag",this.getCurrentValue())}stopDrag(){this.isDragging&&(this.isDragging=!1,this.slider.classList.remove("dragging"),this.emit("dragend",this.getCurrentValue()))}startDragTouch(e){e.preventDefault(),this.isDragging=!0,this.maxOffset=this.track.offsetWidth;const t=e.touches[0];this.startX=t.clientX,this.startLeft=this.slider.offsetLeft,this.slider.classList.add("dragging"),this.emit("dragstart",this.getCurrentValue())}onDragTouch(e){if(!this.isDragging)return;e.preventDefault();const i=e.touches[0].clientX-this.startX;let s=this.startLeft+i;s=Math.max(0,Math.min(this.maxOffset,s)),this.slider.style.left=s+"px",this.emit("drag",this.getCurrentValue())}getCurrentValue(){return this.slider.offsetLeft/this.maxOffset}setValue(e){e=Math.max(0,Math.min(1,e));const t=e*this.maxOffset;this.slider.style.left=t+"px"}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}emit(e,t){this.events[e]&&this.events[e].forEach(i=>i(t))}}class li{static getList(e){const t=e&&e.container||e&&e.videoElm&&e.videoElm.parentElement;return t?t.querySelector(".ylc-video-player-rate-list"):null}static changeRate(e,t){e.videoElm.playbackRate=Number(t);const i=li.getList(e);if(!i)return;i.querySelectorAll("li.ylc-video-player-rate-item").forEach(n=>{n.classList.remove("active")});const s=i.querySelector(`li[data-value="${t}"]`);s&&s.classList.add("active")}static showRatePannel(e){const t=li.getList(e);t&&(t.style.display="block")}static hideRatePannel(e){const t=li.getList(e);t&&(t.style.display="none")}}class at{static getRoot(e){return e.container||e.videoElm&&e.videoElm.parentElement}static getPanel(e){const t=at.getRoot(e);return t?t.querySelector(".ylc-video-player-line-panel"):null}static changeLineUI(e,t){const i=at.getRoot(e);if(!i)return;const s=i.querySelector(".ylc-video-player-line-list"),n=i.querySelector(".ylc-video-player-line-label");if(!s)return;s.querySelectorAll("li.ylc-video-player-line-item").forEach(o=>{o.classList.remove("active")});const a=s.querySelector(`li[data-value="${t}"]`);a&&a.classList.add("active"),n&&(n.textContent=Number(t)===2?"线路2":"线路1")}static showLinePannel(e){const t=at.getPanel(e);t&&(t.style.display="block")}static hideLinePannel(e){const t=at.getPanel(e);t&&(t.style.display="none")}}class aa{static mount(e){if(!e||!e.options||!e.options.controls||!e.container)return null;const t=new aa(e);return t.collectRefs(),t.bind(),t}constructor(e){this.player=e,this.progressLineBg=null,this.rateButton=null,this._lineHideTimer=null}collectRefs(){const e=this.player,t=i=>e.container.querySelector(i);e.playButton=t(".ylc-video-player-play-button"),e.pauseButton=t(".ylc-video-player-pause-button"),e.timeElm=t(".ylc-video-player-current-time"),e.totalTimeElm=t(".ylc-video-player-total-time"),this.progressWrap=t(".ylc-video-player-progerss"),this.progressLineBg=t(".ylc-video-player-progress-line-bg"),e.progressLine=t(".ylc-video-player-progress-line"),e.progressLineDot=t(".ylc-video-player-progress-line-dot"),e.progressHoverTime=t(".ylc-video-player-progress-hover-time"),e.fullScreenButton=t(".ylc-video-player-full-screen-button"),e.exitFullScreenButton=t(".ylc-video-player-exit-full-screen-button"),e.volumeButton=t(".ylc-video-player-volume-button"),e.muteButton=t(".ylc-video-player-mute-button"),this.rateButton=t(".ylc-video-player-rate-button"),oi.sync(e,!e.videoElm.muted)}bind(){const e=this.player;if(!e.playButton)return;e.playButton.addEventListener("click",()=>{me.click("VideoPlayer日志-点击了内部播放按钮"),e.play()}),e.pauseButton.addEventListener("click",()=>{me.click("VideoPlayer日志-点击了内部暂停按钮"),e.pause()});const t=(n,a)=>{const o=e.videoElm&&e.videoElm.duration;if(!o||!Number.isFinite(o))return;const l=(n.clientX-a.left)/a.width;Number.isFinite(l)&&e.seek(Math.max(0,Math.min(1,l))*o)};e.progressLine.addEventListener("click",n=>{me.click("VideoPlayer日志-点击了内部进度条快进"),t(n,this.progressLineBg.getBoundingClientRect())}),this.progressLineBg.addEventListener("click",n=>{me.click("VideoPlayer日志-点击了内部进度条背景快进"),t(n,n.target.getBoundingClientRect())});const i=n=>{const a=e.videoElm&&e.videoElm.duration,o=e.progressHoverTime,l=this.progressLineBg;if(!o||!l)return;if(!a||!Number.isFinite(a)||a<=0){o.classList.remove("is-show");return}const c=l.getBoundingClientRect();if(!c.width)return;const u=Math.max(0,Math.min(1,(n.clientX-c.left)/c.width));o.textContent=as.dealTime(u*a),o.classList.add("is-show");const h=o.offsetWidth/2,d=Math.max(h,Math.min(c.width-h,u*c.width));o.style.left=`${d}px`};this.progressWrap&&(this.progressWrap.addEventListener("mousemove",i),this.progressWrap.addEventListener("mouseleave",()=>{e.progressHoverTime&&e.progressHoverTime.classList.remove("is-show")})),e.progressSlider=new Yv(e.progressLineDot,this.progressLineBg),e.progressSlider.on("drag",n=>{const a=e.videoElm&&e.videoElm.duration;lr.updateLine(e,n),Number.isFinite(a)&&as.updateCurrentTime(e,n*a),me.operate("VideoPlayer日志-正在拖拽内部进度条快进")}),e.progressSlider.on("dragend",n=>{const a=e.videoElm&&e.videoElm.duration;me.operate("VideoPlayer日志-结束拖拽内部进度条快进",{value:n,duration:a}),!(!a||!Number.isFinite(a))&&e.seek(n*a)}),e.fullScreenButton.addEventListener("click",()=>{me.click("VideoPlayer日志-点击了内部全屏按钮"),e.requestFullscreen(),e.events.emit("fullscreenchange",!0)}),e.exitFullScreenButton.addEventListener("click",()=>{me.click("VideoPlayer日志-点击了内部退出全屏按钮"),e.exitFullscreen(),e.events.emit("fullscreenchange",!1)}),e.volumeButton.addEventListener("click",()=>{me.click("VideoPlayer日志-点击了静音按钮"),oi.changeVolume(e,!1),e.events.emit("volumechange",!1)}),e.muteButton.addEventListener("click",()=>{me.click("VideoPlayer日志-点击了开启音量按钮"),oi.changeVolume(e,!0),e.events.emit("volumechange",!0)}),this.rateButton.addEventListener("mouseenter",()=>{e.events.emit("ratePannelChange",!0),li.showRatePannel(e)}),this.rateButton.addEventListener("mouseleave",()=>{e.events.emit("ratePannelChange",!1),li.hideRatePannel(e)});const s=this.rateButton.querySelector(".ylc-video-player-rate-list");s&&s.querySelectorAll("li.ylc-video-player-rate-item").forEach(n=>{n.addEventListener("click",()=>{li.changeRate(e,n.getAttribute("data-value")||1)})})}_bindLineButton(){const e=this.player,t=e.lineButton;if(!t)return;const i=()=>{this._lineHideTimer&&(clearTimeout(this._lineHideTimer),this._lineHideTimer=null)};t.addEventListener("mouseenter",()=>{i(),e.events.emit("linePannelChange",!0),at.showLinePannel(e)}),t.addEventListener("mouseleave",()=>{i(),this._lineHideTimer=setTimeout(()=>{e.events.emit("linePannelChange",!1),at.hideLinePannel(e)},320)}),t.addEventListener("click",n=>{if(n.target&&n.target.closest&&n.target.closest(".ylc-video-player-line-item"))return;n.stopPropagation(),i();const a=t.querySelector(".ylc-video-player-line-panel");if(!a)return;const o=a.style.display==="none"||!a.style.display;e.events.emit("linePannelChange",o),o?at.showLinePannel(e):at.hideLinePannel(e)});const s=t.querySelector(".ylc-video-player-line-list");s&&s.querySelectorAll("li.ylc-video-player-line-item").forEach(n=>{n.addEventListener("pointerdown",async a=>{a.preventDefault(),a.stopPropagation();const o=Number(n.getAttribute("data-value"))||1;at.hideLinePannel(e);try{await e.switchLine(o)&&at.changeLineUI(e,o)}catch{}})})}}var Ih=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zv(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function Xv(r){if(Object.prototype.hasOwnProperty.call(r,"__esModule"))return r;var e=r.default;if(typeof e=="function"){var t=function i(){return this instanceof i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(i){var s=Object.getOwnPropertyDescriptor(r,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return r[i]}})}),t}var oa,Rh;function _i(){return Rh||(Rh=1,oa=TypeError),oa}const Qv=Xv(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var la,Lh;function cr(){if(Lh)return la;Lh=1;var r=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&r?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=r&&e&&typeof e.get=="function"?e.get:null,i=r&&Map.prototype.forEach,s=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,a=s&&n&&typeof n.get=="function"?n.get:null,o=s&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,h=u?WeakSet.prototype.has:null,d=typeof WeakRef=="function"&&WeakRef.prototype,g=d?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,p=Object.prototype.toString,m=Function.prototype.toString,y=String.prototype.match,E=String.prototype.slice,S=String.prototype.replace,T=String.prototype.toUpperCase,b=String.prototype.toLowerCase,R=RegExp.prototype.test,I=Array.prototype.concat,L=Array.prototype.join,A=Array.prototype.slice,x=Math.floor,_=typeof BigInt=="function"?BigInt.prototype.valueOf:null,w=Object.getOwnPropertySymbols,G=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,B=typeof Symbol=="function"&&typeof Symbol.iterator=="object",K=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===B||!0)?Symbol.toStringTag:null,O=Object.prototype.propertyIsEnumerable,F=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(k){return k.__proto__}:null);function M(k,N){if(k===1/0||k===-1/0||k!==k||k&&k>-1e3&&k<1e3||R.call(/e/,N))return N;var Ie=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof k=="number"){var De=k<0?-x(-k):x(k);if(De!==k){var Ce=String(De),Se=E.call(N,Ce.length+1);return S.call(Ce,Ie,"$&_")+"."+S.call(S.call(Se,/([0-9]{3})/g,"$&_"),/_$/,"")}}return S.call(N,Ie,"$&_")}var V=Qv,$=V.custom,C=ye($)?$:null,H={__proto__:null,double:'"',single:"'"},Q={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};la=function k(N,Ie,De,Ce){var Se=Ie||{};if(ee(Se,"quoteStyle")&&!ee(H,Se.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(ee(Se,"maxStringLength")&&(typeof Se.maxStringLength=="number"?Se.maxStringLength<0&&Se.maxStringLength!==1/0:Se.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var Zt=ee(Se,"customInspect")?Se.customInspect:!0;if(typeof Zt!="boolean"&&Zt!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(ee(Se,"indent")&&Se.indent!==null&&Se.indent!==" "&&!(parseInt(Se.indent,10)===Se.indent&&Se.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(ee(Se,"numericSeparator")&&typeof Se.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var gi=Se.numericSeparator;if(typeof N>"u")return"undefined";if(N===null)return"null";if(typeof N=="boolean")return N?"true":"false";if(typeof N=="string")return it(N,Se);if(typeof N=="number"){if(N===0)return 1/0/N>0?"0":"-0";var yt=String(N);return gi?M(N,yt):yt}if(typeof N=="bigint"){var ei=String(N)+"n";return gi?M(N,ei):ei}var Ao=typeof Se.depth>"u"?5:Se.depth;if(typeof De>"u"&&(De=0),De>=Ao&&Ao>0&&typeof N=="object")return z(N)?"[Array]":"[Object]";var ki=HT(Se,De);if(typeof Ce>"u")Ce=[];else if(ve(Ce,N)>=0)return"[Circular]";function Pt(Oi,Ir,qT){if(Ir&&(Ce=A.call(Ce),Ce.push(Ir)),qT){var wf={depth:Se.depth};return ee(Se,"quoteStyle")&&(wf.quoteStyle=Se.quoteStyle),k(Oi,wf,De+1,Ce)}return k(Oi,Se,De+1,Ce)}if(typeof N=="function"&&!oe(N)){var xf=ge(N),If=Ar(N,Pt);return"[Function"+(xf?": "+xf:" (anonymous)")+"]"+(If.length>0?" { "+L.call(If,", ")+" }":"")}if(ye(N)){var Rf=B?S.call(String(N),/^(Symbol\(.*\))_[^)]*$/,"$1"):G.call(N);return typeof N=="object"&&!B?ut(Rf):Rf}if(ct(N)){for(var ms="<"+b.call(String(N.nodeName)),xo=N.attributes||[],xr=0;xr<xo.length;xr++)ms+=" "+xo[xr].name+"="+J(ce(xo[xr].value),"double",Se);return ms+=">",N.childNodes&&N.childNodes.length&&(ms+="..."),ms+="</"+b.call(String(N.nodeName))+">",ms}if(z(N)){if(N.length===0)return"[]";var Io=Ar(N,Pt);return ki&&!br(Io)?"["+bo(Io,ki)+"]":"[ "+L.call(Io,", ")+" ]"}if(ue(N)){var Ro=Ar(N,Pt);return!("cause"in Error.prototype)&&"cause"in N&&!O.call(N,"cause")?"{ ["+String(N)+"] "+L.call(I.call("[cause]: "+Pt(N.cause),Ro),", ")+" }":Ro.length===0?"["+String(N)+"]":"{ ["+String(N)+"] "+L.call(Ro,", ")+" }"}if(typeof N=="object"&&Zt){if(C&&typeof N[C]=="function"&&V)return V(N,{depth:Ao-De});if(Zt!=="symbol"&&typeof N.inspect=="function")return N.inspect()}if(Te(N)){var Lf=[];return i&&i.call(N,function(Oi,Ir){Lf.push(Pt(Ir,N,!0)+" => "+Pt(Oi,N))}),ht("Map",t.call(N),Lf,ki)}if(Le(N)){var _f=[];return o&&o.call(N,function(Oi){_f.push(Pt(Oi,N))}),ht("Set",a.call(N),_f,ki)}if($e(N))return mt("WeakMap");if(Xe(N))return mt("WeakSet");if(tt(N))return mt("WeakRef");if(de(N))return ut(Pt(Number(N)));if(Me(N))return ut(Pt(_.call(N)));if(ae(N))return ut(f.call(N));if(Ee(N))return ut(Pt(String(N)));if(typeof window<"u"&&N===window)return"{ [object Window] }";if(typeof globalThis<"u"&&N===globalThis||typeof Ih<"u"&&N===Ih)return"{ [object globalThis] }";if(!ne(N)&&!oe(N)){var Lo=Ar(N,Pt),Pf=F?F(N)===Object.prototype:N instanceof Object||N.constructor===Object,_o=N instanceof Object?"":"null prototype",Df=!Pf&&K&&Object(N)===N&&K in N?E.call(W(N),8,-1):_o?"Object":"",KT=Pf||typeof N.constructor!="function"?"":N.constructor.name?N.constructor.name+" ":"",Po=KT+(Df||_o?"["+L.call(I.call([],Df||[],_o||[]),": ")+"] ":"");return Lo.length===0?Po+"{}":ki?Po+"{"+bo(Lo,ki)+"}":Po+"{ "+L.call(Lo,", ")+" }"}return String(N)};function J(k,N,Ie){var De=Ie.quoteStyle||N,Ce=H[De];return Ce+k+Ce}function ce(k){return S.call(String(k),/"/g,"&quot;")}function ie(k){return!K||!(typeof k=="object"&&(K in k||typeof k[K]<"u"))}function z(k){return W(k)==="[object Array]"&&ie(k)}function ne(k){return W(k)==="[object Date]"&&ie(k)}function oe(k){return W(k)==="[object RegExp]"&&ie(k)}function ue(k){return W(k)==="[object Error]"&&ie(k)}function Ee(k){return W(k)==="[object String]"&&ie(k)}function de(k){return W(k)==="[object Number]"&&ie(k)}function ae(k){return W(k)==="[object Boolean]"&&ie(k)}function ye(k){if(B)return k&&typeof k=="object"&&k instanceof Symbol;if(typeof k=="symbol")return!0;if(!k||typeof k!="object"||!G)return!1;try{return G.call(k),!0}catch{}return!1}function Me(k){if(!k||typeof k!="object"||!_)return!1;try{return _.call(k),!0}catch{}return!1}var j=Object.prototype.hasOwnProperty||function(k){return k in this};function ee(k,N){return j.call(k,N)}function W(k){return p.call(k)}function ge(k){if(k.name)return k.name;var N=y.call(m.call(k),/^function\s*([\w$]+)/);return N?N[1]:null}function ve(k,N){if(k.indexOf)return k.indexOf(N);for(var Ie=0,De=k.length;Ie<De;Ie++)if(k[Ie]===N)return Ie;return-1}function Te(k){if(!t||!k||typeof k!="object")return!1;try{t.call(k);try{a.call(k)}catch{return!0}return k instanceof Map}catch{}return!1}function $e(k){if(!c||!k||typeof k!="object")return!1;try{c.call(k,c);try{h.call(k,h)}catch{return!0}return k instanceof WeakMap}catch{}return!1}function tt(k){if(!g||!k||typeof k!="object")return!1;try{return g.call(k),!0}catch{}return!1}function Le(k){if(!a||!k||typeof k!="object")return!1;try{a.call(k);try{t.call(k)}catch{return!0}return k instanceof Set}catch{}return!1}function Xe(k){if(!h||!k||typeof k!="object")return!1;try{h.call(k,h);try{c.call(k,c)}catch{return!0}return k instanceof WeakSet}catch{}return!1}function ct(k){return!k||typeof k!="object"?!1:typeof HTMLElement<"u"&&k instanceof HTMLElement?!0:typeof k.nodeName=="string"&&typeof k.getAttribute=="function"}function it(k,N){if(k.length>N.maxStringLength){var Ie=k.length-N.maxStringLength,De="... "+Ie+" more character"+(Ie>1?"s":"");return it(E.call(k,0,N.maxStringLength),N)+De}var Ce=Q[N.quoteStyle||"single"];Ce.lastIndex=0;var Se=S.call(S.call(k,Ce,"\\$1"),/[\x00-\x1f]/g,We);return J(Se,"single",N)}function We(k){var N=k.charCodeAt(0),Ie={8:"b",9:"t",10:"n",12:"f",13:"r"}[N];return Ie?"\\"+Ie:"\\x"+(N<16?"0":"")+T.call(N.toString(16))}function ut(k){return"Object("+k+")"}function mt(k){return k+" { ? }"}function ht(k,N,Ie,De){var Ce=De?bo(Ie,De):L.call(Ie,", ");return k+" ("+N+") {"+Ce+"}"}function br(k){for(var N=0;N<k.length;N++)if(ve(k[N],`
109
- `)>=0)return!1;return!0}function HT(k,N){var Ie;if(k.indent===" ")Ie=" ";else if(typeof k.indent=="number"&&k.indent>0)Ie=L.call(Array(k.indent+1)," ");else return null;return{base:Ie,prev:L.call(Array(N+1),Ie)}}function bo(k,N){if(k.length===0)return"";var Ie=`
110
- `+N.prev+N.base;return Ie+L.call(k,","+Ie)+`
111
- `+N.prev}function Ar(k,N){var Ie=z(k),De=[];if(Ie){De.length=k.length;for(var Ce=0;Ce<k.length;Ce++)De[Ce]=ee(k,Ce)?N(k[Ce],k):""}var Se=typeof w=="function"?w(k):[],Zt;if(B){Zt={};for(var gi=0;gi<Se.length;gi++)Zt["$"+Se[gi]]=Se[gi]}for(var yt in k)ee(k,yt)&&(Ie&&String(Number(yt))===yt&&yt<k.length||B&&Zt["$"+yt]instanceof Symbol||(R.call(/[^\w$]/,yt)?De.push(N(yt,k)+": "+N(k[yt],k)):De.push(yt+": "+N(k[yt],k))));if(typeof w=="function")for(var ei=0;ei<Se.length;ei++)O.call(k,Se[ei])&&De.push("["+N(Se[ei])+"]: "+N(k[Se[ei]],k));return De}return la}var ca,_h;function Jv(){if(_h)return ca;_h=1;var r=cr(),e=_i(),t=function(o,l,c){for(var u=o,h;(h=u.next)!=null;u=h)if(h.key===l)return u.next=h.next,c||(h.next=o.next,o.next=h),h},i=function(o,l){if(o){var c=t(o,l);return c&&c.value}},s=function(o,l,c){var u=t(o,l);u?u.value=c:o.next={key:l,next:o.next,value:c}},n=function(o,l){return o?!!t(o,l):!1},a=function(o,l){if(o)return t(o,l,!0)};return ca=function(){var l,c={assert:function(u){if(!c.has(u))throw new e("Side channel does not contain "+r(u))},delete:function(u){var h=a(l,u);return h&&l&&!l.next&&(l=void 0),!!h},get:function(u){return i(l,u)},has:function(u){return n(l,u)},set:function(u,h){l||(l={next:void 0}),s(l,u,h)}};return c},ca}var ua,Ph;function Dh(){return Ph||(Ph=1,ua=Object),ua}var ha,wh;function Zv(){return wh||(wh=1,ha=Error),ha}var da,Ch;function eE(){return Ch||(Ch=1,da=EvalError),da}var fa,kh;function tE(){return kh||(kh=1,fa=RangeError),fa}var ga,Oh;function iE(){return Oh||(Oh=1,ga=ReferenceError),ga}var pa,Fh;function sE(){return Fh||(Fh=1,pa=SyntaxError),pa}var ma,Mh;function rE(){return Mh||(Mh=1,ma=URIError),ma}var ya,Nh;function nE(){return Nh||(Nh=1,ya=Math.abs),ya}var va,Bh;function aE(){return Bh||(Bh=1,va=Math.floor),va}var Ea,Uh;function oE(){return Uh||(Uh=1,Ea=Math.max),Ea}var Sa,$h;function lE(){return $h||($h=1,Sa=Math.min),Sa}var Ta,Gh;function cE(){return Gh||(Gh=1,Ta=Math.pow),Ta}var ba,Vh;function uE(){return Vh||(Vh=1,ba=Math.round),ba}var Aa,Hh;function hE(){return Hh||(Hh=1,Aa=Number.isNaN||function(e){return e!==e}),Aa}var xa,Kh;function dE(){if(Kh)return xa;Kh=1;var r=hE();return xa=function(t){return r(t)||t===0?t:t<0?-1:1},xa}var Ia,qh;function fE(){return qh||(qh=1,Ia=Object.getOwnPropertyDescriptor),Ia}var Ra,Wh;function jh(){if(Wh)return Ra;Wh=1;var r=fE();if(r)try{r([],"length")}catch{r=null}return Ra=r,Ra}var La,Yh;function zh(){if(Yh)return La;Yh=1;var r=Object.defineProperty||!1;if(r)try{r({},"a",{value:1})}catch{r=!1}return La=r,La}var _a,Xh;function gE(){return Xh||(Xh=1,_a=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},t=Symbol("test"),i=Object(t);if(typeof t=="string"||Object.prototype.toString.call(t)!=="[object Symbol]"||Object.prototype.toString.call(i)!=="[object Symbol]")return!1;var s=42;e[t]=s;for(var n in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,t);if(o.value!==s||o.enumerable!==!0)return!1}return!0}),_a}var Pa,Qh;function pE(){if(Qh)return Pa;Qh=1;var r=typeof Symbol<"u"&&Symbol,e=gE();return Pa=function(){return typeof r!="function"||typeof Symbol!="function"||typeof r("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Pa}var Da,Jh;function Zh(){return Jh||(Jh=1,Da=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),Da}var wa,ed;function td(){if(ed)return wa;ed=1;var r=Dh();return wa=r.getPrototypeOf||null,wa}var Ca,id;function mE(){if(id)return Ca;id=1;var r="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,i="[object Function]",s=function(l,c){for(var u=[],h=0;h<l.length;h+=1)u[h]=l[h];for(var d=0;d<c.length;d+=1)u[d+l.length]=c[d];return u},n=function(l,c){for(var u=[],h=c,d=0;h<l.length;h+=1,d+=1)u[d]=l[h];return u},a=function(o,l){for(var c="",u=0;u<o.length;u+=1)c+=o[u],u+1<o.length&&(c+=l);return c};return Ca=function(l){var c=this;if(typeof c!="function"||e.apply(c)!==i)throw new TypeError(r+c);for(var u=n(arguments,1),h,d=function(){if(this instanceof h){var y=c.apply(this,s(u,arguments));return Object(y)===y?y:this}return c.apply(l,s(u,arguments))},g=t(0,c.length-u.length),f=[],p=0;p<g;p++)f[p]="$"+p;if(h=Function("binder","return function ("+a(f,",")+"){ return binder.apply(this,arguments); }")(d),c.prototype){var m=function(){};m.prototype=c.prototype,h.prototype=new m,m.prototype=null}return h},Ca}var ka,sd;function ur(){if(sd)return ka;sd=1;var r=mE();return ka=Function.prototype.bind||r,ka}var Oa,rd;function Fa(){return rd||(rd=1,Oa=Function.prototype.call),Oa}var Ma,nd;function ad(){return nd||(nd=1,Ma=Function.prototype.apply),Ma}var Na,od;function yE(){return od||(od=1,Na=typeof Reflect<"u"&&Reflect&&Reflect.apply),Na}var Ba,ld;function vE(){if(ld)return Ba;ld=1;var r=ur(),e=ad(),t=Fa(),i=yE();return Ba=i||r.call(t,e),Ba}var Ua,cd;function ud(){if(cd)return Ua;cd=1;var r=ur(),e=_i(),t=Fa(),i=vE();return Ua=function(n){if(n.length<1||typeof n[0]!="function")throw new e("a function is required");return i(r,t,n)},Ua}var $a,hd;function EE(){if(hd)return $a;hd=1;var r=ud(),e=jh(),t;try{t=[].__proto__===Array.prototype}catch(a){if(!a||typeof a!="object"||!("code"in a)||a.code!=="ERR_PROTO_ACCESS")throw a}var i=!!t&&e&&e(Object.prototype,"__proto__"),s=Object,n=s.getPrototypeOf;return $a=i&&typeof i.get=="function"?r([i.get]):typeof n=="function"?function(o){return n(o==null?o:s(o))}:!1,$a}var Ga,dd;function SE(){if(dd)return Ga;dd=1;var r=Zh(),e=td(),t=EE();return Ga=r?function(s){return r(s)}:e?function(s){if(!s||typeof s!="object"&&typeof s!="function")throw new TypeError("getProto: not an object");return e(s)}:t?function(s){return t(s)}:null,Ga}var Va,fd;function TE(){if(fd)return Va;fd=1;var r=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=ur();return Va=t.call(r,e),Va}var Ha,gd;function Ka(){if(gd)return Ha;gd=1;var r,e=Dh(),t=Zv(),i=eE(),s=tE(),n=iE(),a=sE(),o=_i(),l=rE(),c=nE(),u=aE(),h=oE(),d=lE(),g=cE(),f=uE(),p=dE(),m=Function,y=function(oe){try{return m('"use strict"; return ('+oe+").constructor;")()}catch{}},E=jh(),S=zh(),T=function(){throw new o},b=E?(function(){try{return arguments.callee,T}catch{try{return E(arguments,"callee").get}catch{return T}}})():T,R=pE()(),I=SE(),L=td(),A=Zh(),x=ad(),_=Fa(),w={},G=typeof Uint8Array>"u"||!I?r:I(Uint8Array),B={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?r:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?r:ArrayBuffer,"%ArrayIteratorPrototype%":R&&I?I([][Symbol.iterator]()):r,"%AsyncFromSyncIteratorPrototype%":r,"%AsyncFunction%":w,"%AsyncGenerator%":w,"%AsyncGeneratorFunction%":w,"%AsyncIteratorPrototype%":w,"%Atomics%":typeof Atomics>"u"?r:Atomics,"%BigInt%":typeof BigInt>"u"?r:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?r:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?r:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?r:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":t,"%eval%":eval,"%EvalError%":i,"%Float16Array%":typeof Float16Array>"u"?r:Float16Array,"%Float32Array%":typeof Float32Array>"u"?r:Float32Array,"%Float64Array%":typeof Float64Array>"u"?r:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?r:FinalizationRegistry,"%Function%":m,"%GeneratorFunction%":w,"%Int8Array%":typeof Int8Array>"u"?r:Int8Array,"%Int16Array%":typeof Int16Array>"u"?r:Int16Array,"%Int32Array%":typeof Int32Array>"u"?r:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":R&&I?I(I([][Symbol.iterator]())):r,"%JSON%":typeof JSON=="object"?JSON:r,"%Map%":typeof Map>"u"?r:Map,"%MapIteratorPrototype%":typeof Map>"u"||!R||!I?r:I(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":E,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?r:Promise,"%Proxy%":typeof Proxy>"u"?r:Proxy,"%RangeError%":s,"%ReferenceError%":n,"%Reflect%":typeof Reflect>"u"?r:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?r:Set,"%SetIteratorPrototype%":typeof Set>"u"||!R||!I?r:I(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?r:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":R&&I?I(""[Symbol.iterator]()):r,"%Symbol%":R?Symbol:r,"%SyntaxError%":a,"%ThrowTypeError%":b,"%TypedArray%":G,"%TypeError%":o,"%Uint8Array%":typeof Uint8Array>"u"?r:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?r:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?r:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?r:Uint32Array,"%URIError%":l,"%WeakMap%":typeof WeakMap>"u"?r:WeakMap,"%WeakRef%":typeof WeakRef>"u"?r:WeakRef,"%WeakSet%":typeof WeakSet>"u"?r:WeakSet,"%Function.prototype.call%":_,"%Function.prototype.apply%":x,"%Object.defineProperty%":S,"%Object.getPrototypeOf%":L,"%Math.abs%":c,"%Math.floor%":u,"%Math.max%":h,"%Math.min%":d,"%Math.pow%":g,"%Math.round%":f,"%Math.sign%":p,"%Reflect.getPrototypeOf%":A};if(I)try{null.error}catch(oe){var K=I(I(oe));B["%Error.prototype%"]=K}var O=function oe(ue){var Ee;if(ue==="%AsyncFunction%")Ee=y("async function () {}");else if(ue==="%GeneratorFunction%")Ee=y("function* () {}");else if(ue==="%AsyncGeneratorFunction%")Ee=y("async function* () {}");else if(ue==="%AsyncGenerator%"){var de=oe("%AsyncGeneratorFunction%");de&&(Ee=de.prototype)}else if(ue==="%AsyncIteratorPrototype%"){var ae=oe("%AsyncGenerator%");ae&&I&&(Ee=I(ae.prototype))}return B[ue]=Ee,Ee},F={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},M=ur(),V=TE(),$=M.call(_,Array.prototype.concat),C=M.call(x,Array.prototype.splice),H=M.call(_,String.prototype.replace),Q=M.call(_,String.prototype.slice),J=M.call(_,RegExp.prototype.exec),ce=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ie=/\\(\\)?/g,z=function(ue){var Ee=Q(ue,0,1),de=Q(ue,-1);if(Ee==="%"&&de!=="%")throw new a("invalid intrinsic syntax, expected closing `%`");if(de==="%"&&Ee!=="%")throw new a("invalid intrinsic syntax, expected opening `%`");var ae=[];return H(ue,ce,function(ye,Me,j,ee){ae[ae.length]=j?H(ee,ie,"$1"):Me||ye}),ae},ne=function(ue,Ee){var de=ue,ae;if(V(F,de)&&(ae=F[de],de="%"+ae[0]+"%"),V(B,de)){var ye=B[de];if(ye===w&&(ye=O(de)),typeof ye>"u"&&!Ee)throw new o("intrinsic "+ue+" exists, but is not available. Please file an issue!");return{alias:ae,name:de,value:ye}}throw new a("intrinsic "+ue+" does not exist!")};return Ha=function(ue,Ee){if(typeof ue!="string"||ue.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof Ee!="boolean")throw new o('"allowMissing" argument must be a boolean');if(J(/^%?[^%]*%?$/,ue)===null)throw new a("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var de=z(ue),ae=de.length>0?de[0]:"",ye=ne("%"+ae+"%",Ee),Me=ye.name,j=ye.value,ee=!1,W=ye.alias;W&&(ae=W[0],C(de,$([0,1],W)));for(var ge=1,ve=!0;ge<de.length;ge+=1){var Te=de[ge],$e=Q(Te,0,1),tt=Q(Te,-1);if(($e==='"'||$e==="'"||$e==="`"||tt==='"'||tt==="'"||tt==="`")&&$e!==tt)throw new a("property names with quotes must have matching quotes");if((Te==="constructor"||!ve)&&(ee=!0),ae+="."+Te,Me="%"+ae+"%",V(B,Me))j=B[Me];else if(j!=null){if(!(Te in j)){if(!Ee)throw new o("base intrinsic for "+ue+" exists, but the property is not available.");return}if(E&&ge+1>=de.length){var Le=E(j,Te);ve=!!Le,ve&&"get"in Le&&!("originalValue"in Le.get)?j=Le.get:j=j[Te]}else ve=V(j,Te),j=j[Te];ve&&!ee&&(B[Me]=j)}}return j},Ha}var qa,pd;function md(){if(pd)return qa;pd=1;var r=Ka(),e=ud(),t=e([r("%String.prototype.indexOf%")]);return qa=function(s,n){var a=r(s,!!n);return typeof a=="function"&&t(s,".prototype.")>-1?e([a]):a},qa}var Wa,yd;function vd(){if(yd)return Wa;yd=1;var r=Ka(),e=md(),t=cr(),i=_i(),s=r("%Map%",!0),n=e("Map.prototype.get",!0),a=e("Map.prototype.set",!0),o=e("Map.prototype.has",!0),l=e("Map.prototype.delete",!0),c=e("Map.prototype.size",!0);return Wa=!!s&&function(){var h,d={assert:function(g){if(!d.has(g))throw new i("Side channel does not contain "+t(g))},delete:function(g){if(h){var f=l(h,g);return c(h)===0&&(h=void 0),f}return!1},get:function(g){if(h)return n(h,g)},has:function(g){return h?o(h,g):!1},set:function(g,f){h||(h=new s),a(h,g,f)}};return d},Wa}var ja,Ed;function bE(){if(Ed)return ja;Ed=1;var r=Ka(),e=md(),t=cr(),i=vd(),s=_i(),n=r("%WeakMap%",!0),a=e("WeakMap.prototype.get",!0),o=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("WeakMap.prototype.delete",!0);return ja=n?function(){var h,d,g={assert:function(f){if(!g.has(f))throw new s("Side channel does not contain "+t(f))},delete:function(f){if(n&&f&&(typeof f=="object"||typeof f=="function")){if(h)return c(h,f)}else if(i&&d)return d.delete(f);return!1},get:function(f){return n&&f&&(typeof f=="object"||typeof f=="function")&&h?a(h,f):d&&d.get(f)},has:function(f){return n&&f&&(typeof f=="object"||typeof f=="function")&&h?l(h,f):!!d&&d.has(f)},set:function(f,p){n&&f&&(typeof f=="object"||typeof f=="function")?(h||(h=new n),o(h,f,p)):i&&(d||(d=i()),d.set(f,p))}};return g}:i,ja}var Ya,Sd;function Td(){if(Sd)return Ya;Sd=1;var r=_i(),e=cr(),t=Jv(),i=vd(),s=bE(),n=s||i||t;return Ya=function(){var o,l={assert:function(c){if(!l.has(c)){var u=c&&Object(c)===c?"the given object key":e(c);throw new r("Side channel does not contain "+u)}},delete:function(c){return!!o&&o.delete(c)},get:function(c){return o&&o.get(c)},has:function(c){return!!o&&o.has(c)},set:function(c,u){o||(o=n()),o.set(c,u)}};return l},Ya}var za,bd;function Xa(){if(bd)return za;bd=1;var r=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return za={default:t.RFC3986,formatters:{RFC1738:function(i){return r.call(i,e,"+")},RFC3986:function(i){return String(i)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},za}var Qa,Ad;function xd(){if(Ad)return Qa;Ad=1;var r=Xa(),e=Td(),t=zh(),i=Object.prototype.hasOwnProperty,s=Array.isArray,n=e(),a=function(A,x){return n.set(A,x),A},o=function(A){return n.has(A)},l=function(A){return n.get(A)},c=function(A,x){n.set(A,x)},u=(function(){for(var L=[],A=0;A<256;++A)L[L.length]="%"+((A<16?"0":"")+A.toString(16)).toUpperCase();return L})(),h=function(A){for(;A.length>1;){var x=A.pop(),_=x.obj[x.prop];if(s(_)){for(var w=[],G=0;G<_.length;++G)typeof _[G]<"u"&&(w[w.length]=_[G]);x.obj[x.prop]=w}}},d=function(A,x){for(var _=x&&x.plainObjects?{__proto__:null}:{},w=0;w<A.length;++w)typeof A[w]<"u"&&(_[w]=A[w]);return _},g=function(A,x,_){x==="__proto__"&&t?t(A,x,{configurable:!0,enumerable:!0,value:_,writable:!0}):A[x]=_},f=function L(A,x,_){if(!x)return A;if(typeof x!="object"&&typeof x!="function"){if(s(A)){var w=A.length;if(_&&typeof _.arrayLimit=="number"&&w>=_.arrayLimit){if(_.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+_.arrayLimit+" element"+(_.arrayLimit===1?"":"s")+" allowed in an array.");return a(d(A.concat(x),_),w)}A[w]=x}else if(A&&typeof A=="object")if(o(A)){var G=l(A)+1;A[G]=x,c(A,G)}else{if(_&&_.strictMerge)return[A,x];(_&&(_.plainObjects||_.allowPrototypes)||!i.call(Object.prototype,x))&&(A[x]=!0)}else return[A,x];return A}if(!A||typeof A!="object"){if(o(x)){for(var B=Object.keys(x),K=_&&_.plainObjects?{__proto__:null,0:A}:{0:A},O=0;O<B.length;O++){var F=parseInt(B[O],10);K[F+1]=x[B[O]]}return a(K,l(x)+1)}var M=[A].concat(x);if(_&&typeof _.arrayLimit=="number"&&M.length>_.arrayLimit){if(_.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+_.arrayLimit+" element"+(_.arrayLimit===1?"":"s")+" allowed in an array.");return a(d(M,_),M.length-1)}return M}var V=A;if(s(A)&&!s(x)&&(V=d(A,_)),s(A)&&s(x)){if(x.forEach(function($,C){if(i.call(A,C)){var H=A[C];H&&typeof H=="object"&&$&&typeof $=="object"?A[C]=L(H,$,_):A[A.length]=$}else A[C]=$}),_&&typeof _.arrayLimit=="number"&&A.length>_.arrayLimit){if(_.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+_.arrayLimit+" element"+(_.arrayLimit===1?"":"s")+" allowed in an array.");return a(d(A,_),A.length-1)}return A}return Object.keys(x).reduce(function($,C){var H=x[C];if(i.call($,C)?g($,C,L($[C],H,_)):g($,C,H),o(x)&&!o($)&&a($,l(x)),o($)){var Q=parseInt(C,10);String(Q)===C&&Q>=0&&Q>l($)&&c($,Q)}return $},V)},p=function(A,x){return Object.keys(x).reduce(function(_,w){return g(_,w,x[w]),_},A)},m=function(L,A,x){var _=L.replace(/\+/g," ");if(x==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},y=1024,E=function(A,x,_,w,G){if(A.length===0)return A;var B=A;if(typeof A=="symbol"?B=Symbol.prototype.toString.call(A):typeof A!="string"&&(B=String(A)),_==="iso-8859-1")return escape(B).replace(/%u[0-9a-f]{4}/gi,function(H){return"%26%23"+parseInt(H.slice(2),16)+"%3B"});for(var K="",O=0;O<B.length;O+=y){var F=B.length>=y?B.slice(O,O+y):B;if(O+y<B.length){var M=F.charCodeAt(F.length-1);M>=55296&&M<=56319&&(F=F.slice(0,-1),O-=1)}for(var V=[],$=0;$<F.length;++$){var C=F.charCodeAt($);if(C===45||C===46||C===95||C===126||C>=48&&C<=57||C>=65&&C<=90||C>=97&&C<=122||G===r.RFC1738&&(C===40||C===41)){V[V.length]=F.charAt($);continue}if(C<128){V[V.length]=u[C];continue}if(C<2048){V[V.length]=u[192|C>>6]+u[128|C&63];continue}if(C<55296||C>=57344){V[V.length]=u[224|C>>12]+u[128|C>>6&63]+u[128|C&63];continue}$+=1,C=65536+((C&1023)<<10|F.charCodeAt($)&1023),V[V.length]=u[240|C>>18]+u[128|C>>12&63]+u[128|C>>6&63]+u[128|C&63]}K+=V.join("")}return K},S=function(A){for(var x=[{obj:{o:A},prop:"o"}],_=e(),w=0;w<x.length;++w)for(var G=x[w],B=G.obj[G.prop],K=Object.keys(B),O=0;O<K.length;++O){var F=K[O],M=B[F];typeof M=="object"&&M!==null&&!_.has(M)&&(x[x.length]={obj:B,prop:F},_.set(M,!0))}return h(x),A},T=function(A){return Object.prototype.toString.call(A)==="[object RegExp]"},b=function(A){return!A||typeof A!="object"?!1:!!(A.constructor&&typeof A.constructor.isBuffer=="function"&&A.constructor.isBuffer(A))},R=function(A,x,_,w,G){if(o(A)){if(G)throw new RangeError("Array limit exceeded. Only "+_+" element"+(_===1?"":"s")+" allowed in an array.");for(var B=s(x)?x:[x],K=l(A),O=0;O<B.length;++O)K+=1,A[K]=B[O];return c(A,K),A}var F=[].concat(A,x);if(F.length>_){if(G)throw new RangeError("Array limit exceeded. Only "+_+" element"+(_===1?"":"s")+" allowed in an array.");return a(d(F,{plainObjects:w}),F.length-1)}return F},I=function(A,x){if(s(A)){for(var _=[],w=0;w<A.length;w+=1)_[_.length]=x(A[w]);return _}return x(A)};return Qa={arrayToObject:d,assign:p,combine:R,compact:S,decode:m,encode:E,isBuffer:b,isOverflow:o,isRegExp:T,markOverflow:a,maybeMap:I,merge:f},Qa}var Ja,Id;function AE(){if(Id)return Ja;Id=1;var r=Td(),e=xd(),t=Xa(),i=Object.prototype.hasOwnProperty,s={brackets:function(m){return m+"[]"},comma:"comma",indices:function(m,y){return m+"["+y+"]"},repeat:function(m){return m}},n=Array.isArray,a=Array.prototype.push,o=function(p,m){a.apply(p,n(m)?m:[m])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",depth:1/0,encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,filter:void 0,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(m){return l.call(m)},skipNulls:!1,strictNullHandling:!1},h=function(m){return typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="symbol"||typeof m=="bigint"},d={},g=function p(m,y,E,S,T,b,R,I,L,A,x,_,w,G,B,K,O,F,M,V){var $=m;if(V>M)throw new RangeError("Input depth exceeded depth option of "+M);for(var C=F,H=0,Q=!1;(C=C.get(d))!==void 0&&!Q;){var J=C.get(m);if(H+=1,typeof J<"u"){if(J===H)throw new RangeError("Cyclic object value");Q=!0}typeof C.get(d)>"u"&&(H=0)}if($=typeof A=="function"?A(y,$):$,$ instanceof Date?$=w($):E==="comma"&&n($)&&($=e.maybeMap($,function(ee){return ee instanceof Date?w(ee):ee})),$===null){if(b)return B(L&&!K?L(y,u.encoder,O,"key",G):y);$=""}if(h($)||e.isBuffer($)){if(L){var ce=K?y:L(y,u.encoder,O,"key",G);return[B(ce)+"="+B(L($,u.encoder,O,"value",G))]}return[B(y)+"="+B(String($))]}var ie=[];if(typeof $>"u")return ie;var z;if(E==="comma"&&n($))K&&L&&($=e.maybeMap($,function(ee){return ee==null?ee:L(ee)})),z=[{value:$.length>0?$.join(",")||null:void 0}];else if(n(A))z=A;else{var ne=Object.keys($);z=x?ne.sort(x):ne}var oe=I?String(y).replace(/\./g,"%2E"):String(y),ue=S&&n($)&&$.length===1?oe+"[]":oe;if(T&&n($)&&$.length===0&&Object.keys($).length===0)return ue+"[]";for(var Ee=0;Ee<z.length;++Ee){var de=z[Ee],ae=typeof de=="object"&&de&&typeof de.value<"u"?de.value:$[de];if(!(R&&ae===null)){var ye=_&&I?String(de).replace(/\./g,"%2E"):String(de),Me=n($)?typeof E=="function"?E(ue,ye):ue:ue+(_?"."+ye:"["+ye+"]");F.set(m,H);var j=r();j.set(d,F),o(ie,p(ae,Me,E,S,T,b,R,I,E==="comma"&&K&&n($)?null:L,A,x,_,w,G,B,K,O,j,M,V+1))}}return ie},f=function(m){if(!m)return u;if(typeof m.allowEmptyArrays<"u"&&typeof m.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof m.encodeDotInKeys<"u"&&typeof m.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(m.encoder!==null&&typeof m.encoder<"u"&&typeof m.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=m.charset||u.charset;if(typeof m.charset<"u"&&m.charset!=="utf-8"&&m.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var E=t.default;if(typeof m.format<"u"){if(!i.call(t.formatters,m.format))throw new TypeError("Unknown format option provided.");E=m.format}var S=t.formatters[E],T=u.filter;(typeof m.filter=="function"||n(m.filter))&&(T=m.filter);var b;if(m.arrayFormat in s?b=m.arrayFormat:"indices"in m?b=m.indices?"indices":"repeat":b=u.arrayFormat,"commaRoundTrip"in m&&typeof m.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var R=typeof m.allowDots>"u"?m.encodeDotInKeys===!0?!0:u.allowDots:!!m.allowDots;return{addQueryPrefix:typeof m.addQueryPrefix=="boolean"?m.addQueryPrefix:u.addQueryPrefix,allowDots:R,allowEmptyArrays:typeof m.allowEmptyArrays=="boolean"?!!m.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:b,charset:y,charsetSentinel:typeof m.charsetSentinel=="boolean"?m.charsetSentinel:u.charsetSentinel,commaRoundTrip:!!m.commaRoundTrip,delimiter:typeof m.delimiter>"u"?u.delimiter:m.delimiter,depth:typeof m.depth=="number"?m.depth:u.depth,encode:typeof m.encode=="boolean"?m.encode:u.encode,encodeDotInKeys:typeof m.encodeDotInKeys=="boolean"?m.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof m.encoder=="function"?m.encoder:u.encoder,encodeValuesOnly:typeof m.encodeValuesOnly=="boolean"?m.encodeValuesOnly:u.encodeValuesOnly,filter:T,format:E,formatter:S,serializeDate:typeof m.serializeDate=="function"?m.serializeDate:u.serializeDate,skipNulls:typeof m.skipNulls=="boolean"?m.skipNulls:u.skipNulls,sort:typeof m.sort=="function"?m.sort:null,strictNullHandling:typeof m.strictNullHandling=="boolean"?m.strictNullHandling:u.strictNullHandling}};return Ja=function(p,m){var y=p,E=f(m),S,T;typeof E.filter=="function"?(T=E.filter,y=T("",y)):n(E.filter)&&(T=E.filter,S=T);var b=[];if(typeof y!="object"||y===null)return"";var R=s[E.arrayFormat],I=R==="comma"&&E.commaRoundTrip;S||(S=Object.keys(y)),E.sort&&S.sort(E.sort);for(var L=r(),A=0;A<S.length;++A){var x=S[A];if(!(typeof x>"u"||x===null)){var _=y[x];if(!(E.skipNulls&&_===null)){var w=E.encodeDotInKeys?String(x).replace(/\./g,"%2E"):String(x);o(b,g(_,w,R,I,E.allowEmptyArrays,E.strictNullHandling,E.skipNulls,E.encodeDotInKeys,E.encode?E.encoder:null,E.filter,E.sort,E.allowDots,E.serializeDate,E.format,E.formatter,E.encodeValuesOnly,E.charset,L,E.depth,0))}}}var G=b.join(E.delimiter),B=E.addQueryPrefix===!0?"?":"";return E.charsetSentinel&&(E.charset==="iso-8859-1"?B+="utf8=%26%2310003%3B"+E.delimiter:B+="utf8=%E2%9C%93"+E.delimiter),G.length>0?B+G:""},Ja}var Za,Rd;function xE(){if(Rd)return Za;Rd=1;var r=xd(),e=Object.prototype.hasOwnProperty,t=Array.isArray,i={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:r.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictMerge:!0,strictNullHandling:!1,throwOnLimitExceeded:!1},s=function(g){return g.replace(/&#(\d+);/g,function(f,p){return String.fromCharCode(parseInt(p,10))})},n=function(g,f,p){if(g&&typeof g=="string"&&f.comma&&g.indexOf(",")>-1){if(f.throwOnLimitExceeded)for(var m=0,y=g.indexOf(",");y>-1;){if(m+=1,m>=f.arrayLimit)throw new RangeError("Array limit exceeded. Only "+f.arrayLimit+" element"+(f.arrayLimit===1?"":"s")+" allowed in an array.");y=g.indexOf(",",y+1)}return g.split(",")}if(f.throwOnLimitExceeded&&p>=f.arrayLimit)throw new RangeError("Array limit exceeded. Only "+f.arrayLimit+" element"+(f.arrayLimit===1?"":"s")+" allowed in an array.");return g},a="utf8=%26%2310003%3B",o="utf8=%E2%9C%93",l=function(f,p){var m={__proto__:null},y=p.ignoreQueryPrefix?f.replace(/^\?/,""):f;y=y.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var E=p.parameterLimit===1/0?void 0:p.parameterLimit,S=y.split(p.delimiter,p.throwOnLimitExceeded&&typeof E<"u"?E+1:E);if(p.throwOnLimitExceeded&&typeof E<"u"&&S.length>E)throw new RangeError("Parameter limit exceeded. Only "+E+" parameter"+(E===1?"":"s")+" allowed.");var T=-1,b,R=p.charset;if(p.charsetSentinel)for(b=0;b<S.length;++b)S[b].indexOf("utf8=")===0&&(S[b]===o?R="utf-8":S[b]===a&&(R="iso-8859-1"),T=b,b=S.length);for(b=0;b<S.length;++b)if(b!==T){var I=S[b],L=I.indexOf("]="),A=L===-1?I.indexOf("="):L+1,x,_;if(A===-1?(x=p.decoder(I,i.decoder,R,"key"),_=p.strictNullHandling?null:""):(x=p.decoder(I.slice(0,A),i.decoder,R,"key"),x!==null&&(_=r.maybeMap(n(I.slice(A+1),p,t(m[x])?m[x].length:0),function(G){return p.decoder(G,i.decoder,R,"value")}))),_&&p.interpretNumericEntities&&R==="iso-8859-1"&&(_=s(String(_))),I.indexOf("[]=")>-1&&(_=t(_)?[_]:_),p.comma&&t(_)&&_.length>p.arrayLimit&&(_=r.combine([],_,p.arrayLimit,p.plainObjects,p.throwOnLimitExceeded)),x!==null){var w=e.call(m,x);w&&(p.duplicates==="combine"||I.indexOf("[]=")>-1)?m[x]=r.combine(m[x],_,p.arrayLimit,p.plainObjects,p.throwOnLimitExceeded):(!w||p.duplicates==="last")&&(m[x]=_)}}return m},c=function(g,f,p,m){var y=0;if(g.length>0&&g[g.length-1]==="[]"){var E=g.slice(0,-1).join("");y=Array.isArray(f)&&f[E]?f[E].length:0}for(var S=m?f:n(f,p,y),T=g.length-1;T>=0;--T){var b,R=g[T];if(R==="[]"&&p.parseArrays)r.isOverflow(S)?b=S:b=p.allowEmptyArrays&&(S===""||p.strictNullHandling&&S===null)?[]:r.combine([],S,p.arrayLimit,p.plainObjects,p.throwOnLimitExceeded);else{b=p.plainObjects?{__proto__:null}:{};var I=R.charAt(0)==="["&&R.charAt(R.length-1)==="]"?R.slice(1,-1):R,L=p.decodeDotInKeys?I.replace(/%2E/g,"."):I,A=parseInt(L,10),x=!isNaN(A)&&R!==L&&String(A)===L&&A>=0&&p.parseArrays;if(!p.parseArrays&&L==="")b={0:S};else if(x&&A<p.arrayLimit)b=[],b[A]=S;else{if(x&&p.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+p.arrayLimit+" element"+(p.arrayLimit===1?"":"s")+" allowed in an array.");x?(b[A]=S,r.markOverflow(b,A)):L!=="__proto__"&&(b[L]=S)}}S=b}return S},u=function(f,p){var m=p.allowDots?f.replace(/\.([^.[]+)/g,"[$1]"):f;if(p.depth<=0)return!p.plainObjects&&e.call(Object.prototype,m)&&!p.allowPrototypes?void 0:[m];var y=[],E=m.indexOf("["),S=E>=0?m.slice(0,E):m;if(S){if(!p.plainObjects&&e.call(Object.prototype,S)&&!p.allowPrototypes)return;y[y.length]=S}for(var T=m.length,b=E,R=0;b>=0&&R<p.depth;){for(var I=1,L=b+1,A=-1;L<T&&A<0;){var x=m.charCodeAt(L);x===91?I+=1:x===93&&(I-=1,I===0&&(A=L)),L+=1}if(A<0)return y[y.length]="["+m.slice(b)+"]",y;var _=m.slice(b,A+1),w=_.slice(1,-1);if(!p.plainObjects&&e.call(Object.prototype,w)&&!p.allowPrototypes)return;y[y.length]=_,R+=1,b=m.indexOf("[",A+1)}if(b>=0){if(p.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+p.depth+" and strictDepth is true");y[y.length]="["+m.slice(b)+"]"}return y},h=function(f,p,m,y){if(f){var E=u(f,m);if(E)return c(E,p,m,y)}},d=function(f){if(!f)return i;if(typeof f.allowEmptyArrays<"u"&&typeof f.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof f.decodeDotInKeys<"u"&&typeof f.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(f.decoder!==null&&typeof f.decoder<"u"&&typeof f.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof f.charset<"u"&&f.charset!=="utf-8"&&f.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(typeof f.throwOnLimitExceeded<"u"&&typeof f.throwOnLimitExceeded!="boolean")throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var p=typeof f.charset>"u"?i.charset:f.charset,m=typeof f.duplicates>"u"?i.duplicates:f.duplicates;if(m!=="combine"&&m!=="first"&&m!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var y=typeof f.allowDots>"u"?f.decodeDotInKeys===!0?!0:i.allowDots:!!f.allowDots;return{allowDots:y,allowEmptyArrays:typeof f.allowEmptyArrays=="boolean"?!!f.allowEmptyArrays:i.allowEmptyArrays,allowPrototypes:typeof f.allowPrototypes=="boolean"?f.allowPrototypes:i.allowPrototypes,allowSparse:typeof f.allowSparse=="boolean"?f.allowSparse:i.allowSparse,arrayLimit:typeof f.arrayLimit=="number"?f.arrayLimit:i.arrayLimit,charset:p,charsetSentinel:typeof f.charsetSentinel=="boolean"?f.charsetSentinel:i.charsetSentinel,comma:typeof f.comma=="boolean"?f.comma:i.comma,decodeDotInKeys:typeof f.decodeDotInKeys=="boolean"?f.decodeDotInKeys:i.decodeDotInKeys,decoder:typeof f.decoder=="function"?f.decoder:i.decoder,delimiter:typeof f.delimiter=="string"||r.isRegExp(f.delimiter)?f.delimiter:i.delimiter,depth:typeof f.depth=="number"||f.depth===!1?+f.depth:i.depth,duplicates:m,ignoreQueryPrefix:f.ignoreQueryPrefix===!0,interpretNumericEntities:typeof f.interpretNumericEntities=="boolean"?f.interpretNumericEntities:i.interpretNumericEntities,parameterLimit:typeof f.parameterLimit=="number"?f.parameterLimit:i.parameterLimit,parseArrays:f.parseArrays!==!1,plainObjects:typeof f.plainObjects=="boolean"?f.plainObjects:i.plainObjects,strictDepth:typeof f.strictDepth=="boolean"?!!f.strictDepth:i.strictDepth,strictMerge:typeof f.strictMerge=="boolean"?!!f.strictMerge:i.strictMerge,strictNullHandling:typeof f.strictNullHandling=="boolean"?f.strictNullHandling:i.strictNullHandling,throwOnLimitExceeded:typeof f.throwOnLimitExceeded=="boolean"?f.throwOnLimitExceeded:!1}};return Za=function(g,f){var p=d(f);if(g===""||g===null||typeof g>"u")return p.plainObjects?{__proto__:null}:{};for(var m=typeof g=="string"?l(g,p):g,y=p.plainObjects?{__proto__:null}:{},E=Object.keys(m),S=0;S<E.length;++S){var T=E[S],b=h(T,m[T],p,typeof g=="string");y=r.merge(y,b,p)}return p.allowSparse===!0?y:r.compact(y)},Za}var eo,Ld;function IE(){if(Ld)return eo;Ld=1;var r=AE(),e=xE(),t=Xa();return eo={formats:t,parse:e,stringify:r},eo}var RE=IE();const LE=zv(RE);function _d(r,e){return function(){return r.apply(e,arguments)}}const{toString:_E}=Object.prototype,{getPrototypeOf:Jt}=Object,{iterator:os,toStringTag:Pd}=Symbol,ls=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),Dd=r=>typeof r=="string"&&(r==="__proto__"||r==="constructor"||r==="prototype"),wd=(r,e,t)=>r===Object.prototype||!t&&e===null,PE=r=>{if(!Object.isExtensible(r))return!1;const e=Object.getOwnPropertyNames(r);return Object.getOwnPropertySymbols&&e.push(...Object.getOwnPropertySymbols(r)),e.every(t=>{if(Dd(t))return!1;const i=Object.getOwnPropertyDescriptor(r,t);return!!i&&i.configurable&&i.writable===!0})},cs=(r,e)=>{let t=r;const i=[];for(;t!=null;){if(i.indexOf(t)!==-1)return!1;i.push(t);const s=Jt(t);if(wd(t,s,t===r))return!1;if(ls(t,e))return!0;t=s}return!1},DE=(r,e)=>r!=null&&cs(r,e)?r[e]:void 0,wE=r=>{if(r==null||typeof r!="object"&&typeof r!="function")return r;const e=Jt(r);if(e===null&&PE(r))return r;const t=Object.create(null),i=Object.create(null),s=[];let n=r;for(;n!=null&&s.indexOf(n)===-1;){s.push(n);const a=n===r?e:Jt(n);if(wd(n,a,n===r))break;const o=Object.getOwnPropertyNames(n);Object.getOwnPropertySymbols&&o.push(...Object.getOwnPropertySymbols(n));for(const l of o)Dd(l)||ls(i,l)||(t[l]=r[l],i[l]=!0);n=a}return t},to=(r=>e=>{const t=_E.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Tt=r=>(r=r.toLowerCase(),e=>to(e)===r),hr=r=>e=>typeof e===r,{isArray:ci}=Array,ui=hr("undefined");function Pi(r){return r!==null&&!ui(r)&&r.constructor!==null&&!ui(r.constructor)&&ot(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const Cd=Tt("ArrayBuffer");function CE(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&Cd(r.buffer),e}const kE=hr("string"),ot=hr("function"),kd=hr("number"),Di=r=>r!==null&&typeof r=="object",OE=r=>r===!0||r===!1,dr=r=>{if(!Di(r))return!1;const e=Jt(r);return(e===null||e===Object.prototype||Jt(e)===null)&&!cs(r,Pd)&&!cs(r,os)},FE=r=>{if(!Di(r)||Pi(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},ME=Tt("Date"),NE=Tt("File"),BE=r=>!!(r&&typeof r.uri<"u"),UE=r=>r&&typeof r.getParts<"u",$E=Tt("Blob"),GE=Tt("FileList"),VE=Tt("Set"),HE=r=>Di(r)&&ot(r.pipe);function KE(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const Od=KE(),Fd=typeof Od.FormData<"u"?Od.FormData:void 0,qE=r=>{if(!r)return!1;if(Fd&&r instanceof Fd)return!0;const e=Jt(r);if(!e||e===Object.prototype||!ot(r.append))return!1;const t=to(r);return t==="formdata"||t==="object"&&ot(r.toString)&&r.toString()==="[object FormData]"},WE=Tt("URLSearchParams"),[jE,YE,zE,XE]=["ReadableStream","Request","Response","Headers"].map(Tt),QE=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function us(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let i,s;if(typeof r!="object"&&(r=[r]),ci(r))for(i=0,s=r.length;i<s;i++)e.call(null,r[i],i,r);else{if(Pi(r))return;const n=t?Object.getOwnPropertyNames(r):Object.keys(r),a=n.length;let o;for(i=0;i<a;i++)o=n[i],e.call(null,r[o],o,r)}}function Md(r,e){if(Pi(r))return null;e=e.toLowerCase();const t=Object.keys(r);let i=t.length,s;for(;i-- >0;)if(s=t[i],e===s.toLowerCase())return s;return null}const hi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nd=r=>!ui(r)&&r!==hi;function io(...r){const{caseless:e,skipUndefined:t}=Nd(this)&&this||{},i={},s=(n,a)=>{if(a==="__proto__"||a==="constructor"||a==="prototype")return;const o=e&&typeof a=="string"&&Md(i,a)||a,l=ls(i,o)?i[o]:void 0;dr(l)&&dr(n)?i[o]=io(l,n):dr(n)?i[o]=io({},n):ci(n)?i[o]=n.slice():(!t||!ui(n))&&(i[o]=n)};for(let n=0,a=r.length;n<a;n++){const o=r[n];if(!o||Pi(o)||(us(o,s),typeof o!="object"||ci(o)))continue;const l=Object.getOwnPropertySymbols(o);for(let c=0;c<l.length;c++){const u=l[c];cS.call(o,u)&&s(o[u],u)}}return i}const JE=(r,e,t,{allOwnKeys:i}={})=>(us(e,(s,n)=>{t&&ot(s)?Object.defineProperty(r,n,{__proto__:null,value:_d(s,t),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(r,n,{__proto__:null,value:s,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),r),ZE=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),eS=(r,e,t,i)=>{r.prototype=Object.create(e.prototype,i),Object.defineProperty(r.prototype,"constructor",{__proto__:null,value:r,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(r,"super",{__proto__:null,value:e.prototype}),t&&Object.assign(r.prototype,t)},tS=(r,e,t,i)=>{let s,n,a;const o={};if(e=e||{},r==null)return e;do{for(s=Object.getOwnPropertyNames(r),n=s.length;n-- >0;)a=s[n],(!i||i(a,r,e))&&!o[a]&&(e[a]=r[a],o[a]=!0);r=t!==!1&&Jt(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},iS=(r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const i=r.indexOf(e,t);return i!==-1&&i===t},sS=r=>{if(!r)return null;if(ci(r))return r;let e=r.length;if(!kd(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},rS=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&Jt(Uint8Array)),nS=(r,e)=>{const i=(r&&r[os]).call(r);let s;for(;(s=i.next())&&!s.done;){const n=s.value;e.call(r,n[0],n[1])}},aS=(r,e)=>{let t;const i=[];for(;(t=r.exec(e))!==null;)i.push(t);return i},oS=Tt("HTMLFormElement"),lS=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,i,s){return i.toUpperCase()+s}),{propertyIsEnumerable:cS}=Object.prototype,uS=Tt("RegExp"),Bd=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),i={};us(t,(s,n)=>{let a;(a=e(s,n,r))!==!1&&(i[n]=a||s)}),Object.defineProperties(r,i)},hS=r=>{Bd(r,(e,t)=>{if(ot(r)&&["arguments","caller","callee"].includes(t))return!1;const i=r[t];if(ot(i)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},dS=(r,e)=>{const t={},i=s=>{s.forEach(n=>{t[n]=!0})};return ci(r)?i(r):i(String(r).split(e)),t},fS=()=>{},gS=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function pS(r){return!!(r&&ot(r.append)&&r[Pd]==="FormData"&&r[os])}const mS=r=>{const e=new WeakSet,t=i=>{if(Di(i)){if(e.has(i))return;if(Pi(i))return i;if(!("toJSON"in i)){e.add(i);let s;if(VE(i)){s=[];for(const n of i){const a=t(n);!ui(a)&&s.push(a)}}else s=ci(i)?[]:{},us(i,(n,a)=>{const o=t(n);!ui(o)&&(s[a]=o)});return e.delete(i),s}}return i};return t(r)},yS=Tt("AsyncFunction"),vS=r=>r&&(Di(r)||ot(r))&&ot(r.then)&&ot(r.catch),Ud=((r,e)=>r?setImmediate:e?((t,i)=>(hi.addEventListener("message",({source:s,data:n})=>{s===hi&&n===t&&i.length&&i.shift()()},!1),s=>{i.push(s),hi.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",ot(hi.postMessage)),ES=typeof queueMicrotask<"u"?queueMicrotask.bind(hi):typeof process<"u"&&process.nextTick||Ud,$d=r=>r!=null&&ot(r[os]),P={isArray:ci,isArrayBuffer:Cd,isBuffer:Pi,isFormData:qE,isArrayBufferView:CE,isString:kE,isNumber:kd,isBoolean:OE,isObject:Di,isPlainObject:dr,isEmptyObject:FE,isReadableStream:jE,isRequest:YE,isResponse:zE,isHeaders:XE,isUndefined:ui,isDate:ME,isFile:NE,isReactNativeBlob:BE,isReactNative:UE,isBlob:$E,isRegExp:uS,isFunction:ot,isStream:HE,isURLSearchParams:WE,isTypedArray:rS,isFileList:GE,forEach:us,merge:io,extend:JE,trim:QE,stripBOM:ZE,inherits:eS,toFlatObject:tS,kindOf:to,kindOfTest:Tt,endsWith:iS,toArray:sS,forEachEntry:nS,matchAll:aS,isHTMLForm:oS,hasOwnProperty:ls,hasOwnProp:ls,hasOwnInPrototypeChain:cs,getSafeProp:DE,toSafeFlatObject:wE,reduceDescriptors:Bd,freezeMethods:hS,toObjectSet:dS,toCamelCase:lS,noop:fS,toFiniteNumber:gS,findKey:Md,global:hi,isContextDefined:Nd,isSpecCompliantForm:pS,toJSONObject:mS,isAsyncFn:yS,isThenable:vS,setImmediate:Ud,asap:ES,isIterable:$d,isSafeIterable:r=>r!=null&&cs(r,os)&&$d(r)},SS=P.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),TS=r=>{const e={};let t,i,s;return r&&r.split(`
112
- `).forEach(function(a){s=a.indexOf(":"),t=a.substring(0,s).trim().toLowerCase(),i=a.substring(s+1).trim();const o=P.hasOwnProp(e,t);!t||o&&P.hasOwnProp(SS,t)||(t==="set-cookie"?o?e[t].push(i):e[t]=[i]:e[t]=o?e[t]+", "+i:i)}),e};function bS(r){let e=0,t=r.length;for(;e<t;){const i=r.charCodeAt(e);if(i!==9&&i!==32)break;e+=1}for(;t>e;){const i=r.charCodeAt(t-1);if(i!==9&&i!==32)break;t-=1}return e===0&&t===r.length?r:r.slice(e,t)}const AS=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),xS=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function so(r,e){return P.isArray(r)?r.map(t=>so(t,e)):bS(String(r).replace(e,""))}const IS=r=>so(r,AS),RS=r=>so(r,xS);function Gd(r){const e=Object.create(null);return P.forEach(r.toJSON(),(t,i)=>{e[i]=RS(t)}),e}const Vd=Symbol("internals");function hs(r){return r&&String(r).trim().toLowerCase()}function fr(r){return r===!1||r==null?r:P.isArray(r)?r.map(fr):IS(String(r))}function LS(r){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=t.exec(r);)e[i[1]]=i[2];return e}const _S=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function ro(r){let e=0,t=r.length;for(;e<t;){const i=r.charCodeAt(e);if(i!==9&&i!==32)break;e+=1}for(;t>e;){const i=r.charCodeAt(t-1);if(i!==9&&i!==32)break;t-=1}return e===0&&t===r.length?r:r.slice(e,t)}function PS(r){const e=r.length-1;if(e<1||r.charCodeAt(0)!==34||r.charCodeAt(e)!==34)return r;let t="";for(let i=1;i<e;i++){const s=r.charCodeAt(i);if(s===34||s===92&&(i+=1,i>=e))return r;t+=r[i]}return t}function DS(r){const e=Object.create(null),t=String(r);let i=0,s=!1,n=!1;function a(o){const l=ro(t.slice(i,o)),c=l.indexOf("=");if(c<1)return;const u=ro(l.slice(0,c));if(!_S.test(u))return;const h=u.toLowerCase();if(h==="__proto__"||h==="constructor"||h==="prototype")return;const d=ro(l.slice(c+1));e[h]=PS(d)}for(let o=0;o<t.length;o++){const l=t.charCodeAt(o);s?n?n=!1:l===92?n=!0:l===34&&(s=!1):l===34?s=!0:(l===44||l===59)&&(a(o),i=o+1)}return a(t.length),e}const wS=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function no(r,e,t,i,s){if(P.isFunction(i))return i.call(this,e,t);if(s&&(e=t),!!P.isString(e)){if(P.isString(i))return e.indexOf(i)!==-1;if(P.isRegExp(i))return i.test(e)}}function CS(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,i)=>t.toUpperCase()+i)}function kS(r,e){const t=P.toCamelCase(" "+e);["get","set","has"].forEach(i=>{Object.defineProperty(r,i+t,{__proto__:null,value:function(s,n,a){return this[i].call(this,e,s,n,a)},configurable:!0})})}let Ze=class{constructor(e){e&&this.set(e)}set(e,t,i){const s=this;function n(o,l,c){const u=hs(l);if(!u)return;const h=P.findKey(s,u);(!h||s[h]===void 0||c===!0||c===void 0&&s[h]!==!1)&&(s[h||l]=fr(o))}const a=(o,l)=>P.forEach(o,(c,u)=>n(c,u,l));if(P.isPlainObject(e)||e instanceof this.constructor)a(e,t);else if(P.isString(e)&&(e=e.trim())&&!wS(e))a(TS(e),t);else if(P.isObject(e)&&P.isSafeIterable(e)){let o=Object.create(null),l,c;for(const u of e){if(!P.isArray(u))throw new TypeError("Object iterator must return a key-value pair");c=u[0],P.hasOwnProp(o,c)?(l=o[c],o[c]=P.isArray(l)?[...l,u[1]]:[l,u[1]]):o[c]=u[1]}a(o,t)}else e!=null&&n(t,e,i);return this}get(e,t){if(e=hs(e),e){const i=P.findKey(this,e);if(i){const s=this[i];if(!t)return s;if(t===!0)return LS(s);if(P.isFunction(t))return t.call(this,s,i);if(P.isRegExp(t))return t.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=hs(e),e){const i=P.findKey(this,e);return!!(i&&this[i]!==void 0&&(!t||no(this,this[i],i,t)))}return!1}delete(e,t){const i=this;let s=!1;function n(a){if(a=hs(a),a){const o=P.findKey(i,a);o&&(!t||no(i,i[o],o,t))&&(delete i[o],s=!0)}}return P.isArray(e)?e.forEach(n):n(e),s}clear(e){const t=Object.keys(this);let i=t.length,s=!1;for(;i--;){const n=t[i];(!e||no(this,this[n],n,e,!0))&&(delete this[n],s=!0)}return s}normalize(e){const t=this,i={};return P.forEach(this,(s,n)=>{const a=P.findKey(i,n);if(a){t[a]=fr(s),delete t[n];return}const o=e?CS(n):String(n).trim();o!==n&&delete t[n],t[o]=fr(s),i[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return P.forEach(this,(i,s)=>{i!=null&&i!==!1&&(t[s]=e&&P.isArray(i)?i.join(", "):i)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(`
113
- `)}getSetCookie(){const e=this.get("set-cookie");return P.isArray(e)?e:e==null||e===!1?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return DS(e)}static concat(e,...t){const i=new this(e);return t.forEach(s=>i.set(s)),i}static accessor(e){const i=(this[Vd]=this[Vd]={accessors:{}}).accessors,s=this.prototype;function n(a){const o=hs(a);i[o]||(kS(s,a),i[o]=!0)}return P.isArray(e)?e.forEach(n):n(e),this}};Ze.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),P.reduceDescriptors(Ze.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(i){this[t]=i}}}),P.freezeMethods(Ze);const gr="[REDACTED ****]";function OS(r){if(P.hasOwnProp(r,"toJSON"))return!0;let e=Object.getPrototypeOf(r);for(;e&&e!==Object.prototype;){if(P.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function FS(r,e){const t=new Set(e.map(n=>String(n).toLowerCase())),i=[],s=n=>{if(n===null||typeof n!="object"||P.isBuffer(n))return n;if(i.indexOf(n)!==-1)return;n instanceof Ze&&(n=n.toJSON()),i.push(n);let a;if(P.isArray(n))a=[],n.forEach((o,l)=>{const c=s(o);P.isUndefined(c)||(a[l]=c)});else{if(!P.isPlainObject(n)&&OS(n))return i.pop(),n;a=Object.create(null);for(const[o,l]of Object.entries(n)){const c=t.has(o.toLowerCase())?gr:s(l);P.isUndefined(c)||(a[o]=c)}}return i.pop(),a};return s(r)}function Hd(r){try{return String(r)}catch{return""}}function MS(r){return r.errors.map(t=>{try{return t&&t.message?Hd(t.message):Hd(t)}catch{return""}}).filter(Boolean).join("; ")||r.name||"AggregateError"}let X=class Cf extends Error{static from(e,t,i,s,n,a){let o=e.message;!o&&P.isArray(e.errors)&&e.errors.length&&(o=MS(e));const l=new Cf(o,t||e.code,i,s,n);return Object.defineProperty(l,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),l.name=e.name,e.status!=null&&l.status==null&&(l.status=e.status),a&&Object.assign(l,a),l}constructor(e,t,i,s,n){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),i&&(this.config=i),s&&(this.request=s),n&&(this.response=n,this.status=n.status)}toJSON(){const e=this.config,t=e&&P.hasOwnProp(e,"redact")?e.redact:void 0,i=P.isArray(t)&&t.length>0?FS(e,t):P.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:i,code:this.code,status:this.status}}};X.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",X.ERR_BAD_OPTION="ERR_BAD_OPTION",X.ECONNABORTED="ECONNABORTED",X.ETIMEDOUT="ETIMEDOUT",X.ECONNREFUSED="ECONNREFUSED",X.ERR_NETWORK="ERR_NETWORK",X.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",X.ERR_DEPRECATED="ERR_DEPRECATED",X.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",X.ERR_BAD_REQUEST="ERR_BAD_REQUEST",X.ERR_CANCELED="ERR_CANCELED",X.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",X.ERR_INVALID_URL="ERR_INVALID_URL",X.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const NS=null,Kd=100;function ao(r){return P.isPlainObject(r)||P.isArray(r)}function qd(r){return P.endsWith(r,"[]")?r.slice(0,-2):r}function oo(r,e,t){return r?r.concat(e).map(function(s,n){return s=qd(s),!t&&n?"["+s+"]":s}).join(t?".":""):e}function BS(r){return P.isArray(r)&&!r.some(ao)}const US=P.toFlatObject(P,{},null,function(e){return/^is[A-Z]/.test(e)});function pr(r,e,t){if(!P.isObject(r))throw new TypeError("target must be an object");e=e||new FormData;const i=(E,S)=>{const T=P.getSafeProp(t,E);return P.isUndefined(T)?S:T},s=i("metaTokens",!0),n=i("visitor")||p,a=i("dots",!1),o=i("indexes",!1),l=i("Blob")||typeof Blob<"u"&&Blob,c=i("maxDepth",Kd),u=l&&P.isSpecCompliantForm(e),h=[];if(!P.isFunction(n))throw new TypeError("visitor must be a function");function d(E){if(E===null)return"";if(P.isDate(E))return E.toISOString();if(P.isBoolean(E))return E.toString();if(!u&&P.isBlob(E))throw new X("Blob is not supported. Use a Buffer instead.");if(P.isArrayBuffer(E)||P.isTypedArray(E)){if(u&&typeof l=="function")return new l([E]);throw new X("Blob is not supported. Use a Buffer instead.",X.ERR_NOT_SUPPORT)}return E}function g(E){if(E>c)throw new X("Object is too deeply nested ("+E+" levels). Max depth: "+c,X.ERR_FORM_DATA_DEPTH_EXCEEDED)}function f(E,S){if(c===1/0)return JSON.stringify(E);const T=[];return JSON.stringify(E,function(R,I){if(!P.isObject(I))return I;for(;T.length&&T[T.length-1]!==this;)T.pop();return T.push(I),g(S+T.length-1),I})}function p(E,S,T){let b=E;if(P.isReactNative(e)&&P.isReactNativeBlob(E))return e.append(oo(T,S,a),d(E)),!1;if(E&&!T&&typeof E=="object"){if(P.endsWith(S,"{}"))S=s?S:S.slice(0,-2),E=f(E,1);else if(P.isArray(E)&&BS(E)||(P.isFileList(E)||P.endsWith(S,"[]"))&&(b=P.toArray(E)))return S=qd(S),b.forEach(function(I,L){!(P.isUndefined(I)||I===null)&&e.append(o===!0?oo([S],L,a):o===null?S:S+"[]",d(I))}),!1}return ao(E)?!0:(e.append(oo(T,S,a),d(E)),!1)}const m=Object.assign(US,{defaultVisitor:p,convertValue:d,isVisitable:ao});function y(E,S,T=0){if(!P.isUndefined(E)){if(g(T),h.indexOf(E)!==-1)throw new Error("Circular reference detected in "+S.join("."));h.push(E),P.forEach(E,function(R,I){(!(P.isUndefined(R)||R===null)&&n.call(e,R,P.isString(I)?I.trim():I,S,m))===!0&&y(R,S?S.concat(I):[I],T+1)}),h.pop()}}if(!P.isObject(r))throw new TypeError("data must be an object");return y(r),e}function Wd(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(r).replace(/[!'()~]|%20/g,function(i){return e[i]})}function lo(r,e){this._pairs=[],r&&pr(r,this,e)}const jd=lo.prototype;jd.append=function(e,t){this._pairs.push([e,t])},jd.toString=function(e){const t=e?i=>e.call(this,i,Wd):Wd;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function $S(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Yd(r,e,t){if(!e)return r;r=r||"";const i=P.isFunction(t)?{serialize:t}:t,s=P.getSafeProp(i,"encode")||$S,n=P.getSafeProp(i,"serialize");let a;if(n?a=n(e,i):a=P.isURLSearchParams(e)?e.toString():new lo(e,i).toString(s),a){const o=r.indexOf("#");o!==-1&&(r=r.slice(0,o)),r+=(r.indexOf("?")===-1?"?":"&")+a}return r}const ds=Symbol("internals");function zd(r){return r?r.length:0}function Xd(r){if(r)for(;r.length&&r[r.length-1]===null;)r.pop()}function fs(r,e){const t=r.handlers,i=zd(t);t!==e.handlersRef?(e.handlersRef=t,e.handlerEntries.clear()):i!==e.handlersLength&&(i?e.handlerEntries.forEach(function(n,a){t[n.index]!==n.handler&&e.handlerEntries.delete(a)}):e.handlerEntries.clear()),e.handlersLength=i}class Qd{constructor(){this.handlers=[],this[ds]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(e,t,i){const s={fulfilled:e,rejected:t,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null},n=this[ds];this.handlers==null&&(this.handlers=[]),fs(this,n);const a=n.nextId++;return this.handlers.push(s),n.handlerEntries.set(a,{handler:s,index:this.handlers.length-1}),n.handlersLength=this.handlers.length,a}eject(e){const t=this[ds];fs(this,t);const i=t.handlerEntries.get(e);if(i){if(t.handlerEntries.delete(e),this.handlers[i.index]!==i.handler)return;this.handlers[i.index]=null,t.iterationDepth||(Xd(this.handlers),t.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],fs(this,this[ds]))}forEach(e){const t=this[ds];fs(this,t),t.iterationDepth++;try{P.forEach(this.handlers,function(s){s!==null&&e(s)})}finally{--t.iterationDepth||(fs(this,t),Xd(this.handlers),t.handlersLength=zd(this.handlers))}}}const co={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},GS={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:lo,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},uo=typeof window<"u"&&typeof document<"u",ho=typeof navigator=="object"&&navigator||void 0,VS=uo&&(!ho||["ReactNative","NativeScript","NS"].indexOf(ho.product)<0),HS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",KS=uo&&window.location.href||"http://localhost",qe={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:uo,hasStandardBrowserEnv:VS,hasStandardBrowserWebWorkerEnv:HS,navigator:ho,origin:KS},Symbol.toStringTag,{value:"Module"})),...GS};function qS(r,e){return pr(r,new qe.classes.URLSearchParams,{visitor:function(t,i,s,n){return qe.isNode&&P.isBuffer(t)?(this.append(i,t.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...e})}const Jd=Kd;function Zd(r){if(r>Jd)throw new X("FormData field is too deeply nested ("+r+" levels). Max depth: "+Jd,X.ERR_FORM_DATA_DEPTH_EXCEEDED)}function WS(r){const e=[],t=/[^.[\]]+|\[([^.[\]]*)]/g;let i;for(;(i=t.exec(r))!==null;)Zd(e.length),e.push(i[0]==="[]"?"":i[1]||i[0]);return e}function jS(r){const e={},t=Object.keys(r);let i;const s=t.length;let n;for(i=0;i<s;i++)n=t[i],e[n]=r[n];return e}function ef(r){function e(t,i,s,n){Zd(n);let a=t[n++];if(a==="__proto__")return!0;const o=Number.isFinite(+a),l=n>=t.length;return a=!a&&P.isArray(s)?s.length:a,l?(P.hasOwnProp(s,a)?s[a]=P.isArray(s[a])?s[a].concat(i):[s[a],i]:s[a]=i,!o):((!P.hasOwnProp(s,a)||!P.isObject(s[a]))&&(s[a]=[]),e(t,i,s[a],n)&&P.isArray(s[a])&&(s[a]=jS(s[a])),!o)}if(P.isFormData(r)&&P.isFunction(r.entries)){const t={};return P.forEachEntry(r,(i,s)=>{e(WS(i),s,t,0)}),t}return null}const tf=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),wi=(r,e)=>r!=null&&P.hasOwnProp(r,e)?r[e]:void 0;function YS(r,e,t){if(P.isString(r))try{return(e||JSON.parse)(r),P.trim(r)}catch(i){if(i.name!=="SyntaxError")throw i}return(t||JSON.stringify)(r)}const gs={transitional:co,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const i=t.getContentType()||"",s=i.indexOf("application/json")>-1,n=P.isObject(e);if(n&&P.isHTMLForm(e)&&(e=new FormData(e)),P.isFormData(e))return s?JSON.stringify(ef(e)):e;if(P.isArrayBuffer(e)||P.isBuffer(e)||P.isStream(e)||P.isFile(e)||P.isBlob(e)||P.isReadableStream(e))return e;if(P.isArrayBufferView(e))return e.buffer;if(P.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(n){const l=wi(this,"formSerializer");if(i.indexOf("application/x-www-form-urlencoded")>-1)return qS(e,l).toString();if((o=P.isFileList(e))||i.indexOf("multipart/form-data")>-1){const c=wi(this,"env"),u=c&&c.FormData;return pr(o?{"files[]":e}:e,u&&new u,l)}}return n||s?(t.setContentType("application/json",!1),YS(e)):e}],transformResponse:[function(e){const t=wi(this,"transitional")||gs.transitional,i=t&&t.forcedJSONParsing,s=wi(this,"responseType"),n=s==="json";if(P.isResponse(e)||P.isReadableStream(e))return e;if(e&&P.isString(e)&&(i&&!s||n)){const o=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e,wi(this,"parseReviver"))}catch(l){if(o)throw l.name==="SyntaxError"?X.from(l,X.ERR_BAD_RESPONSE,this,null,wi(this,"response")):l}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:qe.classes.FormData,Blob:qe.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};P.forEach(tf,r=>{gs.headers[r]={}});function fo(r,e){const t=this||gs,i=e||t,s=Ze.from(i.headers);let n=i.data;return P.forEach(r,function(o){n=o.call(t,n,s.normalize(),e?e.status:void 0)}),s.normalize(),n}function sf(r){return!!(r&&r.__CANCEL__)}let ps=class extends X{constructor(e,t,i){super(e??"canceled",X.ERR_CANCELED,t,i),this.name="CanceledError",this.__CANCEL__=!0}};function rf(r,e,t){const i=t.config.validateStatus;!t.status||!i||i(t.status)?r(t):e(new X("Request failed with status code "+t.status,t.status>=400&&t.status<500?X.ERR_BAD_REQUEST:X.ERR_BAD_RESPONSE,t.config,t.request,t))}const zS=/[\t\n\r]/g;function nf(r){if(typeof r!="string")return r;let e=0;for(;e<r.length&&r.charCodeAt(e)<=32;)e++;return r.slice(e).replace(zS,"")}function go(r){const e=/^([-+\w]{1,25}):(?:\/\/)?/.exec(r);return e&&e[1]||""}function XS(r,e){r=r||10;const t=new Array(r),i=new Array(r);let s=0,n=0,a;return e=e!==void 0?e:1e3,function(l){const c=Date.now(),u=i[n];a||(a=c),t[s]=l,i[s]=c;let h=n,d=0;for(;h!==s;)d+=t[h++],h=h%r;if(s=(s+1)%r,s===n&&(n=(n+1)%r),c-a<e)return;const g=u&&c-u;return g?Math.round(d*1e3/g):void 0}}function QS(r,e){let t=0,i=1e3/e,s,n;const a=(u,h=Date.now())=>{t=h,s=null,n&&(clearTimeout(n),n=null),r(...u)};return[(...u)=>{const h=Date.now(),d=h-t;d>=i?a(u,h):(s=u,n||(n=setTimeout(()=>{n=null,a(s)},i-d)))},()=>s&&a(s),(...u)=>a(u)]}const mr=(r,e,t=3)=>{let i=0;const s=XS(50,250);return QS(n=>{if(!n||!P.isNumber(n.loaded))return;const a=n.loaded,o=n.lengthComputable?n.total:void 0,l=Math.max(0,o!=null?Math.min(a,o):a),c=Math.max(0,l-i),u=s(c);i=Math.max(i,l);const h={loaded:l,total:o,progress:o?l/o:void 0,bytes:c,rate:u||void 0,estimated:u&&o?(o-l)/u:void 0,event:n,lengthComputable:o!=null,[e?"download":"upload"]:!0};r(h)},t)},af=(r,e)=>{const t=r!=null;return[i=>e[0]({lengthComputable:t,total:r,loaded:i}),e[1]]},of=(r,e=P.asap)=>(...t)=>e(()=>r(...t)),JS=qe.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,qe.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(qe.origin),qe.navigator&&/(msie|trident)/i.test(qe.navigator.userAgent)):()=>!0,ZS=qe.hasStandardBrowserEnv?{write(r,e,t,i,s,n,a){if(typeof document>"u")return;const o=[`${r}=${encodeURIComponent(e)}`];P.isNumber(t)&&o.push(`expires=${new Date(t).toUTCString()}`),P.isString(i)&&o.push(`path=${i}`),P.isString(s)&&o.push(`domain=${s}`),n===!0&&o.push("secure"),P.isString(a)&&o.push(`SameSite=${a}`),document.cookie=o.join("; ")},read(r){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let t=0;t<e.length;t++){const i=e[t].replace(/^\s+/,""),s=i.indexOf("=");if(s!==-1&&i.slice(0,s)===r)try{return decodeURIComponent(i.slice(s+1))}catch{return i.slice(s+1)}}return null},remove(r){this.write(r,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function eT(r){return typeof r!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function tT(r,e){if(!e)return r;let t=r.length;for(;t>0&&r.charCodeAt(t-1)===47;)t--;return r.slice(0,t)+"/"+e.replace(/^\/+/,"")}const iT=/^https?:(?!\/\/)/i;function sT(r){return r&&r.replace(/(^|&)([^=&]*=)?[^&]+/g,(e,t,i="")=>`${t}${i}${gr}`)}function rT(r){const e=r.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${gr}@`),t=e.indexOf("#"),s=(t===-1?e:e.slice(0,t)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${gr}`);return t===-1?s:`${s}#${sT(e.slice(t+1))}`}function lf(r,e){if(typeof r=="string"){const t=nf(r);if(iT.test(t))throw new X(`Invalid URL ${JSON.stringify(rT(t))}: missing "//" after protocol`,X.ERR_INVALID_URL,e)}}function cf(r,e,t,i){lf(e,i);let s=!eT(e);return r&&(s||t===!1)?(lf(r,i),tT(r,e)):e}const uf=r=>r instanceof Ze?{...r}:r,nT=r=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(r).concat(Object.getOwnPropertySymbols(r).filter(e=>Object.getOwnPropertyDescriptor(r,e).enumerable)):Object.keys(r);function di(r,e){r=r||{},e=e||{};const t=Object.create(null);Object.defineProperty(t,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function i(u,h,d,g){return P.isPlainObject(u)&&P.isPlainObject(h)?P.merge.call({caseless:g},u,h):P.isPlainObject(h)?P.merge({},h):P.isArray(h)?h.slice():h}function s(u,h,d,g){if(P.isUndefined(h)){if(!P.isUndefined(u))return i(void 0,u,d,g)}else return i(u,h,d,g)}function n(u,h){if(!P.isUndefined(h))return i(void 0,h)}function a(u,h){if(P.isUndefined(h)){if(!P.isUndefined(u))return i(void 0,u)}else return i(void 0,h)}function o(u){const h=P.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!P.isUndefined(h))if(P.isPlainObject(h)){if(P.hasOwnProp(h,u))return h[u]}else return;const d=P.hasOwnProp(r,"transitional")?r.transitional:void 0;if(P.isPlainObject(d)&&P.hasOwnProp(d,u))return d[u]}function l(u,h,d){if(P.hasOwnProp(e,d))return i(u,h);if(P.hasOwnProp(r,d))return i(void 0,u)}const c={url:n,method:n,data:n,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutErrorMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,allowedSocketPaths:a,responseEncoding:a,validateStatus:l,headers:(u,h,d)=>s(uf(u),uf(h),d,!0)};return P.forEach(nT({...r,...e}),function(h){if(h==="__proto__"||h==="constructor"||h==="prototype")return;const d=P.hasOwnProp(c,h)?c[h]:s,g=P.hasOwnProp(r,h)?r[h]:void 0,f=P.hasOwnProp(e,h)?e[h]:void 0,p=d(g,f,h);P.isUndefined(p)&&d!==l||(t[h]=p)}),P.hasOwnProp(e,"validateStatus")&&P.isUndefined(e.validateStatus)&&o("validateStatusUndefinedResolves")===!1&&(P.hasOwnProp(r,"validateStatus")?t.validateStatus=i(void 0,r.validateStatus):delete t.validateStatus),t}const aT=["content-type","content-length"];function oT(r,e,t){if(t!=="content-only"){r.set(e);return}Object.entries(e||{}).forEach(([i,s])=>{aT.includes(i.toLowerCase())&&r.set(i,s)})}const lT=r=>encodeURIComponent(r).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16)));function hf(r){const e=di({},r),t=d=>P.hasOwnProp(e,d)?e[d]:void 0,i=t("data");let s=t("withXSRFToken");const n=t("xsrfHeaderName"),a=t("xsrfCookieName");let o=t("headers");const l=t("auth"),c=t("baseURL"),u=t("allowAbsoluteUrls"),h=t("url");if(e.headers=o=Ze.from(o),e.url=Yd(cf(c,h,u,e),t("params"),t("paramsSerializer")),l){const d=P.getSafeProp(l,"username")||"",g=P.getSafeProp(l,"password")||"";try{o.set("Authorization","Basic "+btoa(d+":"+(g?lT(g):"")))}catch(f){throw X.from(f,X.ERR_BAD_OPTION_VALUE,r)}}if(P.isFormData(i)){const d=P.getSafeProp(i,"getHeaders");qe.hasStandardBrowserEnv||qe.hasStandardBrowserWebWorkerEnv||P.isReactNative(i)?o.setContentType(void 0):P.isFunction(d)&&oT(o,d.call(i),t("formDataHeaderPolicy"))}if(qe.hasStandardBrowserEnv&&(P.isFunction(s)&&(s=s(e)),s===!0||s==null&&JS(e.url))){const g=n&&a&&ZS.read(a);g&&o.set(n,g)}return e}const cT=typeof XMLHttpRequest<"u"&&function(r){return new Promise(function(t,i){const s=hf(r);let n=s.data;const a=Ze.from(s.headers).normalize();let{responseType:o,onUploadProgress:l,onDownloadProgress:c}=s,u,h,d,g,f,p;function m(){g&&g(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(u),s.signal&&s.signal.removeEventListener("abort",u)}let y=new XMLHttpRequest;y.open(s.method.toUpperCase(),s.url,!0),y.timeout=s.timeout;function E(T){if(!y)return;if(y.status===0&&(go(nf(s.url))||go(qe.origin))!=="file"&&!(y.responseURL&&y.responseURL.startsWith("file:"))){i(new X("Request aborted",X.ECONNABORTED,r,y)),m(),y=null;return}try{T?p&&p(T):f&&f()}catch(L){setTimeout(()=>{throw L})}if(!y)return;const b=Ze.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),I={data:!o||o==="text"||o==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:b,config:r,request:y};rf(function(A){t(A),m()},function(A){i(A),m()},I),y=null}"onloadend"in y?y.onloadend=E:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.startsWith("file:"))||setTimeout(E)},y.onabort=function(){y&&(i(new X("Request aborted",X.ECONNABORTED,r,y)),m(),y=null)},y.onerror=function(b){const R=b&&b.message?b.message:"Network Error",I=new X(R,X.ERR_NETWORK,r,y);I.event=b||null,i(I),m(),y=null},y.ontimeout=function(){let b=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const R=s.transitional||co;s.timeoutErrorMessage&&(b=s.timeoutErrorMessage),i(new X(b,R.clarifyTimeoutError?X.ETIMEDOUT:X.ECONNABORTED,r,y)),m(),y=null},n===void 0&&a.setContentType(null),"setRequestHeader"in y&&P.forEach(Gd(a),function(b,R){y.setRequestHeader(R,b)}),P.isUndefined(s.withCredentials)||(y.withCredentials=!!s.withCredentials),o&&o!=="json"&&(y.responseType=s.responseType),c&&([d,f,p]=mr(c,!0),y.addEventListener("progress",d)),l&&y.upload&&([h,g]=mr(l),y.upload.addEventListener("progress",h),y.upload.addEventListener("loadend",g)),(s.cancelToken||s.signal)&&(u=T=>{y&&(i(!T||T.type?new ps(null,r,y):T),y.abort(),m(),y=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));const S=go(s.url);if(S&&!qe.protocols.includes(S)){i(new X("Unsupported protocol "+S+":",X.ERR_BAD_REQUEST,r)),m();return}y.send(n||null)})},uT=(r,e)=>{if(r=r?r.filter(Boolean):[],!e&&!r.length)return;const t=new AbortController;let i=!1;const s=function(l){if(!i){i=!0,a();const c=l instanceof Error?l:this.reason;t.abort(c instanceof X?c:new ps(c instanceof Error?c.message:c))}};let n=e&&setTimeout(()=>{n=null,s(new X(`timeout of ${e}ms exceeded`,X.ETIMEDOUT))},e);const a=()=>{r&&(n&&clearTimeout(n),n=null,r.forEach(l=>{l.unsubscribe?l.unsubscribe(s):l.removeEventListener("abort",s)}),r=null)};r.forEach(l=>{if(!i){if(l.aborted){s.call(l);return}l.addEventListener("abort",s,{once:!0})}});const{signal:o}=t;return o.unsubscribe=()=>P.asap(a),o},hT=function*(r,e){let t=r.byteLength;if(t<e){yield r;return}let i=0,s;for(;i<t;)s=i+e,yield r.slice(i,s),i=s},dT=async function*(r,e){for await(const t of fT(r))yield*hT(t,e)},fT=async function*(r){if(r[Symbol.asyncIterator]){yield*r;return}const e=r.getReader();try{for(;;){const{done:t,value:i}=await e.read();if(t)break;yield i}}finally{await e.cancel()}},df=(r,e,t,i)=>{const s=dT(r,e);let n=0,a,o=l=>{a||(a=!0,i&&i(l))};return new ReadableStream({async pull(l){try{const{done:c,value:u}=await s.next();if(c){o(),l.close();return}let h=u.byteLength;if(t){let d=n+=h;t(d)}l.enqueue(new Uint8Array(u))}catch(c){throw o(c),c}},cancel(l){return o(l),s.return()}},{highWaterMark:2})},ff=r=>r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102,gf=(r,e,t)=>e+2<t&&ff(r.charCodeAt(e+1))&&ff(r.charCodeAt(e+2)),pf=r=>r<=57?r-48:(r&223)-55,gT=r=>r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||r===43||r===47||r===45||r===95,pT=r=>r===9||r===10||r===12||r===13||r===32,mT=r=>{const e=Math.floor(r/4),t=r%4;return e*3+(t===2?1:t===3?2:0)},yT=r=>{const e=r.length;let t=0;return e>0&&r.charCodeAt(e-1)===61&&(t++,e>1&&r.charCodeAt(e-2)===61&&t++),Math.floor((e-t)*3/4)},vT=r=>{const e=r.length;let t=0,i=0,s=!1;for(let n=0;n<e;n++){let a=r.charCodeAt(n);if(a===37&&gf(r,n,e)&&(a=pf(r.charCodeAt(n+1))*16+pf(r.charCodeAt(n+2)),n+=2),!pT(a)){if(a===61){i++;continue}if(!gT(a)||i>0){s=!0;continue}t++}}return s||i>2||i>0&&(t+i)%4!==0||t%4===1?yT(r):mT(t)},ET=(r,e)=>{if(!r||typeof r!="string"||!r.startsWith("data:"))return 0;const t=r.indexOf(",");if(t<0)return 0;const i=r.slice(5,t),s=r.slice(t+1);if(/;base64/i.test(i))return e(s);let a=0;for(let o=0,l=s.length;o<l;o++){const c=s.charCodeAt(o);if(c===37&&gf(s,o,l))a+=1,o+=2;else if(c<128)a+=1;else if(c<2048)a+=2;else if(c>=55296&&c<=56319&&o+1<l){const u=s.charCodeAt(o+1);u>=56320&&u<=57343?(a+=4,o++):a+=3}else a+=3}return a};function ST(r){const e=typeof r=="string"?r.indexOf("#"):-1;return ET(e===-1?r:r.slice(0,e),vT)}const po="1.20.0",mf=64*1024,TT={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:yr}=P,bT=r=>encodeURIComponent(r).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16))),yf=r=>{if(!P.isString(r))return r;try{return decodeURIComponent(r)}catch{return r}},vf=(r,...e)=>{try{return!!r(...e)}catch{return!1}},AT=r=>{const e=r.indexOf("://");let t=r;return e!==-1&&(t=t.slice(e+3)),t.includes("@")||t.includes(":")},xT=r=>{const e=P.global!==void 0&&P.global!==null?P.global:globalThis,{ReadableStream:t,TextEncoder:i}=e;r=P.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},r);const{fetch:s,Request:n,Response:a}=r,o=s?yr(s):typeof fetch=="function",l=yr(n),c=yr(a);if(!o)return!1;const u=o&&yr(t),h=o&&(typeof i=="function"?(y=>E=>y.encode(E))(new i):async y=>new Uint8Array(await new n(y).arrayBuffer())),d=l&&u&&vf(()=>{let y=!1;const E=new n(qe.origin,{body:new t,method:"POST",get duplex(){return y=!0,"half"}}),S=E.headers.has("Content-Type");return E.body!=null&&E.body.cancel(),y&&!S}),g=c&&u&&vf(()=>P.isReadableStream(new a("").body)),f={stream:g&&(y=>y.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(y=>{!f[y]&&(f[y]=(E,S)=>{let T=E&&E[y];if(T)return T.call(E);throw new X(`Response type '${y}' is not supported`,X.ERR_NOT_SUPPORT,S)})});const p=async y=>{if(y==null)return 0;if(P.isBlob(y))return y.size;if(P.isSpecCompliantForm(y))return(await new n(qe.origin,{method:"POST",body:y}).arrayBuffer()).byteLength;if(P.isArrayBufferView(y)||P.isArrayBuffer(y))return y.byteLength;if(P.isURLSearchParams(y)&&(y=y+""),P.isString(y))return(await h(y)).byteLength},m=async(y,E)=>{const S=P.toFiniteNumber(y.getContentLength());return S??p(E)};return async y=>{let{url:E,method:S,data:T,signal:b,cancelToken:R,timeout:I,onDownloadProgress:L,onUploadProgress:A,responseType:x,headers:_,withCredentials:w="same-origin",fetchOptions:G,maxContentLength:B,maxBodyLength:K,maxRedirects:O}=hf(y);const F=P.isNumber(B)&&B>-1,M=P.isNumber(K)&&K>-1,V=z=>P.hasOwnProp(y,z)?y[z]:void 0;let $=s||fetch;x=x?(x+"").toLowerCase():"text";let C=uT([b,R&&R.toAbortSignal()],I),H=null;const Q=C&&C.unsubscribe&&(()=>{C.unsubscribe()});let J,ce=null;const ie=()=>new X("Request body larger than maxBodyLength limit",X.ERR_BAD_REQUEST,y,H);try{let z;const ne=V("auth");if(ne){const W=P.getSafeProp(ne,"username")||"",ge=P.getSafeProp(ne,"password")||"";z={username:W,password:ge}}if(AT(E)){const W=new URL(E,qe.origin);if(!z&&(W.username||W.password)){const ge=yf(W.username),ve=yf(W.password);z={username:ge,password:ve}}(W.username||W.password)&&(W.username="",W.password="",E=W.href)}if(z&&(_.delete("authorization"),_.set("Authorization","Basic "+btoa(bT((z.username||"")+":"+(z.password||""))))),F&&typeof E=="string"&&E.startsWith("data:")&&ST(E)>B)throw new X("maxContentLength size of "+B+" exceeded",X.ERR_BAD_RESPONSE,y,H);if(M&&S!=="get"&&S!=="head"){const W=await p(T);if(typeof W=="number"&&isFinite(W)&&(J=W,W>K))throw ie()}const oe=M&&(P.isReadableStream(T)||P.isStream(T)),ue=(W,ge,ve)=>df(W,mf,Te=>{if(M&&Te>K)throw ce=ie();ge&&ge(Te)},ve);if(d&&S!=="get"&&S!=="head"&&(A||oe)){if(J=J??await m(_,T),J!==0||oe){let W=new n(E,{method:"POST",body:T,duplex:"half"}),ge;if(P.isFormData(T)&&(ge=W.headers.get("content-type"))&&_.setContentType(ge),W.body){const[ve,Te]=A&&af(J,mr(of(A)))||[];T=ue(W.body,ve,Te)}}}else if(oe&&!l&&u&&S!=="get"&&S!=="head")T=ue(T);else if(oe&&l&&!d&&S!=="get"&&S!=="head")throw new X("Stream request bodies are not supported by the current fetch implementation",X.ERR_NOT_SUPPORT,y,H);P.isString(w)||(w=w?"include":"omit");const Ee=l&&"credentials"in n.prototype;if(P.isFormData(T)){const W=_.getContentType();W&&/^multipart\/form-data/i.test(W)&&!/boundary=/i.test(W)&&_.delete("content-type")}_.set("User-Agent","axios/"+po,!1);const de=G==null?G:Object.assign(Object.create(null),G);de&&(delete de.body,delete de.headers,delete de.method,delete de.signal,delete de.duplex,delete de.credentials);const ae=Object.assign(Object.create(null),de,{signal:C,method:S.toUpperCase(),headers:Gd(_.normalize()),body:T,duplex:"half",credentials:Ee?w:void 0});l&&(P.forEach(TT,(W,ge)=>{ae[ge]===void 0&&(ae[ge]=W)}),ae.signal===void 0&&(ae.signal=null),ae.body===void 0&&(ae.body=null)),O===0&&(ae.redirect="manual",de&&(de.redirect="manual")),H=l&&new n(E,ae);let ye=await(l?$(H,de):$(E,ae));const Me=Ze.from(ye.headers);if(F){const W=P.toFiniteNumber(Me.getContentLength());if(W!=null&&W>B)throw new X("maxContentLength size of "+B+" exceeded",X.ERR_BAD_RESPONSE,y,H)}const j=g&&(x==="stream"||x==="response");if(g&&ye.body&&(L||F||j&&Q)){const W={};["status","statusText","headers"].forEach(Le=>{W[Le]=ye[Le]});const ge=P.toFiniteNumber(Me.getContentLength()),[ve,Te]=L&&af(ge,mr(of(L),!0))||[];let $e=0;const tt=Le=>{if(F&&($e=Le,$e>B))throw new X("maxContentLength size of "+B+" exceeded",X.ERR_BAD_RESPONSE,y,H);ve&&ve(Le)};ye=new a(df(ye.body,mf,tt,()=>{Te&&Te(),Q&&Q()}),W)}x=x||"text";let ee=await f[P.findKey(f,x)||"text"](ye,y);if(F&&!g&&!j){let W;if(ee!=null&&(typeof ee.byteLength=="number"?W=ee.byteLength:typeof ee.size=="number"?W=ee.size:typeof ee=="string"&&(W=typeof i=="function"?new i().encode(ee).byteLength:ee.length)),typeof W=="number"&&W>B)throw new X("maxContentLength size of "+B+" exceeded",X.ERR_BAD_RESPONSE,y,H)}return!j&&Q&&Q(),await new Promise((W,ge)=>{rf(W,ge,{data:ee,headers:Ze.from(ye.headers),status:ye.status,statusText:ye.statusText,config:y,request:H})})}catch(z){if(Q&&Q(),C&&C.aborted&&C.reason instanceof X){const ne=C.reason;throw ne.config=y,H&&(ne.request=H),z!==ne&&Object.defineProperty(ne,"cause",{__proto__:null,value:z,writable:!0,enumerable:!1,configurable:!0}),ne}if(ce)throw H&&!ce.request&&(ce.request=H),ce;if(z instanceof X)throw H&&!z.request&&(z.request=H),z;if(z&&z.name==="TypeError"&&/Load failed|fetch/i.test(z.message)){const ne=new X("Network Error",X.ERR_NETWORK,y,H,z&&z.response);throw Object.defineProperty(ne,"cause",{__proto__:null,value:z.cause||z,writable:!0,enumerable:!1,configurable:!0}),ne}throw X.from(z,z&&z.code,y,H,z&&z.response)}}},IT=new Map,Ef=r=>{let e=r&&r.env||{};const{fetch:t,Request:i,Response:s}=e,n=[i,s,t];let a=n.length,o=a,l,c,u=IT;for(;o--;)l=n[o],c=u.get(l),c===void 0&&u.set(l,c=o?new Map:xT(e)),u=c;return c};Ef();const mo={http:NS,xhr:cT,fetch:{get:Ef}};P.forEach(mo,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(r,"adapterName",{__proto__:null,value:e})}});const Sf=r=>`- ${r}`,RT=r=>P.isFunction(r)||r===null||r===!1;function LT(r,e){r=P.isArray(r)?r:[r];const{length:t}=r;let i,s;const n={};for(let a=0;a<t;a++){i=r[a];let o;if(s=i,!RT(i)&&(s=mo[(o=String(i)).toLowerCase()],s===void 0))throw new X(`Unknown adapter '${o}'`);if(s&&(P.isFunction(s)||(s=s.get(e))))break;n[o||"#"+a]=s}if(!s){const a=Object.entries(n).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let o=t?a.length>1?`since :
114
- `+a.map(Sf).join(`
115
- `):" "+Sf(a[0]):"as no adapter specified";throw new X("There is no suitable adapter to dispatch the request "+o,X.ERR_NOT_SUPPORT)}return s}const Tf={getAdapter:LT,adapters:mo};function yo(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new ps(null,r)}function vo(r){const e=P.toSafeFlatObject(r);return yo(e),e.headers=Ze.from(P.getSafeProp(e,"headers")),e.data=fo.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Tf.getAdapter(e.adapter||gs.adapter,e)(e).then(function(s){yo(e),e.response=s;try{s.data=fo.call(e,e.transformResponse,s)}finally{delete e.response}return s.headers=Ze.from(s.headers),s},function(s){if(!sf(s)&&(yo(e),s&&s.response)){e.response=s.response;try{s.response.data=fo.call(e,e.transformResponse,s.response)}finally{delete e.response}s.response.headers=Ze.from(s.response.headers)}return Promise.reject(s)})}const vr={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{vr[r]=function(i){return typeof i===r||"a"+(e<1?"n ":" ")+r}});const bf={};vr.transitional=function(e,t,i){function s(n,a){return"[Axios v"+po+"] Transitional option '"+n+"'"+a+(i?". "+i:"")}return(n,a,o)=>{if(e===!1)throw new X(s(a," has been removed"+(t?" in "+t:"")),X.ERR_DEPRECATED);return t&&!bf[a]&&(bf[a]=!0,console.warn(s(a," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(n,a,o):!0}},vr.spelling=function(e){return(t,i)=>(console.warn(`${i} is likely a misspelling of ${e}`),!0)};function _T(r,e,t){if(typeof r!="object"||r===null)throw new X("options must be an object",X.ERR_BAD_OPTION_VALUE);const i=Object.keys(r);let s=i.length;for(;s-- >0;){const n=i[s],a=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(a){const o=r[n],l=o===void 0||a(o,n,r);if(l!==!0)throw new X("option "+n+" must be "+l,X.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new X("Unknown option "+n,X.ERR_BAD_OPTION)}}const Er={assertOptions:_T,validators:vr},et=Er.validators;let fi=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Qd,response:new Qd}}async request(e,t){try{return await this._request(e,t)}catch(i){if(i instanceof Error)try{let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const n=s.stack;let a="";if(typeof n=="string"){const o=n.indexOf(`
116
- `);a=o===-1?"":n.slice(o+1)}if(!i.stack)i.stack=a;else if(a){const o=a.indexOf(`
117
- `),l=o===-1?-1:a.indexOf(`
118
- `,o+1),c=l===-1?"":a.slice(l+1);String(i.stack).endsWith(c)||(i.stack+=`
119
- `+a)}}catch{}throw i}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=di(this.defaults,t);const{transitional:i,paramsSerializer:s,headers:n}=t;i!==void 0&&Er.assertOptions(i,{silentJSONParsing:et.transitional(et.boolean),forcedJSONParsing:et.transitional(et.boolean),clarifyTimeoutError:et.transitional(et.boolean),legacyInterceptorReqResOrdering:et.transitional(et.boolean),advertiseZstdAcceptEncoding:et.transitional(et.boolean),validateStatusUndefinedResolves:et.transitional(et.boolean)},!1),s!=null&&(P.isFunction(s)?t.paramsSerializer={serialize:s}:Er.assertOptions(s,{encode:et.function,serialize:et.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Er.assertOptions(t,{baseUrl:et.spelling("baseURL"),withXsrfToken:et.spelling("withXSRFToken")},!0),t.method=(P.getSafeProp(t,"method")||P.getSafeProp(this.defaults,"method")||"get").toLowerCase();let a=n&&P.merge(n.common,n[t.method]);n&&P.forEach(tf.concat("common"),f=>{delete n[f]}),t.headers=Ze.concat(a,n);const o=[];let l=!0;this.interceptors.request.forEach(function(p){if(typeof p.runWhen=="function"&&p.runWhen(t)===!1)return;l=l&&p.synchronous;const m=t.transitional||co;m&&m.legacyInterceptorReqResOrdering?o.unshift(p.fulfilled,p.rejected):o.push(p.fulfilled,p.rejected)});const c=[];this.interceptors.response.forEach(function(p){c.push(p.fulfilled,p.rejected)});let u,h=0,d;if(!l){const f=[vo.bind(this),void 0];for(f.unshift(...o),f.push(...c),d=f.length,u=Promise.resolve(t);h<d;)u=u.then(f[h++],f[h++]);return u}d=o.length;let g=t;for(;h<d;){const f=o[h++],p=o[h++];try{g=f?f(g):g}catch(m){if(!p){u=Promise.reject(m);break}try{const y=p.call(this,m);P.isThenable(y)&&(u=Promise.resolve(y).then(()=>vo.call(this,g)))}catch(y){u=Promise.reject(y)}break}}if(!u)try{u=vo.call(this,g)}catch(f){u=Promise.reject(f)}for(h=0,d=c.length;h<d;)u=u.then(c[h++],c[h++]);return u}getUri(e){e=di(this.defaults,e);const t=cf(e.baseURL,e.url,e.allowAbsoluteUrls,e);return Yd(t,e.params,e.paramsSerializer)}};P.forEach(["delete","get","head","options"],function(e){fi.prototype[e]=function(t,i){return this.request(di(i||{},{method:e,url:t,data:i&&P.hasOwnProp(i,"data")?i.data:void 0}))}}),P.forEach(["post","put","patch","query"],function(e){function t(i){return function(n,a,o){return this.request(di(o||{},{method:e,headers:i?{"Content-Type":"multipart/form-data"}:{},url:n,data:a}))}}fi.prototype[e]=t(),e!=="query"&&(fi.prototype[e+"Form"]=t(!0))});let PT=class kf{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(n){t=n});const i=this;this.promise.then(s=>{if(!i._listeners)return;let n=i._listeners.length;for(;n-- >0;)i._listeners[n](s);i._listeners=null}),this.promise.then=s=>{let n;const a=new Promise(o=>{i.subscribe(o),n=o}).then(s);return a.cancel=function(){i.unsubscribe(n)},a},e(function(n,a,o){i.reason||(i.reason=new ps(n,a,o),t(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=i=>{e.abort(i)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new kf(function(s){e=s}),cancel:e}}};function DT(r){return function(t){return r.apply(null,t)}}function wT(r){return P.isObject(r)&&r.isAxiosError===!0}const Sr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Sr).forEach(([r,e])=>{Sr[e]===void 0&&(Sr[e]=r)});function Af(r){const e=new fi(r),t=_d(fi.prototype.request,e);return P.extend(t,fi.prototype,e,{allOwnKeys:!0}),P.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return Af(di(r,s))},t}const Ue=Af(gs);Ue.Axios=fi,Ue.CanceledError=ps,Ue.CancelToken=PT,Ue.isCancel=sf,Ue.VERSION=po,Ue.toFormData=pr,Ue.AxiosError=X,Ue.Cancel=Ue.CanceledError,Ue.all=function(e){return Promise.all(e)},Ue.spread=DT,Ue.isAxiosError=wT,Ue.mergeConfig=di,Ue.AxiosHeaders=Ze,Ue.formToJSON=r=>ef(P.isHTMLForm(r)?new FormData(r):r),Ue.getAdapter=Tf.getAdapter,Ue.HttpStatusCode=Sr,Ue.default=Ue;const{Axios:sb,AxiosError:rb,CanceledError:nb,isCancel:ab,CancelToken:ob,VERSION:lb,all:cb,Cancel:ub,isAxiosError:hb,spread:db,toFormData:fb,AxiosHeaders:gb,HttpStatusCode:pb,formToJSON:mb,getAdapter:yb,mergeConfig:vb,create:Eb}=Ue;class Eo{constructor(e){vt(this,"get",(e,t,i={})=>new Promise((s,n)=>{this.instance({url:e,method:"GET",params:t,...i}).then(a=>{s(a)}).catch(a=>{n(a)})}));vt(this,"post",(e,t,i)=>new Promise((s,n)=>{const a={};i?i==="json"?a["Content-Type"]="application/json":a["Content-Type"]="multipart/form-data":(t=LE.stringify(t),a["Content-Type"]="application/x-www-form-urlencoded"),this.instance({url:e,method:"POST",data:t,headers:a}).then(o=>{s(o)}).catch(o=>{n(o)})}));this.instance=Ue.create({baseURL:e||"",timeout:1e4}),this.instance.interceptors.request.use(t=>t),this.instance.interceptors.response.use(t=>{const{code:i,message:s}=t.data;return i&&i===200?Promise.resolve(t.data):Promise.reject(s)},t=>(console.log(t),Promise.reject(t)))}}class Ci{static fetchUrls(e,t){return new Eo().get(`${e}?appid=${t}&all_play_url=true`)}static sortUrls(e){return e.sort((t,i)=>t.file_size-i.file_size)}static markSources(e){return e.map(t=>{const i=Number(t.source_type??t.sourceType),s=Number(t.source_storage_id??t.sourceStorageId);return{...t,source_type:i,source_storage_id:s,isLine2:i===8&&s===4}})}static findLine2Source(e=[]){if(!e||!e.length)return null;const t=e.find(i=>i.isLine2&&i.url);return t||e.find(i=>Number(i.source_type??i.sourceType)===8&&Number(i.source_storage_id??i.sourceStorageId)===4&&i.url)||null}static probeSource(e){const t=performance.now();return fetch(e.url,{method:"GET",headers:{Accept:"application/vnd.apple.mpegurl, */*"}}).then(async i=>{const s=await i.text(),n=i.ok&&/#EXTM3U/i.test(s);return{ok:n,durationMs:Math.round(performance.now()-t),url:e.url,content:n?s:null,isLine2:!!e.isLine2,source:e}}).catch(()=>({ok:!1,durationMs:Math.round(performance.now()-t),url:e.url,content:null,isLine2:!!e.isLine2,source:e}))}static raceFastestSource(e=[],t,i){const s=(e||[]).filter(o=>o&&o.url);if(!s.length)return Promise.resolve({winner:null,results:[]});if(s.length===1){const o=s[0],l={ok:!0,durationMs:0,url:o.url,skipped:!0,isLine2:!!o.isLine2,source:o};return typeof t=="function"&&t(o,l),Promise.resolve({winner:o,results:[l]})}let n=!1;const a=s.map(o=>this.probeSource(o).then(l=>(l.ok&&l.content&&i&&(i[l.url]=l.content),l.ok&&!n&&(n=!0,typeof t=="function"&&t(o,l)),l)));return Promise.all(a).then(o=>{const l=o.filter(u=>u.ok&&u.content).sort((u,h)=>u.durationMs-h.durationMs);return{winner:l.length?l[0].source:null,results:o}})}static putWinnerFirst(e,t){if(!t||!e||!e.length)return e||[];const i=e.filter(s=>s&&s.url!==t.url);return[t,...i]}static async ableUrls(e){const t=await this.fetchUrls(e.sourceURL,e.appId);return this.markSources(this.sortUrls(t.data.play_urls||[]))}}class CT{constructor(e,t){this.video=e,this.container=t,this.canvas=document.createElement("canvas"),this.canvas.className="ylc-video-canvas-mirror",this.canvas.setAttribute("data-ylc","canvas-mirror"),this.ctx=this.canvas.getContext("2d",{alpha:!1}),this.running=!1,this.destroyed=!1,this.failed=!1,this.raf=0,this.vfc=0,this._onPlay=()=>this.start(),this._onPause=()=>{this.draw(),this.stop()},this._onFrame=()=>this.draw(),this._onResize=()=>this.resize(),this._onFs=()=>this.exitNativeFullscreen(),this.hideVideo(),this.resize(),this.bind()}hideVideo(){const e=this.video;e.setAttribute("t7-video-player-type","inline"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-video-player-fullscreen","false"),e.controls=!1,e.removeAttribute("controls"),e.style.cssText=["position:fixed","left:-9999px","top:0","width:16px","height:16px","opacity:0.01","pointer-events:none","z-index:-1","object-fit:contain"].join(";")}restoreVideo(){const e=this.video;e.style.cssText=["position:relative","z-index:0","width:100%","height:100%","background:#000","overflow:hidden","object-fit:contain","pointer-events:none"].join(";"),this.canvas&&this.canvas.parentNode&&(this.canvas.style.display="none")}bind(){this.video.addEventListener("play",this._onPlay),this.video.addEventListener("playing",this._onPlay),this.video.addEventListener("pause",this._onPause),this.video.addEventListener("ended",this._onPause),this.video.addEventListener("seeked",this._onFrame),this.video.addEventListener("loadeddata",this._onFrame),window.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFs),document.addEventListener("webkitfullscreenchange",this._onFs),this.video.addEventListener("webkitbeginfullscreen",this._onFs),typeof ResizeObserver<"u"&&(this.ro=new ResizeObserver(this._onResize),this.ro.observe(this.container))}unbind(){this.video.removeEventListener("play",this._onPlay),this.video.removeEventListener("playing",this._onPlay),this.video.removeEventListener("pause",this._onPause),this.video.removeEventListener("ended",this._onPause),this.video.removeEventListener("seeked",this._onFrame),this.video.removeEventListener("loadeddata",this._onFrame),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFs),document.removeEventListener("webkitfullscreenchange",this._onFs),this.video.removeEventListener("webkitbeginfullscreen",this._onFs),this.ro&&(this.ro.disconnect(),this.ro=null)}exitNativeFullscreen(e){e&&typeof e.preventDefault=="function"&&e.preventDefault();try{this.video.webkitExitFullScreen&&this.video.webkitExitFullScreen()}catch{}try{document.fullscreenElement&&document.exitFullscreen(),document.webkitFullscreenElement&&document.webkitExitFullscreen&&document.webkitExitFullscreen()}catch{}}resize(){if(this.destroyed||!this.container)return;const e=this.container.getBoundingClientRect(),t=Math.min(window.devicePixelRatio||1,2),i=Math.max(1,Math.floor(e.width*t)),s=Math.max(1,Math.floor(e.height*t));(this.canvas.width!==i||this.canvas.height!==s)&&(this.canvas.width=i,this.canvas.height=s,this.draw())}draw(){if(this.destroyed||this.failed||!this.ctx)return;const e=this.canvas.width,t=this.canvas.height,i=this.video.videoWidth,s=this.video.videoHeight;if(this.ctx.fillStyle="#000",this.ctx.fillRect(0,0,e,t),!i||!s)return;const n=Math.min(e/i,t/s),a=i*n,o=s*n,l=(e-a)/2,c=(t-o)/2;try{this.ctx.drawImage(this.video,l,c,a,o)}catch{this.failed=!0,this.stop(),this.restoreVideo()}}start(){this.running||this.destroyed||this.failed||(this.running=!0,this.loop())}loop(){!this.running||this.destroyed||this.failed||(this.draw(),typeof this.video.requestVideoFrameCallback=="function"?this.vfc=this.video.requestVideoFrameCallback(()=>this.loop()):this.raf=requestAnimationFrame(()=>this.loop()))}stop(){if(this.running=!1,this.vfc&&typeof this.video.cancelVideoFrameCallback=="function")try{this.video.cancelVideoFrameCallback(this.vfc)}catch{}this.vfc=0,this.raf&&cancelAnimationFrame(this.raf),this.raf=0}destroy(){this.destroyed=!0,this.stop(),this.unbind(),this.ctx=null,this.video=null,this.container=null,this.canvas=null}}class So{constructor(e,t={}){if(this.containerId=e,this.options={sourceURL:"",poster:"",autoplay:!1,controls:!0,muted:!1,loop:!1,preload:"metadata",width:"100%",height:"100%",...t},this.hlsInstance=null,this.playUrls=null,this.currentLine=1,this._destroyed=!1,this.controlBar=null,this._handleFullscreenChange=null,this._isSeeking=!1,this._seekTarget=null,!this.containerId){me.error("VideoPlayer日志-未传节点id",{containerId:e});return}const i=document.querySelector("#"+e);i||me.error("VideoPlayer日志-未查询到节点",{containerId:e,elTmp:i}),me.info("VideoPlayer日志-开始事件和节点初始化",{containerId:e,options:{...this.options,fullscreenElement:""}}),this.el=i,this.events=new Bv(this),this.clearPlayer(),this.init(),me.info("VideoPlayer日志-canVideoPlayHevcHls",{canVideoPlayHevcHls:Dv(),browser:navigator.userAgent,options:this.options})}init(){this.createPlayerContainer(),this.setVideoSource(),this.bindEvents()}createPlayerContainer(){if(this.el.innerHTML="",ar.mount(this),Rv()||ta()){this.canvasMirror=new CT(this.videoElm,this.container);const e=this.touchMask;e?this.container.insertBefore(this.canvasMirror.canvas,e):this.container.appendChild(this.canvasMirror.canvas),me.info("VideoPlayer日志-启用canvas镜像防浏览器接管",{ua:navigator.userAgent})}if(this._bindTouchMask(),this.controlBar=aa.mount(this),typeof this.options.customControlsMount=="function")try{const e=this.options.customControlsMount({player:this,container:this.container,video:this.videoElm});e instanceof HTMLElement&&this.container.appendChild(e)}catch(e){me.error("VideoPlayer日志-挂载自定义控件失败",{e})}this.el.appendChild(this.container),me.info("VideoPlayer日志-节点初始化完成并加载")}_bindTouchMask(){if(!this.touchMask)return;const e=t=>{t.stopPropagation()};this.touchMask.addEventListener("pointerdown",e),this.touchMask.addEventListener("touchstart",e,{passive:!0}),this.touchMask.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.videoElm&&(this.videoElm.paused?this.play():this.pause())})}async setVideoSource(){if(this.useHls()){let e;try{e=await Ci.ableUrls(this.options)}catch{e=null}if(this._destroyed)return;this._startHlsWithFastestSource(e)}else{if(this._destroyed)return;this.videoElm.src=this.options.sourceURL}}bindEvents(){this.videoElm.addEventListener("play",()=>{this._applyPlayUi(),this.events.emit("play")}),this.videoElm.addEventListener("playing",()=>{this._clearSeekHold(),this._hideLoading(),this.events.emit("playing")}),this.videoElm.addEventListener("pause",()=>{this._applyPauseUi(),this.events.emit("pause")}),this.videoElm.addEventListener("ended",()=>{this.events.emit("ended")}),this.videoElm.addEventListener("loadedmetadata",()=>{as.updateDurationTime(this),this.events.emit("loadedmetadata")}),this.videoElm.addEventListener("loadeddata",()=>{this.events.emit("loadeddata")}),this.videoElm.addEventListener("loadstart",()=>{this.events.emit("loadstart")}),this.videoElm.addEventListener("canplay",()=>{this.events.emit("autoPlay"),this.events.emit("canplay"),!this._shouldHoldSeekUi()&&this.videoElm.readyState>=3&&this._hideLoading()}),this.videoElm.addEventListener("seeking",t=>{this._isSeeking=!0,this._seekTarget==null&&(this._seekTarget=t.target.currentTime,this._syncSeekUi(this._seekTarget));const i=this._seekTarget!=null?this._seekTarget:t.target.currentTime;this._isTimeBuffered(i)||this._showLoading(),this.events.emit("seeking",t.target.currentTime)}),this.videoElm.addEventListener("seeked",t=>{const i=t.target.currentTime,s=this._seekTarget,n=s==null||Math.abs(i-s)<=.5;this.videoElm.readyState<2||!n?this._syncSeekUi(s??i):(this._clearSeekHold(),this._syncSeekUi(i)),(this.videoElm.readyState>=3||this.videoElm.paused&&this.videoElm.readyState>=2)&&this._hideLoading(),this.events.emit("seeked",i)}),this.videoElm.addEventListener("waiting",()=>{this._showLoading(),this.events.emit("waiting")}),this.videoElm.addEventListener("durationchange",()=>{this.events.emit("durationchange")}),this.videoElm.addEventListener("timeupdate",t=>{this._shouldHoldSeekUi()||(this._clearSeekHold(),as.updateCurrentTime(this),lr.updateLine(this)),this.events.emit("timeupdate",t.target.currentTime)}),this.videoElm.addEventListener("error",()=>{const t=this.videoElm.error,i={code:t?t.code:null,message:t?t.message:"未知错误",src:this.videoElm.src,networkState:this.videoElm.networkState,readyState:this.videoElm.readyState},s={1:"MEDIA_ERR_ABORTED - 用户中止",2:"MEDIA_ERR_NETWORK - 网络错误",3:"MEDIA_ERR_DECODE - 解码错误",4:"MEDIA_ERR_SRC_NOT_SUPPORTED - 格式不支持"};t&&t.code&&(i.message=s[t.code]||i.message),this.videoElm.src&&this.videoElm.src.startsWith("blob:")?(i.blobUrlError=!0,i.message=`Blob URL加载失败: ${this.videoElm.src}`,me.error("VideoPlayer日志-视频Blob URL错误",i),this.hlsInstance&&console.error("HLS实例状态:",{media:this.hlsInstance.media,url:this.hlsInstance.url,levels:this.hlsInstance.levels,currentLevel:this.hlsInstance.currentLevel})):me.error("VideoPlayer日志-视频加载错误",i),this.events.emit("error",i)}),this._handleFullscreenChange=()=>{const i=!!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement);this.events.emit("fullscreenchange",i),this.options.controls&&Li.changeFullScreen(this,i)},document.addEventListener("fullscreenchange",this._handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this._handleFullscreenChange),document.addEventListener("mozfullscreenchange",this._handleFullscreenChange),document.addEventListener("MSFullscreenChange",this._handleFullscreenChange),this.events.on("fullscreenchange",t=>{this.options.controls&&Li.changeFullScreen(this,t)}),this.events.on("volumechange",t=>{oi.sync(this,t)}),this.events.on("changeProgress",t=>{lr.updateLineDot(this,t)}),this.options.autoPlay&&this.events.once("autoPlay",()=>{this.play()});const e=new MutationObserver(()=>{this.videoElm&&this.videoElm.hasAttribute("controls")&&(this.videoElm.removeAttribute("controls"),this.videoElm.controls=!1)});this.videoElm&&(e.observe(this.videoElm,{attributes:!0,attributeFilter:["controls"]}),this._controlsObserver=e,this.videoElm.hasAttribute("controls")&&(this.videoElm.removeAttribute("controls"),this.videoElm.controls=!1)),me.info("VideoPlayer日志-事件绑定完成")}clearPlayer(){if(!this.el)return;const e=this.el.querySelector("video");if(e&&(e.pause(),e.src="",typeof e.remove=="function"))try{e.remove()}catch{}this.el.innerHTML="",me.info("VideoPlayer日志-清除播放器")}_applyPlayUi(){this.status="playing",xh.changeBtnStatus(this)}_applyPauseUi(){this.status="pause",xh.changeBtnStatus(this)}play(){if(this._applyPlayUi(),this.videoElm&&(this.videoElm.controls=!1,this.videoElm.removeAttribute("controls"),this.videoElm.paused)){const e=this.videoElm.play();e&&typeof e.catch=="function"&&e.catch(()=>{})}me.info("VideoPlayer日志-播放",{status:this.status})}pause(){this._applyPauseUi(),this.videoElm&&!this.videoElm.paused&&this.videoElm.pause(),me.info("VideoPlayer日志-暂停",{status:this.status})}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}currentTimeSec(e){return e!==void 0&&this.seek(e),this.videoElm.currentTime}duration(){return this.videoElm.duration}_isProgressDragging(){return!!(this.progressSlider&&this.progressSlider.isDragging)}_isTimeBuffered(e){const t=this.videoElm&&this.videoElm.buffered;if(!t||!Number.isFinite(e))return!1;for(let i=0;i<t.length;i++)if(e>=t.start(i)&&e<t.end(i)-.15)return!0;return!1}_shouldHoldSeekUi(){return this._isProgressDragging()?!0:this._isSeeking}_syncSeekUi(e){if(!Number.isFinite(e)||!this.videoElm)return;const t=this.videoElm.duration;as.updateCurrentTime(this,e),t&&Number.isFinite(t)&&t>0&&lr.updateLine(this,e/t)}_clearSeekHold(){this._isSeeking=!1,this._seekTarget=null}_showLoading(){this.loadingElm&&this.loadingElm.classList.add("is-show")}_hideLoading(){this.loadingElm&&this.loadingElm.classList.remove("is-show")}seek(e){if(!this.videoElm||!Number.isFinite(e))return;const t=this.videoElm.duration,i=t&&Number.isFinite(t)?Math.max(0,Math.min(t,e)):Math.max(0,e);this._isSeeking=!0,this._seekTarget=i,this._syncSeekUi(i),this._isTimeBuffered(i)||this._showLoading(),this.videoElm.currentTime=i}changeSrc(e){this.hlsInstance&&(Qt.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),e&&e.includes(".m3u8")&&Je.isSupported()?(this.options.isSupportHls=!0,this.options.sourceURL=e,this.setVideoSource()):(this.options.isSupportHls=!1,this.options.sourceURL=e,this.videoElm.src=e,this.events.once("autoPlay",()=>{this.play()}))}muted(e){oi.changeVolume(this,!e),this.events.emit("volumechange",!e)}requestFullscreen(){Li.fullScreen(this)}exitFullscreen(){Li.exitFullScreen(this)}changeSpeed({value:e}){this.videoElm.playbackRate=e||1}async uploadPlayerLogs(){me.info("VideoPlayer日志-日志已通过WebSocket实时上报")}destroy(){this._destroyed=!0,this._hideLoading(),this._clearSeekHold(),this.hlsInstance&&(Qt.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),this._controlsObserver&&(this._controlsObserver.disconnect(),this._controlsObserver=null),this._handleFullscreenChange&&(document.removeEventListener("fullscreenchange",this._handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._handleFullscreenChange),document.removeEventListener("mozfullscreenchange",this._handleFullscreenChange),document.removeEventListener("MSFullscreenChange",this._handleFullscreenChange),this._handleFullscreenChange=null),this.canvasMirror&&(this.canvasMirror.destroy(),this.canvasMirror=null),this.events&&typeof this.events.removeAll=="function"&&this.events.removeAll(),this.clearPlayer()}useHls(){return this.options.isSupportHls&&this.options.sourceURL.includes(".m3u8")}_findLine2Source(e){return Ci.findLine2Source(e)}async switchLine(e){const t=Number(e)===2?2:1;if(this._destroyed||!this.useHls())return!1;if(this.currentLine===t&&this.hlsInstance)return at.changeLineUI(this,t),!0;try{this.playUrls=await Ci.ableUrls(this.options)}catch{if(!this.playUrls||!this.playUrls.length)return!1}if(this._destroyed)return!1;if(t===2){const n=this._findLine2Source(this.playUrls);return!n||!n.url?!1:(await this._reloadHlsByLine({line:2,url:n.url,cdnList:[n],switchCdn:!1}),!0)}this.currentLine=1,at.changeLineUI(this,1);const i=this.videoElm?this.videoElm.currentTime:0,s=this.status==="playing"||this.videoElm&&!this.videoElm.paused;return this._startHlsWithFastestSource(this.playUrls,{restoreTime:i,wasPlaying:s}),!0}_startHlsWithFastestSource(e,t={}){const i=e&&e.length?e:null,s=!!(i&&i.length>1),n=i&&i[0]&&i[0].url||this.options.sourceURL;this.playUrls=i,this.currentLine=this.currentLine||1;const a=t.restoreTime,o=t.wasPlaying,l={},c=(h,d)=>{this._destroyed||!h||(this.hlsInstance&&(Qt.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),this.hlsInstance=Qt.createHlsInstance(this.videoElm,!!(d&&d.length>1),d||[],{...this.options,m3u8Cache:l}),Qt.startLoad(this.hlsInstance,h),(a>0&&Number.isFinite(a)||o)&&this.hlsInstance.once(Je.Events.MANIFEST_PARSED,()=>{if(!(this._destroyed||!this.videoElm)){if(a>0&&Number.isFinite(a))try{this.videoElm.currentTime=a}catch{}o&&this.play()}}))};if(!s){c(n,i||[]);return}let u=!1;Ci.raceFastestSource(i,(h,d)=>{if(u||this._destroyed)return;u=!0,d.content&&(l[h.url]=d.content);const g=Ci.putWinnerFirst(i,h);this.playUrls=g,c(h.url,g)},l).then(({winner:h})=>{const d=h?Ci.putWinnerFirst(i,h):this.playUrls||i;if(this.playUrls=d,d&&d.length>1&&Ah(d,l),!u&&!this._destroyed){u=!0;const g=d&&d[0]&&d[0].url||n;c(g,d||i)}}).catch(()=>{!u&&!this._destroyed&&(u=!0,c(n,i))})}async _reloadHlsByLine({line:e,url:t,cdnList:i,switchCdn:s}){if(this._destroyed||!t)return;const n=this.videoElm?this.videoElm.currentTime:0,a=this.status==="playing"||this.videoElm&&!this.videoElm.paused;this.hlsInstance&&(Qt.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),this.currentLine=e,at.changeLineUI(this,e),this.hlsInstance=Qt.createHlsInstance(this.videoElm,s,i||[],this.options),Qt.startLoad(this.hlsInstance,t);const o=()=>{if(!(this._destroyed||!this.videoElm)){if(n>0&&Number.isFinite(n))try{this.videoElm.currentTime=n}catch{}a&&this.play()}};this.hlsInstance.once(Je.Events.MANIFEST_PARSED,o)}}class kT{constructor(e){this.target=e,this.eventsQueue={}}on(e,t,i=!1){this.eventsQueue[e]||(this.eventsQueue[e]={methods:[],onceFlags:[]}),!this.eventsQueue[e].methods.includes(t)&&(this.eventsQueue[e].methods.push(t),this.eventsQueue[e].onceFlags.push(!!i))}once(e,t){this.on(e,t,!0)}emit(e,...t){const i=this.eventsQueue[e];if(!i)return;const{methods:s,onceFlags:n}=i,a=[],o=[];s.forEach((l,c)=>{try{l.apply(this.target,t)}catch(u){console.error("[LivePlayer Events]",e,u)}n[c]||(a.push(l),o.push(!1))}),i.methods=a,i.onceFlags=o}off(e,t){const i=this.eventsQueue[e];if(!i)return;if(!t){delete this.eventsQueue[e];return}const s=i.methods.indexOf(t);s>=0&&(i.methods.splice(s,1),i.onceFlags.splice(s,1)),i.methods.length||delete this.eventsQueue[e]}removeAll(){this.eventsQueue={}}}class Tr{static injectStyle(){ra()}static createVideoElement(e={}){const t=document.createElement("video");return t.className="ylc-live-player-video",t.setAttribute("playsinline","true"),t.setAttribute("webkit-playsinline","true"),t.muted=!!e.muted,t.autoplay=!!e.autoPlay||!!e.autoplay,t.controls=!1,e.poster&&(t.poster=e.poster),t}static mount(e){Tr.injectStyle();const t=e.options||{},i=yh(Nv({showControls:!!t.controls,muted:!!t.muted})),s=Tr.createVideoElement(t);return i.insertBefore(s,i.firstChild),e.container=i,e.videoElm=s,e.liveBadge=i.querySelector(".ylc-live-player-badge"),e.statusText=i.querySelector(".ylc-live-player-status"),e.controlBar=i.querySelector(".ylc-live-player-controls"),e.playButton=i.querySelector(".ylc-live-play-button"),e.pauseButton=i.querySelector(".ylc-live-pause-button"),e.volumeButton=i.querySelector(".ylc-live-volume-button"),e.muteButton=i.querySelector(".ylc-live-mute-button"),e.fullScreenButton=i.querySelector(".ylc-live-full-screen-button"),e.exitFullScreenButton=i.querySelector(".ylc-live-exit-full-screen-button"),i}}class OT{constructor(e={}){this.whepUrl=e.whepUrl||"",this.rtcConfig=e.rtcConfig||{iceServers:[{urls:"stun:stun.l.google.com:19302"}]},this.headers=e.headers||{},this.onPeer=e.onPeer,this.onTrack=e.onTrack,this.onError=e.onError,this.onConnectionState=e.onConnectionState,this.pc=null,this.resourceUrl=null,this._closed=!1}async start(){if(!this.whepUrl)throw new Error("whepUrl 不能为空");this._closed=!1,this.pc=new RTCPeerConnection(this.rtcConfig),typeof this.onPeer=="function"&&this.onPeer(this.pc),this.pc.addTransceiver("video",{direction:"recvonly"}),this.pc.addTransceiver("audio",{direction:"recvonly"}),this.pc.ontrack=a=>{if(typeof this.onTrack=="function"){const o=a.streams&&a.streams[0]?a.streams[0]:new MediaStream([a.track]);this.onTrack(o,a)}},this.pc.onconnectionstatechange=()=>{typeof this.onConnectionState=="function"&&this.onConnectionState(this.pc.connectionState),this.pc.connectionState==="failed"&&this._emitError(new Error("WebRTC connection failed"))};const e=await this.pc.createOffer();await this.pc.setLocalDescription(e),await this._waitIceGatheringComplete(this.pc);const t=this.pc.localDescription&&this.pc.localDescription.sdp,i=await fetch(this.whepUrl,{method:"POST",headers:{"Content-Type":"application/sdp",...this.headers},body:t});if(!i.ok){const a=await i.text().catch(()=>"");throw new Error(`WHEP 请求失败 HTTP ${i.status} ${a}`)}const s=i.headers.get("Location")||i.headers.get("location");if(s)try{this.resourceUrl=new URL(s,this.whepUrl).toString()}catch{this.resourceUrl=s}const n=await i.text();return await this.pc.setRemoteDescription({type:"answer",sdp:n}),this.pc}async stop(){if(this._closed=!0,this.resourceUrl){try{await fetch(this.resourceUrl,{method:"DELETE",headers:{...this.headers}})}catch{}this.resourceUrl=null}if(this.pc){try{this.pc.getSenders().forEach(e=>{e.track&&e.track.stop()}),this.pc.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this.pc.close()}catch{}this.pc=null}}_waitIceGatheringComplete(e,t=3e3){return e.iceGatheringState==="complete"?Promise.resolve():new Promise(i=>{const s=setTimeout(()=>{e.removeEventListener("icegatheringstatechange",n),i()},t),n=()=>{e.iceGatheringState==="complete"&&(clearTimeout(s),e.removeEventListener("icegatheringstatechange",n),i())};e.addEventListener("icegatheringstatechange",n)})}_emitError(e){this._closed||typeof this.onError=="function"&&this.onError(e)}}class FT{constructor(e={}){this.video=e.video,this.options=e,this.pc=null,this.whep=null,this.stream=null,this._destroyed=!1}async start(){if(!this._destroyed){if(this.options.mediaStream){await this._attachStream(this.options.mediaStream),this._emit("connected");return}if(typeof this.options.getStream=="function"){const e=await this.options.getStream();await this._attachStream(e),this._emit("connected");return}if(this.options.whepUrl){await this._startWhep();return}if(typeof this.options.signaling=="function"){await this._startCustomSignaling();return}throw new Error("LivePlayer: 请提供 mediaStream / getStream / whepUrl / signaling 之一")}}async _startWhep(){this.whep=new OT({whepUrl:this.options.whepUrl,rtcConfig:this.options.rtcConfig,headers:this.options.headers,onPeer:e=>{this.pc=e},onTrack:e=>{this._attachStream(e)},onConnectionState:e=>{this._emit("connectionstatechange",{state:e}),e==="connected"&&this._emit("connected"),(e==="disconnected"||e==="failed"||e==="closed")&&this._emit("disconnected",{state:e})},onError:e=>this._emit("error",{error:e})}),await this.whep.start()}async _startCustomSignaling(){const e=this.options.rtcConfig||{iceServers:[{urls:"stun:stun.l.google.com:19302"}]};this.pc=new RTCPeerConnection(e),this.pc.addTransceiver("video",{direction:"recvonly"}),this.pc.addTransceiver("audio",{direction:"recvonly"}),this.pc.ontrack=t=>{const i=t.streams&&t.streams[0]?t.streams[0]:new MediaStream([t.track]);this._attachStream(i)},this.pc.onconnectionstatechange=()=>{const t=this.pc.connectionState;this._emit("connectionstatechange",{state:t}),t==="connected"&&this._emit("connected"),(t==="disconnected"||t==="failed"||t==="closed")&&this._emit("disconnected",{state:t})},await this.options.signaling(this.pc,{attachStream:t=>this._attachStream(t)})}async _attachStream(e){if(!(this._destroyed||!e)){if(this.stream=e,this.video){this.video.srcObject=e;try{await this.video.play()}catch(t){this._emit("autoplayblocked",{error:t})}}this._emit("track",{stream:e})}}getPeerConnection(){return this.pc}getStream(){return this.stream}async destroy(){if(this._destroyed=!0,this.whep&&(await this.whep.stop(),this.whep=null),this.pc&&!this.whep){try{this.pc.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this.pc.close()}catch{}this.pc=null}if(this.stream){try{this.stream.getTracks().forEach(e=>e.stop())}catch{}this.stream=null}this.video&&(this.video.srcObject=null)}_emit(e,t={}){typeof this.options.onEvent=="function"&&this.options.onEvent({type:e,...t})}}class To{constructor(e,t={}){if(this.containerId=e,this.options={poster:"",autoPlay:!0,autoplay:!0,controls:!0,muted:!0,protocol:"webrtc",whepUrl:"",mediaStream:null,getStream:null,signaling:null,rtcConfig:null,headers:null,...t},this._destroyed=!1,this.status="idle",this.adapter=null,this._docFsHandler=null,!this.containerId){me.error("LivePlayer日志-未传节点id",{containerId:e});return}if(this.el=document.querySelector("#"+e),!this.el){me.error("LivePlayer日志-未查询到节点",{containerId:e});return}this.events=new kT(this),this.clearPlayer(),this.init()}init(){me.info("LivePlayer日志-开始初始化",{containerId:this.containerId,protocol:this.options.protocol,hasWhep:!!this.options.whepUrl,hasStream:!!this.options.mediaStream,hasGetStream:typeof this.options.getStream=="function",hasSignaling:typeof this.options.signaling=="function"}),this.createPlayerContainer(),this.bindUiEvents(),this.startLive().catch(e=>{this._handleError(e)})}createPlayerContainer(){this.el.innerHTML="",Tr.mount(this),this.statusText&&(this.statusText.textContent="连接中..."),this.el.appendChild(this.container)}bindUiEvents(){this.playButton&&(this.playButton.onclick=()=>this.play()),this.pauseButton&&(this.pauseButton.onclick=()=>this.pause()),this.volumeButton&&(this.volumeButton.onclick=()=>this.muted(!0)),this.muteButton&&(this.muteButton.onclick=()=>this.muted(!1)),this.fullScreenButton&&(this.fullScreenButton.onclick=()=>this.requestFullscreen()),this.exitFullScreenButton&&(this.exitFullScreenButton.onclick=()=>this.exitFullscreen()),this.videoElm.addEventListener("playing",()=>{this.status="playing",this._syncPlayButtons(),this._setStatusText(""),this.events.emit("playing"),this.events.emit("play")}),this.videoElm.addEventListener("pause",()=>{this.status="pause",this._syncPlayButtons(),this.events.emit("pause")}),this.videoElm.addEventListener("waiting",()=>{this._setStatusText("加载中..."),this.events.emit("waiting")}),this.videoElm.addEventListener("error",()=>{this._handleError(new Error("video element error"))}),this._docFsHandler=()=>this._syncFullscreenButtons(),document.addEventListener("fullscreenchange",this._docFsHandler),document.addEventListener("webkitfullscreenchange",this._docFsHandler)}async startLive(){this._destroyed||(this.adapter=new FT({video:this.videoElm,mediaStream:this.options.mediaStream,getStream:this.options.getStream,whepUrl:this.options.whepUrl||this.options.sourceURL,rtcConfig:this.options.rtcConfig,headers:this.options.headers,signaling:this.options.signaling,onEvent:e=>this._onAdapterEvent(e)}),this.status="connecting",this._setStatusText("连接中..."),this.events.emit("connecting"),await this.adapter.start())}_onAdapterEvent(e){if(this._destroyed)return;const{type:t}=e;t==="connected"?(this.status="connected",this._setStatusText(""),this.events.emit("connected"),me.info("LivePlayer日志-已连接")):t==="disconnected"?(this.status="disconnected",this._setStatusText("已断开"),this.events.emit("disconnected",e),me.info("LivePlayer日志-已断开",e)):t==="connectionstatechange"?this.events.emit("connectionstatechange",e):t==="track"?this.events.emit("track",e):t==="autoplayblocked"?(this._setStatusText("点击播放"),this.events.emit("autoplayblocked",e),me.info("LivePlayer日志-自动播放被拦截")):t==="error"&&this._handleError(e.error||new Error("rtc error"))}_handleError(e){const t=e&&e.message?e.message:String(e);this.status="error",this._setStatusText(t),me.error("LivePlayer日志-错误",{message:t}),this.events.emit("error",{error:e,message:t})}_setStatusText(e){this.statusText&&(this.statusText.textContent=e||"",this.statusText.style.display=e?"block":"none")}_syncPlayButtons(){if(!this.playButton||!this.pauseButton)return;const e=this.status==="playing";this.playButton.style.display=e?"none":"inline-block",this.pauseButton.style.display=e?"inline-block":"none"}_syncFullscreenButtons(){if(!this.fullScreenButton||!this.exitFullScreenButton)return;const t=!!(document.fullscreenElement||document.webkitFullscreenElement);this.fullScreenButton.style.display=t?"none":"inline-block",this.exitFullScreenButton.style.display=t?"inline-block":"none"}play(){if(!this.videoElm)return;const e=this.videoElm.play();e&&typeof e.then=="function"&&e.then(()=>{this.status="playing",this._syncPlayButtons(),this._setStatusText(""),me.info("LivePlayer日志-播放")}).catch(t=>{this._handleError(t)})}pause(){this.videoElm&&(this.videoElm.pause(),this.status="pause",this._syncPlayButtons(),me.info("LivePlayer日志-暂停"))}muted(e){this.videoElm&&(this.videoElm.muted=!!e,this.volumeButton&&this.muteButton&&(this.volumeButton.style.display=e?"none":"inline-block",this.muteButton.style.display=e?"inline-block":"none"),this.events.emit("volumechange",{muted:!!e}))}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}async changeSrc(e){this._destroyed||(typeof e=="string"?(this.options.whepUrl=e,this.options.sourceURL=e,this.options.mediaStream=null,this.options.getStream=null,this.options.signaling=null):e&&typeof e=="object"&&Object.assign(this.options,e),this.adapter&&(await this.adapter.destroy(),this.adapter=null),this._setStatusText("重新连接..."),await this.startLive())}requestFullscreen(){const e=this.options.fullscreenElement||this.container||this.el;if(!e)return;const t=e.requestFullscreen||e.webkitRequestFullscreen||e.webkitEnterFullscreen;if(t)try{const i=t.call(e);i&&typeof i.catch=="function"&&i.catch(()=>{})}catch{this.videoElm&&this.videoElm.webkitEnterFullscreen&&this.videoElm.webkitEnterFullscreen()}this.events.emit("fullscreenchange",{fullscreen:!0})}exitFullscreen(){const e=document.exitFullscreen||document.webkitExitFullscreen;if(e)try{const t=e.call(document);t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}this.events.emit("fullscreenchange",{fullscreen:!1})}getPeerConnection(){return this.adapter?this.adapter.getPeerConnection():null}getStream(){return this.adapter?this.adapter.getStream():null}clearPlayer(){if(!this.el)return;const e=this.el.querySelector("video");if(e)try{e.pause(),e.srcObject=null,e.removeAttribute("src")}catch{}this.el.innerHTML=""}async destroy(){this._destroyed=!0,this._docFsHandler&&(document.removeEventListener("fullscreenchange",this._docFsHandler),document.removeEventListener("webkitfullscreenchange",this._docFsHandler),this._docFsHandler=null),this.adapter&&(await this.adapter.destroy(),this.adapter=null),this.events&&this.events.removeAll(),this.clearPlayer(),this.status="destroyed",me.info("LivePlayer日志-已销毁",{containerId:this.containerId})}}class MT{static getVideoSignByFileId(e,t,i){return new Promise((s,n)=>{const a=new Eo,o={secret_id:t,secret_key:i,file_id:e};a.post("https://console-api.huaxiacloud.net/third_party/generate/sign",o,"json").then(l=>{s(l)}).catch(l=>{n(l)})})}static getVideoUrlBySign(e,t,i,s){return new Promise((n,a)=>{const o=new Eo,l={secret_id:t,file_id:String(e),timestamp:String(i),sign:s,client_type:"web"};o.post("https://console-api.huaxiacloud.net/third_party/verify/sign",l,"json").then(c=>{n(c)}).catch(c=>{a(c)})})}}const NT=["play","pause","seek","currentTimeSec","duration","changeSrc","muted","changeSpeed","switchLine","on","off","uploadPlayerLogs","requestFullscreen","exitFullscreen"];function BT(r){return!!r&&typeof r=="object"&&r.nodeType!==1&&!Array.isArray(r)}function UT(r){if(!r)return{id:"",el:null};if(typeof r=="string"){const e=r.replace(/^#/,"");return{id:e,el:typeof document<"u"?document.querySelector("#"+e):null}}return r.nodeType===1?(r.id||(r.id="hx-player-"+Date.now()),{id:r.id,el:r}):{id:"",el:null}}function $T(r={}){const e={...r};return e.url&&!e.sourceURL&&(e.sourceURL=e.url),e.autoplay!=null&&e.autoPlay==null&&(e.autoPlay=e.autoplay),e}function GT(r={}){return!!(r.mode==="live"||r.protocol==="webrtc"||r.protocol==="rtc"||r.whepUrl||r.mediaStream||typeof r.getStream=="function"||typeof r.signaling=="function")}function VT(r={}){return(r.sourceURL||"").includes(".m3u8")?ch()&&!r.isEncrypt?{type:"VIDEO"}:{type:"HLS"}:{type:"VIDEO"}}const _t=class _t{constructor(e,t={}){BT(e)&&(e.id||e.el||e.container||e.url||e.sourceURL||e.fileId||e.whepUrl||e.mode)&&(t={...e,...t},e=t.id||t.el||t.container);const i=UT(e);this.containerId=i.id,this.el=i.el,this.options=$T(t),this._player=null,this._destroyed=!1;const s=_t._instances.get(this.containerId);s&&s!==this&&typeof s.destroy=="function"&&s.destroy(),this.containerId&&_t._instances.set(this.containerId,this),this._seq=(_t._createSeq.get(this.containerId)||0)+1,_t._createSeq.set(this.containerId,this._seq),this.ready=this._bootstrap(),NT.forEach(n=>{this[n]=(...a)=>this._call(n,...a)})}get player(){return this._player}get video(){return this._player&&this._player.videoElm}async _bootstrap(){try{if(me.info("HxPlayer日志-创建播放器实例",{containerId:this.containerId,options:{...this.options,fullscreenElement:""}}),ns.connect({userId:this.options.fansId||this.options.userId||this.options.user_id||"",terminal:this.options.terminal||ns.detectTerminal()}).catch(e=>{console.warn("[HxPlayer] LogWebSocket 连接失败",e)}),me.setAppContext({appId:this.options.appId,fansId:this.options.fansId}),!this.options.sourceURL&&this.options.fileId&&this.options.secret_id){const{code:e,data:{play_url:t,encrypt_type:i,encrypted_data:s}}=await MT.getVideoUrlBySign(this.options.fileId,this.options.secret_id,this.options.timestamp,this.options.sign);e===200&&(this.options.sourceURL=t,this.options.url=t,this.options.isEncrypt=i===1,this.options.encryptedData=s)}if(this._destroyed)return this;if(this.containerId&&_t._createSeq.get(this.containerId)!==this._seq)return me.info("HxPlayer日志-检测到更新的实例,放弃本次初始化",{containerId:this.containerId,seq:this._seq}),this;if(GT(this.options))this._player=new To(this.containerId,this.options);else{const e=VT(this.options);if(this._destroyed)return this;this._player=new So(this.containerId,{...this.options,isSupportHls:e.type==="HLS"})}return this}catch(e){throw console.log("HxPlayer日志-播放器初始化失败",e),me.error("HxPlayer日志-播放器初始化失败",{error:e&&e.message?e.message:String(e)}),e}}_call(e,...t){return e==="destroy"?this.destroy():this.ready.then(()=>{if(this._destroyed||!this._player)return;const i=this._player[e];if(typeof i=="function")return i.apply(this._player,t)})}setPlaybackRate(e){return this._call("changeSpeed",{value:e})}destroy(){this._destroyed=!0,this._player&&typeof this._player.destroy=="function"&&this._player.destroy(),this._player=null,this.containerId&&_t._instances.get(this.containerId)===this&&_t._instances.delete(this.containerId)}};vt(_t,"_instances",new Map),vt(_t,"_createSeq",new Map);let Ht=_t;Ht.VideoPlayer=So,Ht.LivePlayer=To,Ht.Hls=Je,Ht.version="1.0.0",typeof window<"u"&&(window.HxPlayer=Ht),Qe.Hls=Je,Qe.HxPlayer=Ht,Qe.LivePlayer=To,Qe.VideoPlayer=So,Qe.default=Ht,Object.defineProperties(Qe,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));typeof globalThis<"u"&&globalThis.HxPlayer&&globalThis.HxPlayer.HxPlayer&&(globalThis.HxPlayer=globalThis.HxPlayer.default||globalThis.HxPlayer.HxPlayer);
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).HxPlayer={})}(this,function(e){"use strict";function t(e,t){this.v=e,this.k=t}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function n(e){var r={},n=!1;function i(r,i){return n=!0,i=new Promise(function(t){t(e[r](i))}),{done:!1,value:new t(i,1)}}return r["undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator"]=function(){return this},r.next=function(e){return n?(n=!1,e):i("next",e)},"function"==typeof e.throw&&(r.throw=function(e){if(n)throw n=!1,e;return i("throw",e)}),"function"==typeof e.return&&(r.return=function(e){return n?(n=!1,e):i("return",e)}),r}function i(e){var t,r,n,i=2;for("undefined"!=typeof Symbol&&(r=Symbol.asyncIterator,n=Symbol.iterator);i--;){if(r&&null!=(t=e[r]))return t.call(e);if(n&&null!=(t=e[n]))return new a(t.call(e));r="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function a(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then(function(e){return{value:e,done:t}})}return a=function(e){this.s=e,this.n=e.next},a.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return void 0===r?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return void 0===r?Promise.reject(e):t(r.apply(this.s,arguments))}},new a(e)}function s(e,t,r,n,i,a,s){try{var o=e[a](s),l=o.value}catch(e){return void r(e)}o.done?t(l):Promise.resolve(l).then(n,i)}function o(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var a=e.apply(t,r);function o(e){s(a,n,i,o,l,"next",e)}function l(e){s(a,n,i,o,l,"throw",e)}o(void 0)})}}function l(e){return new t(e,0)}function u(e,t,r){return t=p(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,m()?Reflect.construct(t,r||[],p(e).constructor):t.apply(e,r))}function c(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function d(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,w(n.key),n)}}function h(e,t,r){return t&&d(e.prototype,t),r&&d(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function f(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=P(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(o)throw a}}}}function v(e,t,r){return(t=w(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function g(){return g="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var n=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=p(e)););return e}(e,t);if(n){var i=Object.getOwnPropertyDescriptor(n,t);return i.get?i.get.call(arguments.length<3?e:r):i.value}},g.apply(null,arguments)}function p(e){return p=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},p(e)}function y(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&A(e,t)}function m(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(m=function(){return!!e})()}function E(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function k(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?E(Object(r),!0).forEach(function(t){v(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):E(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function S(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",i=r.toStringTag||"@@toStringTag";function a(r,n,i,a){var l=n&&n.prototype instanceof o?n:o,u=Object.create(l.prototype);return T(u,"_invoke",function(r,n,i){var a,o,l,u=0,c=i||[],d=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,r){return a=t,o=0,l=e,h.n=r,s}};function f(r,n){for(o=r,l=n,t=0;!d&&u&&!i&&t<c.length;t++){var i,a=c[t],f=h.p,v=a[2];r>3?(i=v===n)&&(l=a[(o=a[4])?5:(o=3,3)],a[4]=a[5]=e):a[0]<=f&&((i=r<2&&f<a[1])?(o=0,h.v=n,h.n=a[1]):f<v&&(i=r<3||a[0]>n||n>v)&&(a[4]=r,a[5]=n,h.n=v,o=0))}if(i||r>1)return s;throw d=!0,n}return function(i,c,v){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&f(c,v),o=c,l=v;(t=o<2?e:l)||!d;){a||(o?o<3?(o>1&&(h.n=-1),f(o,l)):h.n=l:h.v=l);try{if(u=2,a){if(o||(i="next"),t=a[i]){if(!(t=t.call(a,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,o<2&&(o=0)}else 1===o&&(t=a.return)&&t.call(a),o<2&&(l=TypeError("The iterator does not provide a '"+i+"' method"),o=1);a=e}else if((t=(d=h.n<0)?l:r.call(n,h))!==s)break}catch(t){a=e,o=1,l=t}finally{u=1}}return{value:t,done:d}}}(r,i,a),!0),u}var s={};function o(){}function l(){}function u(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(T(t={},n,function(){return this}),t),d=u.prototype=o.prototype=Object.create(c);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,T(e,i,"GeneratorFunction")),e.prototype=Object.create(d),e}return l.prototype=u,T(d,"constructor",u),T(u,"constructor",l),l.displayName="GeneratorFunction",T(u,i,"GeneratorFunction"),T(d),T(d,i,"Generator"),T(d,n,function(){return this}),T(d,"toString",function(){return"[object Generator]"}),(S=function(){return{w:a,m:h}})()}function T(e,t,r,n){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}T=function(e,t,r,n){function a(t,r){T(e,t,function(e){return this._invoke(t,r,e)})}t?i?i(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},T(e,t,r,n)}function b(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(typeof e+" is not iterable")}function A(e,t){return A=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},A(e,t)}function L(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,a,s,o=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;l=!1}else for(;!(l=(n=a.call(r)).done)&&(o.push(n.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw i}}return o}}(e,t)||P(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function R(e,t,r,n){var i=g(p(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}function I(e){return function(e){if(Array.isArray(e))return r(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||P(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function w(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r;if("undefined"!=typeof Symbol&&void 0!==(r=e[Symbol.toPrimitive])){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function _(e){return _="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_(e)}function P(e,t){if(e){if("string"==typeof e)return r(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}function D(e){return function(){return new C(e.apply(this,arguments))}}function C(e){var r,n;function i(r,n){try{var s=e[r](n),o=s.value,l=o instanceof t;Promise.resolve(l?o.v:o).then(function(t){if(l){var n="return"===r&&o.k?r:"next";if(!o.k||t.done)return i(n,t);t=e[n](t).value}a(!!s.done,t)},function(e){i("throw",e)})}catch(e){a(2,e)}}function a(e,t){2===e?r.reject(t):r.resolve({value:t,done:e}),(r=r.next)?i(r.key,r.arg):n=null}this._invoke=function(e,t){return new Promise(function(a,s){var o={key:e,arg:t,resolve:a,reject:s,next:null};n?n=n.next=o:(r=n=o,i(e,t))})},"function"!=typeof e.return&&(this.return=void 0)}function O(e){var t="function"==typeof Map?new Map:void 0;return O=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(m())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&A(i,r.prototype),i}(e,arguments,p(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),A(r,e)},O(e)}C.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},C.prototype.next=function(e){return this._invoke("next",e)},C.prototype.throw=function(e){return this._invoke("throw",e)},C.prototype.return=function(e){return this._invoke("return",e)};var x=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},M=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=F},F=Number.MAX_SAFE_INTEGER||9007199254740991,N=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),U=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",e.UNKNOWN="unknown",e}({}),B=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});function G(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var j,K={exports:{}};var H=(j||(j=1,function(e){var t,r,n,i,a;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,n){if(n=n||{},e=e.trim(),!(t=t.trim())){if(!n.alwaysNormalize)return e;var i=a.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=a.normalizePath(i.path),a.buildURLFromParts(i)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return n.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(u.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var c=o.path,d=c.substring(0,c.lastIndexOf("/")+1)+s.path;u.path=a.normalizePath(d)}else u.path=o.path,s.params||(u.params=o.params,s.query||(u.query=o.query));return null===u.path&&(u.path=n.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(u)},parseURL:function(e){var r=t.exec(e);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(n,"");e.length!==(e=e.replace(i,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(K)),K.exports),V=h(function e(){c(this,e),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}}),q=function(e){return e.MANIFEST="manifest",e.LEVEL="level",e.AUDIO_TRACK="audioTrack",e.SUBTITLE_TRACK="subtitleTrack",e.MEDIA_FRAGMENT="media-fragment",e.KEY="key",e.STEERING_MANIFEST="steering-manifest",e.SERVER_CERTIFICATE="server-certificate",e.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",e}({}),W=function(e){return e.MAIN="main",e.AUDIO="audio",e.SUBTITLE="subtitle",e}({}),Y="audio",z="video",X="audiovideo",Q=function(){return h(function e(t){var r,n,i;c(this,e),this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,(i=re(r=this,n="stats"))&&(i.enumerable=!0,Object.defineProperty(r,n,i))},[{key:"setByteRange",value:function(e,t){var r,n=e.split("@",2);r=1===n.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(n[1]),this._byteRange=[r,parseInt(n[0])+r]}},{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){return null===this._streams&&(this._streams=v(v(v({},Y,null),z,null),X,null)),this._streams},set:function(e){this._streams=e}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new V),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=H.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}},{key:"clearElementaryStreamInfo",value:function(){var e=this.elementaryStreams;e[Y]=null,e[z]=null,e[X]=null,this.url=null}}])}();function $(e){return"initSegment"!==e.sn}function J(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level}function Z(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}var ee=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,[r]))._decryptdata=null,n._programDateTime=null,n._ref=null,n._bitrate=void 0,n.rawProgramDateTime=null,n.tagList=[],n.duration=0,n.sn=0,n.levelkeys=void 0,n.type=void 0,n.loader=null,n.keyLoader=null,n.level=-1,n.cc=0,n.startPTS=void 0,n.endPTS=void 0,n.startDTS=void 0,n.endDTS=void 0,n.start=0,n.playlistOffset=0,n.deltaPTS=void 0,n.maxStartPTS=void 0,n.minEndPTS=void 0,n.data=void 0,n.bitrateTest=!1,n.title=null,n.initSegment=null,n.endList=void 0,n.gap=void 0,n.urlId=0,n.type=e,n}return y(t,e),h(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange.length){var t=this.byteRange[0],r=this.byteRange[1];if(x(t)&&x(r))return r-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){var e,t=this.levelkeys;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){var r=Object.keys(t);if(1===r.length){var n=this._decryptdata=t[r[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=x(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t,r=Object.keys(this.levelkeys),n=r.length;if(n>1||1===n&&null!=(t=this.levelkeys[r[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){x(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return $(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}},{key:"addStart",value:function(e){this.setStart(this.start+e)}},{key:"setStart",value:function(e){this.start=e,this._ref&&(this._ref.start=e)}},{key:"setDuration",value:function(e){this.duration=e,this._ref&&(this._ref.duration=e)}},{key:"setKeyFormat",value:function(e){var t=this.levelkeys;if(t){var r,n=t[e];!n||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=n.getDecryptData(this.sn,t))}}},{key:"abortRequests",value:function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}},{key:"setElementaryStreamInfo",value:function(e,t,r,n,i){var a=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,n),o.endDTS=Math.max(o.endDTS,i)):s[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:i,partial:a}}}])}(Q),te=function(e){function t(e,r,n,i,a){var s;c(this,t),(s=u(this,t,[n])).fragOffset=0,s.duration=0,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.gap=!1,s.duration=e.decimalFloatingPoint("DURATION"),s.gap=e.bool("GAP"),s.independent=e.bool("INDEPENDENT"),s.relurl=e.enumeratedString("URI"),s.fragment=r,s.index=i;var o=e.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return y(t,e),h(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===W.SUBTITLE&&this.stats.loading.end>0)}}])}(Q);function re(e,t){var r=Object.getPrototypeOf(e);if(r){var n=Object.getOwnPropertyDescriptor(r,t);return n||re(r,t)}}function ne(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=_(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=_(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==_(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ie(){return ie=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ie.apply(null,arguments)}function ae(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function se(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ae(Object(r),!0).forEach(function(t){ne(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ae(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function oe(e,t){if(null==e)return{};var r,n,i=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==t.indexOf(n))continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n<a.length;n++)r=a[n],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function le(e){switch(e.details){case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_TIMEOUT:case U.LEVEL_LOAD_TIMEOUT:case U.MANIFEST_LOAD_TIMEOUT:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.SUBTITLE_TRACK_LOAD_TIMEOUT:case U.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function ue(e){return e.details.startsWith("key")}function ce(e){return ue(e)&&!!e.frag&&!e.frag.decryptdata}function de(e,t){var r=le(t);return e.default["".concat(r?"timeout":"error","Retry")]}function he(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function fe(e){return se(se({},e),{errorRetry:null,timeoutRetry:null})}function ve(e,t,r,n){if(!e)return!1;var i=null==n?void 0:n.code,a=t<e.maxNumRetry&&(function(e){return ge(e)||!!e&&(e<400||e>499)}(i)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,n,a):a}function ge(e){return 0===e&&!1===navigator.onLine}function pe(e,t){return t>0&&e.loadError>0&&0!==e.loadErrorTime&&self.performance.now()-e.loadErrorTime>t}var ye=function(){return h(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;c(this,e),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=r,this.totalWeight_=n},[{key:"sample",value:function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}},{key:"getTotalWeight",value:function(){return this.totalWeight_}},{key:"getEstimate",value:function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}])}(),me=function(){return h(function e(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;c(this,e),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_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ye(t),this.fast_=new ye(r),this.defaultTTFB_=i,this.ttfb_=new ye(t)},[{key:"update",value:function(e,t){var r=this.slow_,n=this.fast_,i=this.ttfb_;r.halfLife!==e&&(this.slow_=new ye(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new ye(t,n.getEstimate(),n.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new ye(e,i.getEstimate(),i.getTotalWeight()))}},{key:"sample",value:function(e,t){if(!(t<=0)){var r=Math.min(this.minDelayMs_,t/1e5),n=8*t,i=Math.max(e,r)/1e3,a=n/i;this.fast_.sample(i,a),this.slow_.sample(i,a)}}},{key:"sampleTTFB",value:function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}},{key:"canEstimate",value:function(){return this.fast_.getTotalWeight()>=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"getEstimateTTFB",value:function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}},{key:"defaultEstimate",get:function(){return this.defaultEstimate_}},{key:"destroy",value:function(){}}])}(),Ee=h(function e(t,r){c(this,e),this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var n="[".concat(t,"]:");this.trace=ke,this.debug=r.debug.bind(null,n),this.log=r.log.bind(null,n),this.warn=r.warn.bind(null,n),this.info=r.info.bind(null,n),this.error=r.error.bind(null,n)}),ke=function(){},Se={trace:ke,debug:ke,log:ke,warn:ke,info:ke,error:ke};function Te(){return ie({},Se)}function be(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,"".concat(t?"["+t+"] ":"","[").concat(e,"] >")):ke}(e,r)}var Ae=Te();var Le=Ae;function Re(){if("undefined"!=typeof self)return(!(arguments.length>0&&void 0!==arguments[0])||arguments[0]||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ie(e,t){var r=Object.keys(e),n=Object.keys(t),i=r.length,a=n.length;return!i||!a||i===a&&!r.some(function(e){return-1===n.indexOf(e)})}function we(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}var _e="utf-16be",Pe="utf-16le",De="utf-8";function Ce(e,t){if(e<0)return-Ce(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){var n=Math.floor(e*r);return(n%2==0?n:n+1)/r}return Math.round(e*r)/r}function Oe(){try{return crypto.randomUUID()}catch(n){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(i){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)})}}}function xe(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Me(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]}function Fe(e,t){return xe(e,t)&&Me(e,t+6)+10<=e.length-t}function Ne(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Ue(e,t){for(var r=t,n=0;xe(e,t);){n+=10,n+=Me(e,t+6),Ne(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)}function Be(e){return function(e,t,r,n){var i=(s=e,we(s)?s:s.buffer),a=1;var s;"BYTES_PER_ELEMENT"in n&&(a=n.BYTES_PER_ELEMENT);var o=(d=e,d&&we(d.buffer)&&void 0!==d.byteLength&&void 0!==d.byteOffset?e.byteOffset:0),l=(o+e.byteLength)/a,u=(o+t)/a,c=Math.floor(Math.max(0,Math.min(u,l)));var d;return new n(i,c,Math.floor(Math.min(c+Math.max(r,0),l))-c)}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,arguments.length>2&&void 0!==arguments[2]?arguments[2]:1/0,Uint8Array)}function Ge(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t?e.indexOf(0):e.length,n=function(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=we(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);var n=0,i=r.encoding;if(!i){var a=t.getUint8(0),s=t.getUint8(1);239==a&&187==s&&191==t.getUint8(2)?(i=De,n=3):254==a&&255==s?(i=_e,n=2):255==a&&254==s?(i=Pe,n=2):i=De}if("undefined"!=typeof TextDecoder)return new TextDecoder(i).decode(t);for(var o,l=t.byteLength,u=i!==_e,c="";n<l;){switch(i){case De:if((o=t.getUint8(n))<128)n++;else if(o>=194&&o<=223)if(n+1<l){var d=t.getUint8(n+1);d>=128&&d<=191?(o=(31&o)<<6|63&d,n+=2):n++}else n++;else if(o>=224&&o<=239)if(n+2<=l-1){var h=t.getUint8(n+1),f=t.getUint8(n+2);h>=128&&h<=191&&f>=128&&f<=191?(o=(15&o)<<12|(63&h)<<6|63&f,n+=3):n++}else n++;else if(o>=240&&o<=244)if(n+3<=l-1){var v=t.getUint8(n+1),g=t.getUint8(n+2),p=t.getUint8(n+3);v>=128&&v<=191&&g>=128&&g<=191&&p>=128&&p<=191?(o=(7&o)<<18|(63&v)<<12|(63&g)<<6|63&p,n+=4):n++}else n++;else n++;break;case _e:case"utf-16":case Pe:o=t.getUint16(n,u),n+=2}c+=String.fromCodePoint(o)}return c}(new DataView(e.buffer,e.byteOffset,r),{encoding:De});return t?n:n.replace(/\0/g,"")}function je(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var n=Ge(Be(e.data,1,r)),i=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o,l=Ge(Be(e.data,3+r,a));return"--\x3e"===n?s=Ge(Be(e.data,4+r+a)):s=we(o=e.data.subarray(4+r+a))?o:0==o.byteOffset&&o.byteLength==o.buffer.byteLength?o.buffer:new Uint8Array(o).buffer,t.mimeType=n,t.pictureType=i,t.description=l,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function Ke(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=Ge(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=Ge(e.data.subarray(t),!0);t+=r.length+1;var n=Ge(e.data.subarray(t));return{key:e.type,info:r,data:n}}var i=Ge(e.data);return{key:e.type,info:"",data:i}}(e):"APIC"===e.type?je(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=e.data,n=Ge(r.subarray(t),!0);t+=n.length+1;var i=Ge(r.subarray(t));return{key:e.type,info:n,data:i}}var a=Ge(e.data.subarray(1));return{key:e.type,info:"",data:a}}}(e)}function He(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Me(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}function Ve(e){for(var t=0,r=[];xe(e,t);){var n=Me(e,t+6);e[t+5]>>6&1&&(t+=10);for(var i=(t+=10)+n;t+10<i;){var a=He(e.subarray(t)),s=Ke(a);s&&r.push(s),t+=a.size+10}Ne(e,t)&&(t+=10)}return r}function qe(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function We(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],n=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return n/=45,r&&(n+=47721858.84),Math.round(n)}}function Ye(e){var t,r=f(Ve(e));try{for(r.s();!(t=r.n()).done;){var n=t.value;if(qe(n))return We(n)}}catch(i){r.e(i)}finally{r.f()}}function ze(e){for(var t="",r=0;r<e.length;r++){var n=e[r].toString(16);n.length<2&&(n="0"+n),t+=n}return t}function Xe(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Qe(e){return Uint8Array.from(atob(e),function(e){return e.charCodeAt(0)})}function $e(e){return String.fromCharCode.apply(null,e)}var Je,Ze=Math.pow(2,32)-1,et={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},tt={video:1,audio:2,id3:3,text:4};function rt(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function nt(e,t){var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r}function it(e,t){var r=nt(e,t);return r*=Math.pow(2,32),r+=nt(e,t+4)}function at(e,t){for(var r="",n=t;n<e.length;n++)if(r+=String.fromCharCode(e[n]),0===e[n])return r;return null}function st(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ot(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function lt(e,t,r){var n=t.byteOffset-e.byteOffset-8,i=8+r,a=t.byteLength+8-i;a<8||(ot(e,n,i),ot(e,n+i,a),ot(e,n+i+4,et.free))}function ut(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function ct(e,t){t.sort(function(e,t){return e[0]-t[0]});for(var r=t.reduce(function(e,t){var r=L(t,2),n=r[0];return e+r[1]-n},0),n=new Uint8Array(e.byteLength-r),i=0,a=0,s=0;s<t.length;s++){var o=L(t[s],2),l=o[0],u=o[1];n.set(e.subarray(i,l),a),a+=l-i,i=u}n.set(e.subarray(i),a);return{result:n,dropped:r,droppedBefore:function(e){return t.reduce(function(t,r){var n=L(r,2),i=n[0],a=n[1];return a<=e?t+a-i:t},0)}}}function dt(e,t){var r=[];return t.length?(ht(e,t,0,0,e.byteLength,r),r):r}function ht(e,t,r,n,i,a){var s=t[r];if(4===(null==s?void 0:s.length))for(var o=s.charCodeAt(0),l=s.charCodeAt(1),u=s.charCodeAt(2),c=s.charCodeAt(3),d=t.length-1,h=n;h<i;){var f=h+8<=i,v=h+4<=i?16777216*e[h]+(e[h+1]<<16|e[h+2]<<8|e[h+3]):nt(e,h),g=v>1?h+v:i;if(f&&e[h+4]===o&&e[h+5]===l&&e[h+6]===u&&e[h+7]===c){var p=Math.min(g,i);r===d?a.push(e.subarray(h+8,p)):ht(e,t,r+1,h+8,p,a)}h=g}}function ft(e){var t=[],r=e[0],n=8,i=nt(e,n);n+=4;var a=0,s=0;0===r?(a=nt(e,n),s=nt(e,n+4),n+=8):(a=it(e,n),s=it(e,n+8),n+=16),n+=2;var o=e.length+s,l=rt(e,n);n+=2;for(var u=0;u<l;u++){var c=n,d=nt(e,c);c+=4;var h=2147483647&d;if(1===(2147483648&d)>>>31)return Le.warn("SIDX has hierarchical references (not supported)"),null;var f=nt(e,c);c+=4,t.push({referenceSize:h,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+h-1}}),o+=h,n=c+=4}return{earliestPresentationTime:a,timescale:i,version:r,referencesCount:l,references:t}}function vt(e){for(var t=[],r=dt(e,["moov","trak"]),n=0;n<r.length;n++){var i=r[n],a=dt(i,["tkhd"])[0];if(a){var s=a[0],o=nt(a,0===s?12:20),l=dt(i,["mdia","mdhd"])[0];if(l){var u=nt(l,0===(s=l[0])?12:20),c=dt(i,["mdia","hdlr"])[0];if(c){var d=$e(c.subarray(8,12)),h={soun:Y,vide:z}[d],f=gt(dt(i,["mdia","minf","stbl","stsd"])[0]);h?(t[o]={timescale:u,type:h,stsd:f},t[h]=se({timescale:u,id:o},f)):t[o]={timescale:u,type:d,stsd:f}}}}}return dt(e,["moov","mvex","trex"]).forEach(function(e){var r=nt(e,4),n=t[r];n&&(n.default={duration:nt(e,12),sampleSize:nt(e,16),flags:nt(e,20)})}),t}function gt(e){var t,r=e.subarray(8),n=r.subarray(86),i=$e(r.subarray(4,8)),a=i,s="enca"===i||"encv"===i;if(s){var o=dt(r,[i])[0];dt(o.subarray("enca"===i?28:78),["sinf"]).forEach(function(e){var t=dt(e,["schm"])[0];if(t){var r=$e(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var n=dt(e,["frma"])[0];n&&(a=$e(n))}}})}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=dt(n,["avcC"])[0];u&&u.length>3&&(a+="."+mt(u[1])+mt(u[2])+mt(u[3]),t=pt("avc1"===l?"dva1":"dvav",n));break;case"mp4a":var c=dt(r,[i])[0],d=dt(c.subarray(28),["esds"])[0];if(d&&d.length>7){var h=4;if(3!==d[h++])break;h=yt(d,h),h+=2;var f=d[h++];if(128&f&&(h+=2),64&f&&(h+=d[h++]),4!==d[h++])break;h=yt(d,h);var v=d[h++];if(64!==v)break;if(a+="."+mt(v),h+=12,5!==d[h++])break;h=yt(d,h);var g=d[h++],p=(248&g)>>3;31===p&&(p+=1+((7&g)<<3)+((224&d[h])>>5)),a+="."+p}break;case"hvc1":case"hev1":var y=dt(n,["hvcC"])[0];if(y&&y.length>12){var m=y[1],E=["","A","B","C"][m>>6],k=31&m,S=nt(y,2),T=(32&m)>>5?"H":"L",b=y[12],A=y.subarray(6,12);a+="."+E+k,a+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(S).toString(16).toUpperCase(),a+="."+T+b;for(var L="",R=A.length;R--;){var I=A[R];if(I||L)L="."+I.toString(16).toUpperCase()+L}a+=L}t=pt("hev1"==l?"dvhe":"dvh1",n);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=pt(a,n)||a;break;case"vp09":var w=dt(n,["vpcC"])[0];if(w&&w.length>6){var _=w[4],P=w[5],D=w[6]>>4&15;a+="."+Et(_)+"."+Et(P)+"."+Et(D)}break;case"av01":var C=dt(n,["av1C"])[0];if(C&&C.length>2){var O=C[1]>>>5,x=31&C[1],M=C[2]>>>7?"H":"M",F=(64&C[2])>>6,N=(32&C[2])>>5,U=2===O&&F?N?12:10:F?10:8,B=(16&C[2])>>4,G=(8&C[2])>>3,j=(4&C[2])>>2,K=3&C[2];a+="."+O+"."+Et(x)+M+"."+Et(U)+"."+B+"."+G+j+K+"."+Et(1)+"."+Et(1)+"."+Et(1)+".0",t=pt("dav1",n)}}return{codec:a,encrypted:s,supplemental:t}}function pt(e,t){var r=dt(t,["dvvC"]),n=r.length?r[0]:dt(t,["dvcC"])[0];if(n){var i=n[2]>>1&127,a=n[2]<<5&32|n[3]>>3&31;return e+"."+Et(i)+"."+Et(a)}}function yt(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function mt(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Et(e){return(e<10?"0":"")+e}function kt(e,t){dt(e,["moov","trak"]).forEach(function(e){var r=dt(e,["mdia","minf","stbl","stsd"])[0];if(r){var n=r.subarray(8),i=dt(n,["enca"]),a=i.length>0;a||(i=dt(n,["encv"])),i.forEach(function(e){dt(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(function(e){var r=St(e);r&&t(r,a)})})}})}function St(e){var t=dt(e,["schm"])[0];if(t){var r=$e(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var n=dt(e,["schi","tenc"])[0];if(n)return n}}}function Tt(e){return"undefined"==typeof TextDecoder?Ge(e):(Je||(Je=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function bt(e,t,r,n,i){for(var a={},s=!1,o=function(e){for(var t=e.byteLength,r=[],n=0;n<t;){var i=n+8<=t,a=n+4<=t?16777216*e[n]+(e[n+1]<<16|e[n+2]<<8|e[n+3]):nt(e,n),s=a>1?n+a:t;if(i&&109===e[n+4]&&111===e[n+5]&&111===e[n+6]&&102===e[n+7])for(var o=Math.min(s,t),l=n+8;l<o;){var u=l+8<=o,c=l+4<=o?16777216*e[l]+(e[l+1]<<16|e[l+2]<<8|e[l+3]):nt(e,l),d=c>1?l+c:o;if(u&&116===e[l+4]&&114===e[l+5]&&97===e[l+6]&&102===e[l+7]){for(var h=Math.min(d,o),f=void 0,v=void 0,g=[],p=l+8;p<h;){var y=p+8<=h,m=p+4<=h?16777216*e[p]+(e[p+1]<<16|e[p+2]<<8|e[p+3]):nt(e,p),E=m>1?p+m:h;if(y&&116===e[p+4]){var k=Math.min(E,h);102===e[p+5]&&104===e[p+6]&&100===e[p+7]?v||(v=e.subarray(p+8,k)):102===e[p+5]&&100===e[p+6]&&116===e[p+7]?f||(f=e.subarray(p+8,k)):114===e[p+5]&&117===e[p+6]&&110===e[p+7]&&g.push(e.subarray(p+8,k))}p=E}r.push({moofOffset:e.byteOffset+n,tfdt:f,tfhd:v,truns:g})}l=d}n=s}return r}(e),l=e.byteLength,u=0;u<o.length;u++){var c=o[u],d=c.moofOffset,h=c.tfdt,f=c.tfhd,v=c.truns,g=nt(f,4),p=t[g];if(p){var y=a[g]||(a[g]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:p.timescale,type:p.type}),m=void 0;if(h){var E=h[0];m=nt(h,4),1===E&&(m===Ze?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(m*=Ze+1,m+=nt(h,8))),x(m)&&(!x(y.start)||m<y.start)&&(y.start=m),i&&x(m)&&(i.timeOffset=m/i.timescale)}var k=(null==i?void 0:i.trackId)===g&&p.type===z,S=p.default,T=16777215&nt(f,0),b=(null==S?void 0:S.duration)||0,A=void 0,L=(null==S?void 0:S.sampleSize)||0,R=8;1&T&&(R+=8),2&T&&(R+=4),8&T&&(b=nt(f,R),A=f.byteOffset-e.byteOffset+R,R+=4),16&T&&(L=nt(f,R));var I=0,w=!!(1&T),_=!w&&!!(131072&T);w?(I=nt(f,8),I*=Math.pow(2,32),I+=nt(f,12)):_&&(I=d);for(var P=m||0,D=0,C=b,O=0;O<v.length;O++){var M=v[O],F=nt(M,4),N=y.sampleCount;y.sampleCount+=F;var U=1&M[3],B=0,G=4&M[3],j=1&M[2],K=2&M[2],H=4&M[2],V=8&M[2],q=8;if(U&&(B=st(M,q),q+=4),G)1&M[q+1]||void 0!==y.keyFrameIndex||(y.keyFrameIndex=N),q+=4;var W=I+B;if(n||0!==M[1]||6!==M[2]||1!==M[3]){var Y=void 0,X=void 0;n&&(X={sampleOffset:W,samples:Y=[],defaultSampleDurationOffset:A},W<=l&&y.trun.push(X));for(var Q=void 0,$=0;$<F;$++){var J=void 0;j?(n&&(J=M.byteOffset-e.byteOffset+q),C=nt(M,q),q+=4):C=b,K?(Q=nt(M,q),q+=4):Q=L;var Z=void 0,ee=void 0;H&&(ee=1&M[q+1]?1:0,n&&(Z={isNonSync:ee,dependsOn:1==(3&M[q])?1:2}),q+=4);var te=0;if(V)te=0===M[0]?nt(M,q):st(M,q),q+=4;if(k){for(var re=W,ne=0;ne<Q;){var ie=nt(e,re);re+=4,Rt(i.isHEVCFlavor,e[re])&&It(e.subarray(re,re+ie),i.isHEVCFlavor?2:1,i.timeOffset+te/i.timescale,i.samples),re+=ie,ne+=ie+4}i.timeOffset+=C/i.timescale}if((W+=Q)<=l){X&&void 0!==J&&(X.lastSampleDurationOffset=J),0===ee&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=$,y.keyFrameStart=P);var ae=P+te;(!x(y.ptsMin)||ae<y.ptsMin)&&(y.ptsMin=ae),(!x(y.ptsMax)||ae+C>y.ptsMax)&&(y.ptsMax=ae+C),Y&&(Y[$]={cts:te,duration:C,flags:Z,size:Q})}P+=C,D+=C}!D&&b&&(D+=b*F)}else{for(var se,oe,le=P,ue=W,ce=q,de=-1,he=0,fe=0,ve=null!=(se=null==i?void 0:i.timeOffset)?se:0,ge=b/(null!=(oe=null==i?void 0:i.timescale)?oe:1),pe=!0===(null==i?void 0:i.isHEVCFlavor),ye=pe?2:1,me=0;me<F;me++){var Ee=0===M[q]?M[q+1]<<16|M[q+2]<<8|M[q+3]:nt(M,q),ke=-1===de&&void 0===y.keyFrameIndex&&!(1&M[q+5]);q+=8;var Se=W+Ee;if(k){if(Ee>0){var Te=W;do{var be=0===e[Te]?e[Te+1]<<16|e[Te+2]<<8|e[Te+3]:nt(e,Te),Ae=e[Te+=4],Le=pe?Ae>>1&63:31&Ae;(pe?39===Le||40===Le:6===Le)&&It(e.subarray(Te,Te+be),ye,ve,i.samples),Te+=be}while(Te<Se)}ve+=ge}W=Se,ke&&(de=me,he=W)}if(W<=l)fe=F;else for(var Re=ue,Ie=ce,we=0;we<F;we++){if((Re+=0===M[Ie]?M[Ie+1]<<16|M[Ie+2]<<8|M[Ie+3]:nt(M,Ie))>l)break;fe=we+1,Ie+=8}if(k&&(i.timeOffset=ve),-1!==de&&he<=l&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=de,y.keyFrameStart=le+de*b),fe){(!x(y.ptsMin)||le<y.ptsMin)&&(y.ptsMin=le);var _e=le+fe*b;(!x(y.ptsMax)||_e>y.ptsMax)&&(y.ptsMax=_e)}var Pe=b*F;P=le+Pe,D+=Pe}}y.duration+=D,y.duration&&(s=!0)}}if(!s){for(var De=1/0,Ce=0,Oe=dt(e,["sidx"]),xe=0;xe<Oe.length;xe++){var Me=ft(Oe[xe]);if(null!=Me&&Me.references){De=Math.min(De,Me.earliestPresentationTime/Me.timescale);var Fe=Me.references.reduce(function(e,t){return e+t.info.duration||0},0);Ce=Math.max(Ce,Fe+Me.earliestPresentationTime/Me.timescale)}}Ce&&x(Ce)&&Object.keys(a).forEach(function(e){a[e].duration||(a[e].duration=Ce*a[e].timescale-a[e].start)})}return a}function At(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Lt(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Rt(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6===(31&t)}function It(e,t,r,n){var i=wt(e),a=0;a+=t;for(var s=0,o=0,l=0;a<i.length;){s=0;do{if(a>=i.length)break;s+=l=i[a++]}while(255===l);o=0;do{if(a>=i.length)break;o+=l=i[a++]}while(255===l);var u=i.length-a,c=a;if(o<u)a+=o;else if(o>u){Le.error("Malformed SEI payload. ".concat(o," is too small, only ").concat(u," bytes left to parse."));break}if(4===s){if(181===i[c++]){var d=rt(i,c);if(c+=2,49===d){var h=nt(i,c);if(c+=4,1195456820===h){var f=i[c++];if(3===f){var v=i[c++],g=64&v,p=g?2+3*(31&v):0,y=new Uint8Array(p);if(g){y[0]=v;for(var m=1;m<p;m++)y[m]=i[c++]}n.push({type:f,payloadType:s,pts:r,bytes:y})}}}}}else if(5===s&&o>16){for(var E=[],k=0;k<16;k++){var S=i[c++].toString(16);E.push(1==S.length?"0"+S:S),3!==k&&5!==k&&7!==k&&9!==k||E.push("-")}for(var T=o-16,b=new Uint8Array(T),A=0;A<T;A++)b[A]=i[c++];n.push({payloadType:s,pts:r,uuid:E.join(""),userData:Tt(b),userDataBytes:b})}}}function wt(e){for(var t,r=e.byteLength,n=e.indexOf(3,3);-1!==n;)0===e[n-1]&&0===e[n-2]&&(t||(t=[])).push(n),n=e.indexOf(3,n+1);if(!t)return e;for(var i=r-t.length,a=new Uint8Array(i),s=0,o=0,l=0;l<i;o++,l++)o===t[s]&&(o++,s++),a[l]=e[o];return a}function _t(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");var n,i;n=new Uint8Array,i=new Uint8Array;var a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];for(var i=r.length,a=8,s=i;s--;)a+=r[s].byteLength;var o=new Uint8Array(a);for(o[0]=a>>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(e,4),s=0,a=8;s<i;s++)o.set(r[s],a),a+=r[s].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,i,n,a,r)}function Pt(e){var t=[];if(e instanceof ArrayBuffer)for(var r=e.byteLength,n=0;n+32<r;){var i=Dt(new DataView(e,n));t.push(i),n+=i.size}return t}function Dt(e){var t=e.getUint32(0),r=e.byteOffset,n=e.byteLength;if(n<t)return{offset:r,size:n};if(1886614376!==e.getUint32(4))return{offset:r,size:t};var i=e.getUint32(8)>>>24;if(0!==i&&1!==i)return{offset:r,size:t};var a,s=e.buffer,o=ze(new Uint8Array(s,r+12,16)),l=null,u=0;if(0===i)u=28;else{var c=e.getUint32(28);if(!c||n<32+16*c)return{offset:r,size:t};l=[];for(var d=0;d<c;d++)l.push(new Uint8Array(s,r+32+16*d,16));u=32+16*c}if(!u)return{offset:r,size:t};var h=e.getUint32(u);return t-32<h?{offset:r,size:t}:(a=new Uint8Array(s,r+u+4,h),0===i&&(l=function(e){for(var t=[],r=0;r<e.length;){var n=e[r++],i=7&n;if(0!==i)if(2===i){for(var a=0,s=0,o=128;128&o;s+=7)a|=(127&(o=e[r++]))<<s;if(n>>3==2)if(32===a){for(var l=new Uint8Array(16),u=0;u<16;u++)l[u]=parseInt(String.fromCharCode(e[r+2*u],e[r+2*u+1]),16);t.push(l)}else 16===a&&t.push(e.subarray(r,r+16));r+=a}else r+=1===i?8:4;else for(;128&e[r++];);}return t}(a)),{version:i,systemId:o,kids:l,data:a,offset:r,size:t})}var Ct,Ot,xt,Mt=Nt("userAgent"),Ft=Nt("vendor");function Nt(e){try{return navigator[e]||""}catch(t){}return""}function Ut(){if(void 0===Ct){var e=Mt.match(/Chrome\/(\d+)/i);Ct=e?parseInt(e[1]):0}return Ct}function Bt(){return/\(Windows.+Firefox\//i.test(Mt)}var Gt={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function jt(e,t){var r=Gt[t];return!!r&&!!r[e.slice(0,4)]}function Kt(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return!e.split(",").some(function(e){return!Ht(e,t,r)})}function Ht(e,t){var r,n=Re(!(arguments.length>2&&void 0!==arguments[2])||arguments[2]);return null!=(r=null==n?void 0:n.isTypeSupported(Vt(e,t)))&&r}function Vt(e,t){return"".concat(t,"/mp4;codecs=").concat(e)}function qt(e){if(e){var t=e.substring(0,4);return Gt.video[t]}return 2}function Wt(e){var t=Bt();return e.split(",").reduce(function(e,r){var n=t&&Lt(r)?9:Gt.video[r];return n?(2*n+e)/(e?3:2):(Gt.audio[r]+e)/(e?2:1)},0)}var Yt={};var zt=/flac|opus|mp4a\.40\.34/i;function Xt(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.replace(zt,function(e){return function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(Yt[e])return Yt[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],n=0;n<r.length;n++){var i;if(Ht(r[n],"audio",t))return Yt[e]=r[n],r[n];if("mp3"===r[n]&&null!=(i=Re(t))&&i.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)})}function Qt(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&($t(e,"audio")||$t(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var n=r.length;n--;)if(r[n].substring(0,4)===e.substring(0,4))return r[n];return r[0]}}return t||e}function $t(e,t){return jt(e,t)&&Ht(e,t)}function Jt(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],n=t.length;n>4&&n<10;n++)t[n]=r[n-4];return t.join(".")}return e}function Zt(e){var t=Re(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function er(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var tr={supported:!1,smooth:!1,powerEfficient:!1},rr={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function nr(e,t){return{supported:!1,configurations:t,decodingInfoResults:[tr],error:e}}function ir(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=e.videoCodec;if(!i&&!e.audioCodec||!r)return Promise.resolve(rr);for(var a=[],s=function(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),n=sr(e),i=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(function(e){var t={contentType:Vt(Jt(e),"video"),width:i,height:a,bitrate:n,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=s.length,l=function(e,t,r){var n,i=null==(n=e.audioCodec)?void 0:n.split(","),a=sr(e);if(i&&e.audioGroups)return e.audioGroups.reduce(function(e,n){var s,o=n?null==(s=t.groups[n])?void 0:s.tracks:null;return o?o.reduce(function(e,t){if(t.groupId===n){var s=parseFloat(t.channels||"");i.forEach(function(t){var n={contentType:Vt(t,"audio"),bitrate:r?ar(t,a):a};s&&(n.channels=""+s),e.push(n)})}return e},e):e},[]);return[]}(e,t,o>0),u=l.length,c=o||1*u||1;c--;){var d={type:"media-source"};if(o&&(d.video=s[c%o]),u){d.audio=l[c%u];var h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}a.push(d)}if(i){var f=navigator.userAgent;if(i.split(",").some(function(e){return Lt(e)})&&Bt())return Promise.resolve(nr(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (".concat(f,")")),a))}return Promise.all(a.map(function(e){var t=function(e){var t="",r=e.audio,n=e.video;if(n){var i=er(n.contentType);t+="".concat(i,"_r").concat(n.height,"x").concat(n.width,"f").concat(Math.ceil(n.framerate)).concat(n.transferFunction||"sd","_").concat(Math.ceil(n.bitrate/1e5))}if(r){var a=er(r.contentType);t+="".concat(n?"_":"").concat(a,"_c").concat(r.channels)}return t}(e);return n[t]||(n[t]=r.decodingInfo(e))})).then(function(e){return{supported:!e.some(function(e){return!e.supported}),configurations:a,decodingInfoResults:e}}).catch(function(e){return{supported:!1,configurations:a,decodingInfoResults:[],error:e}})}function ar(e,t){if(t<=1)return 1;var r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function sr(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function or(e,t,r){var n=encodeURIComponent(t),i="".concat(n,"=").concat(encodeURIComponent(r)),a=!1,s=[];e.search.substring(1).split("&").forEach(function(e){e===n||e.startsWith(n+"=")?a||(s.push(i),a=!0):e&&s.push(e)}),a||s.push(i),e.search=s.join("&")}var lr=["NONE","TYPE-0","TYPE-1",null];var ur=["SDR","PQ","HLG"];var cr="",dr="YES",hr="v2";function fr(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,n=e.age;return t&&n<t/2?r?hr:dr:cr}var vr=function(){return h(function e(t,r,n){c(this,e),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=r,this.skip=n},[{key:"addDirectives",value:function(e){var t=new self.URL(e);return void 0!==this.msn&&or(t,"_HLS_msn",this.msn.toString()),void 0!==this.part&&or(t,"_HLS_part",this.part.toString()),this.skip&&or(t,"_HLS_skip",this.skip),t.href}}])}(),gr=function(){return h(function e(t){if(c(this,e),this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(function(e){return!!e}).map(function(e){return e.substring(0,4)}).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;var n=null==(r=t.supplemental)?void 0:r.videoCodec;n&&n!==t.videoCodec&&(this.codecSet+=",".concat(n.substring(0,4)))}"iframes"in t&&t.iframes?this.iframes=!0:(this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES))},[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"hasAudioGroup",value:function(e){return pr(this._audioGroups,e)}},{key:"hasSubtitleGroup",value:function(e){return pr(this._subtitleGroups,e)}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"addGroupId",value:function(e,t){if(t)if("audio"===e){var r=this._audioGroups;r||(r=this._audioGroups=[]),-1===r.indexOf(t)&&r.push(t)}else if("text"===e){var n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),-1===n.indexOf(t)&&n.push(t)}}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}},{key:"addFallback",value:function(){}}])}();function pr(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function yr(e,t){var r=!1,n=[];if(e&&(r="SDR"!==e,n=[e]),t){var i="SDR"!==(n=t.allowedVideoRanges||ur.slice(0)).join("")&&!t.videoCodec;(r=void 0!==t.preferHDR?t.preferHDR:i&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}var mr=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(r,n){if(e&&(n=e(r,n)),"object"===_(n)&&null!==n){if(t.has(n))return;t.add(n)}return n}}(t))};function Er(e,t){Le.log('[abr] start candidates with "'.concat(e,'" ignored because ').concat(t))}function kr(e){return e.reduce(function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var n=t.channels||"2";return r.channels[n]=(r.channels[n]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Sr(e){return e?{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}:e}function Tr(e,t,r){if("attrs"in e){var n=t.indexOf(e);if(-1!==n)return n}for(var i=0;i<t.length;i++){if(br(e,t[i],r))return i}return-1}function br(e,t,r){var n=e.groupId,i=e.name,a=e.lang,s=e.assocLang,o=e.default,l=e.forced;return(void 0===n||t.groupId===n)&&(void 0===i||t.name===i)&&(void 0===a||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"--";if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(a,t.lang))&&(void 0===s||t.assocLang===s)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=e.split(","),n=t.split(",");return r.length===n.length&&!r.some(function(e){return-1===n.indexOf(e)})}(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function Ar(e,t){var r=e.audioCodec,n=e.channels;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==n&&n!==(t.channels||"2"))}function Lr(e,t,r){for(var n=t;n>-1;n--)if(r(e[n]))return n;for(var i=t+1;i<e.length;i++)if(r(e[i]))return i;return-1}function Rr(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}function Ir(e,t){return!t||-1!==t.indexOf(e)}function wr(e,t){if(t||e){var r=ie({},t);return e&&(e.videoCodec&&(r.videoCodec=e.videoCodec),e.videoRange&&(r.allowedVideoRanges=[e.videoRange])),r}}var _r=function(e){function t(e){var r;return c(this,t),(r=u(this,t,["abr",e.logger])).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r.firstAutoFloor=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.supportedCache={},r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,n=r,i=n.fragCurrent,a=n.partCurrent,s=n.hls;if(s){var o=s.autoLevelEnabled,l=s.media;if(i&&l){var u=performance.now(),c=a?a.stats:i.stats,d=a?a.duration:i.duration,h=u-c.loading.start,f=s.minAutoLevel,v=i.level,g=r._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||v<=f)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var p=g>-1&&g!==v,y=!!e||p;if(y||!l.paused&&l.playbackRate&&l.readyState){var m=s.mainForwardBufferInfo;if(y||null!==m){var E=r.bwEstimator.getEstimateTTFB(),k=Math.abs(l.playbackRate);if(!(h<=Math.max(E,d/(2*k)*1e3))){var S=m?m.len/k:0,T=c.loading.first?c.loading.first-c.loading.start:-1,b=c.loaded&&T>-1,A=r.getBwEstimate(),L=s.levels,R=L[v],I=Math.max(c.loaded,Math.round(d*(i.bitrate||R.averageBitrate)/8)),w=b?h-T:h;w<1&&b&&(w=Math.min(h,8*c.loaded/A));var _=b?1e3*c.loaded/w:0,P=E/1e3,D=_?(I-c.loaded)/_:8*I/A+P;if(!(D<=S)){var C,O=_?8*_:A,M=!0===(null==(t=(null==e?void 0:e.details)||s.latestLevelDetails)?void 0:t.live),F=s.config.abrBandWidthUpFactor,N=Number.POSITIVE_INFINITY;for(C=v-1;C>f;C--){var U=L[C].maxBitrate,G=!L[C].details||M;if((N=r.getTimeToLoadFrag(P,O,d*U,G))<Math.min(S,d+P))break}if(!(N>=D||N>10*d)){b?r.bwEstimator.sample(h-Math.min(E,T),c.loaded):r.bwEstimator.sampleTTFB(h);var j=L[C].maxBitrate;r.getBwEstimate()*F>j&&(r.firstAutoFloor=Math.min(C,s.firstLevel),r.resetEstimator(j));var K=r.findBestLevel(j,f,C,0,S,1,1);K>-1&&(C=K),r.warn("Fragment ".concat(i.sn).concat(a?" part "+a.index:""," of level ").concat(v," is loading too slowly;\n Fragment duration: ").concat(i.duration.toFixed(3),"\n Time to underbuffer: ").concat(S.toFixed(3)," s\n Estimated load time for current fragment: ").concat(D.toFixed(3)," s\n Estimated load time for down switch fragment: ").concat(N.toFixed(3)," s\n TTFB estimate: ").concat(0|T," ms\n Current BW estimate: ").concat(x(A)?0|A:"Unknown"," bps\n New BW estimate: ").concat(0|r.getBwEstimate()," bps\n Switching to level ").concat(C," @ ").concat(0|j," bps")),s.nextLoadLevel=s.nextAutoLevel=C,r.clearTimer();var H=function(){r.clearTimer();var e=r.hls;if(r.fragCurrent===i&&e.loadLevel===C&&C>0){var t=r.getStarvationDelay();if(r.warn("Aborting inflight request ".concat(C>0?"and switching down":"","\n Fragment duration: ").concat(i.duration.toFixed(3)," s\n Time to underbuffer: ").concat(t.toFixed(3)," s")),i.abortRequests(),r.fragCurrent=r.partCurrent=null,C>f){var n=r.findBestLevel(e.levels[f].bitrate,f,C,0,t,1,1);-1===n&&(n=f),e.nextLoadLevel=e.nextAutoLevel=n,r.firstAutoFloor=Math.min(n,e.firstLevel),r.resetEstimator(e.levels[n].bitrate)}}};p||D>2*N?H():r.timer=self.setInterval(H,1e3*N),s.trigger(B.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:a,stats:c})}}}}}}}}},r.hls=e,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}return y(t,e),h(t,[{key:"resetEstimator",value:function(e){this.hls&&(e&&(this.log("setting initial bwe to ".concat(e)),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}},{key:"initEstimator",value:function(){var e=this.hls.config;return new me(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}},{key:"registerListeners",value:function(){var e=this.hls;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.FRAG_LOADING,this.onFragLoading,this),e.on(B.FRAG_LOADED,this.onFragLoaded,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(B.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.FRAG_LOADING,this.onFragLoading,this),e.off(B.FRAG_LOADED,this.onFragLoaded,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(B.ERROR,this.onError,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}},{key:"onManifestLoading",value:function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}},{key:"onLevelsUpdated",value:function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}},{key:"onMaxAutoLevelUpdated",value:function(){this.firstSelection=-1,this.nextAutoLevelKey=""}},{key:"onFragLoading",value:function(e,t){var r=t.frag;if(!this.ignoreFragment(r)){var n;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(n=t.part)?n:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}},{key:"onLevelSwitching",value:function(e,t){this.clearTimer()}},{key:"onError",value:function(e,t){if(!t.fatal)switch(t.details){case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case U.FRAG_LOAD_TIMEOUT:var r=t.frag,n=this.fragCurrent,i=this.partCurrent;if(r&&Z(r,n)){var a=performance.now(),s=i?i.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}}},{key:"getTimeToLoadFrag",value:function(e,t,r,n){return e+r/t+(n?e+this.lastLevelLoadSec:0)}},{key:"onLevelLoaded",value:function(e,t){var r=this.hls.config,n=t.stats.loading,i=n.end-n.first;x(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}},{key:"onFragLoaded",value:function(e,t){var r,n=t.frag,i=t.part,a=i?i.stats:n.stats;if(n.type===W.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(n)){if(this.clearTimer(),n.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(r=this.hls)&&r.config.abrMaxWithRealBitrate){var s=i?i.duration:n.duration,o=this.hls.levels[n.level],l=(o.loaded?o.loaded.bytes:0)+a.loaded,u=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:l,duration:u},o.realBitrate=Math.round(8*l/u)}if(n.bitrateTest){var c={stats:a,frag:n,part:i,id:n.type};this.onFragBuffered(B.FRAG_BUFFERED,c),n.bitrateTest=!1}else this.lastLoadedFragLevel=n.level}}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,n=t.part,i=null!=n&&n.stats.loaded?n.stats:r.stats;if(!i.aborted&&!this.ignoreFragment(r)){var a=((r.bitrate||0)>=1e5?i.parsing.end:i.loading.end)-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}}},{key:"ignoreFragment",value:function(e){return e.type!==W.MAIN||"initSegment"===e.sn}},{key:"clearTimer",value:function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}},{key:"firstAutoLevel",get:function(){var e=this.hls;if(!e)return 0;var t=e.maxAutoLevel,r=e.minAutoLevel,n=this.getBwEstimate(),i=this.getStarvationDelay(),a=e.config.maxStarvationDelay,s=this.findBestLevel(n,r,t,i/2,a,1,1);if(s>-1)return s;var o=e.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,u=Math.min(Math.max(o,r),t,l);return this.warn("Could not find best starting auto level. Defaulting to first in playlist ".concat(o," clamped to ").concat(u)),u}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){if(!this.hls)return-1;var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var n=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var i=this.hls.levels;if(i.length>Math.max(e,n)&&i[e].loadError<=i[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}},{key:"getAutoLevelKey",value:function(){return"".concat(this.getBwEstimate(),"_").concat(this.getStarvationDelay().toFixed(2))}},{key:"getNextABRAutoLevel",value:function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(!r)return-1;if(r.levels.length<=1)return r.loadLevel;var n=r.maxAutoLevel,i=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=i.abrBandWidthFactor,c=i.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,a,n,l,0,u,c);if(d>=0)return this.rebufferNotice=-1,d}var h=s?Math.min(s,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;if(f)h=(s?Math.min(s,i.maxLoadingDelay):i.maxLoadingDelay)-f,this.info("bitrate test took ".concat(Math.round(1e3*f),"ms, set first fragment max fetchDuration to ").concat(Math.round(1e3*h)," ms")),u=c=1}var v=this.findBestLevel(o,a,n,l,h,u,c);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info("".concat(l?"rebuffering expected":"buffer is empty",", optimal quality level ").concat(v))),v>-1)return v;var g=r.levels[a],p=r.loadLevelObj;return p&&(null==g?void 0:g.bitrate)<p.bitrate?a:r.loadLevel}},{key:"getStarvationDelay",value:function(){var e=this.hls,t=null==e?void 0:e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/r}},{key:"getBwEstimate",value:function(){return this.bwEstimator.getEstimate()}},{key:"findBestLevel",value:function(e,t,r,n,i,a,s){var o=this,l=this.hls,u=this.lastLoadedFragLevel,c=this.fragCurrent,d=this.partCurrent;if(!l)return-1;var h=n+i,f=-1===u?l.firstLevel:u,v=l.levels,g=l.allAudioTracks,p=l.loadLevel,y=l.latestLevelDetails,m=l.config;if(1===v.length)return 0;var E,k=v[f],S=!(null==y||!y.live),T=-1===p||-1===u,b="SDR",A=(null==k?void 0:k.frameRate)||0,L=m.audioPreference,R=m.videoPreference,I=this.audioTracksByGroup||(this.audioTracksByGroup=kr(g)),w=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;var _=this.codecTiers||(this.codecTiers=function(e,t,r,n){return e.slice(r,n+1).reduce(function(e,r,n){if(!r.codecSet)return e;var i=r.audioGroups,a=e[r.codecSet];a||(e[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,r.bitrate);var s=Math.min(r.height,r.width);return a.minHeight=Math.min(a.minHeight,s),a.minFramerate=Math.min(a.minFramerate,r.frameRate),a.minIndex=Math.min(a.minIndex,n),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,i&&i.forEach(function(e){if(e){var r=t.groups[e];r&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach(function(e){a.channels[e]=(a.channels[e]||0)+r.channels[e]}))}}),e},{})}(v,I,t,r)),P=function(e,t,r,n,i){for(var a=Object.keys(e),s=null==n?void 0:n.channels,o=null==n?void 0:n.audioCodec,l=null==i?void 0:i.videoCodec,u=s&&2===parseInt(s),c=!1,d=!1,h=1/0,f=1/0,v=1/0,g=1/0,p=0,y=[],m=yr(t,i),E=m.preferHDR,k=m.allowedVideoRanges,S=function(){var t=e[a[T]];c||(c=t.channels[2]>0),h=Math.min(h,t.minHeight),f=Math.min(f,t.minFramerate),v=Math.min(v,t.minBitrate);var r=k.filter(function(e){return t.videoRanges[e]>0});r.length>0&&(d=!0)},T=a.length;T--;)S();h=x(h)?h:0,f=x(f)?f:0;var b=Math.max(1080,h),A=Math.max(30,f);v=x(v)?v:r,r=Math.max(v,r),d||(t=void 0);var L=a.length>1,R=a.reduce(function(t,n){var i=e[n];if(n===t)return t;if(y=d?k.filter(function(e){return i.videoRanges[e]>0}):[],L){if(i.minBitrate>r)return Er(n,"min bitrate of ".concat(i.minBitrate," > current estimate of ").concat(r)),t;if(!i.hasDefaultAudio)return Er(n,"no renditions with default or auto-select sound found"),t;if(o&&n.indexOf(o.substring(0,4))%5!=0)return Er(n,'audio codec preference "'.concat(o,'" not found')),t;if(s&&!u){if(!i.channels[s])return Er(n,"no renditions with ".concat(s," channel sound found (channels options: ").concat(Object.keys(i.channels),")")),t}else if((!o||u)&&c&&0===i.channels[2])return Er(n,"no renditions with stereo sound found"),t;if(i.minHeight>b)return Er(n,"min resolution of ".concat(i.minHeight," > maximum of ").concat(b)),t;if(i.minFramerate>A)return Er(n,"min framerate of ".concat(i.minFramerate," > maximum of ").concat(A)),t;if(!y.some(function(e){return i.videoRanges[e]>0}))return Er(n,"no variants with VIDEO-RANGE of ".concat(mr(y)," found")),t;if(l&&n.indexOf(l.substring(0,4))%5!=0)return Er(n,'video codec preference "'.concat(l,'" not found')),t;if(i.maxScore<p)return Er(n,"max score of ".concat(i.maxScore," < selected max of ").concat(p)),t}return t&&(Wt(n)>=Wt(t)||i.fragmentError>e[t].fragmentError)?t:(g=i.minIndex,p=i.maxScore,n)},void 0);return{codecSet:R,videoRanges:y,preferHDR:E,minFramerate:f,minBitrate:v,minIndex:g}}(_,b,e,L,R),D=P.codecSet,C=P.videoRanges,O=P.minFramerate,M=P.minBitrate,F=P.minIndex,N=P.preferHDR;w=F,E=D,b=N?C[C.length-1]:C[0],A=O,e=Math.max(e,M),this.log("picked start tier ".concat(mr(P)))}else E=null==k?void 0:k.codecSet,b=null==k?void 0:k.videoRange;for(var U,B,G=d?d.duration:c?c.duration:0,j=this.bwEstimator.getEstimateTTFB()/1e3,K=[],H=function(){var t=v[V],l=V>f;if(!t)return 0;if(m.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){var c=navigator.mediaCapabilities;"function"==typeof(null==c?void 0:c.decodingInfo)&&function(e,t,r,n,i,a){var s=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==a?void 0:a.audioCodec,u=null==a?void 0:a.channels,c=u?parseInt(u):l?1/0:2,d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce(function(e,r){if(r){var n=t.groups[r];if(!n)throw new Error("Audio track group ".concat(r," not found"));Object.keys(n.channels).forEach(function(t){e[t]=(e[t]||0)+n.channels[t]})}return e},{2:0})}catch(h){return!0}return void 0!==s&&(s.split(",").some(function(e){return Lt(e)})||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(n,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(i,8e6))||!!d&&x(c)&&Object.keys(d).some(function(e){return parseInt(e)>c})}(t,I,b,A,e,L)?(t.supportedPromise=ir(t,I,c,o.supportedCache),t.supportedPromise.then(function(e){if(o.hls){t.supportedResult=e;var r=o.hls.levels,n=r.indexOf(t);e.error?o.warn('MediaCapabilities decodingInfo error: "'.concat(e.error,'" for level ').concat(n," ").concat(mr(e))):e.supported?e.decodingInfoResults.some(function(e){return!1===e.smooth||!1===e.powerEfficient})&&o.log("MediaCapabilities decodingInfo for level ".concat(n," not smooth or powerEfficient: ").concat(mr(e))):(o.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(n," ").concat(mr(e))),n>-1&&r.length>1&&(o.log("Removing unsupported level ".concat(n)),o.hls.removeLevel(n),-1===o.hls.loadLevel&&(o.hls.nextLoadLevel=0)))}}).catch(function(e){o.warn("Error handling MediaCapabilities decodingInfo: ".concat(e))})):t.supportedResult=rr}if((E&&t.codecSet!==E||b&&t.videoRange!==b||l&&A>t.frameRate||!l&&A>0&&A<t.frameRate||null!=(U=t.supportedResult)&&null!=(U=U.decodingInfoResults)&&U.some(function(e){return!1===e.smooth}))&&(!T||V!==w))return K.push(V),0;var g,y=t.details,k=(d?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||G||1;g=l?s*e:a*e;var R=G&&n>=2*G&&0===i?t.averageBitrate:t.maxBitrate,_=o.getTimeToLoadFrag(j,g,R*k,!y||y.live);if(g>=R&&(V===u||0===t.loadError&&0===t.fragmentError||pe(t,m.errorPenaltyExpireMs))&&(_<=j||!x(_)||S&&!o.bitrateTestDelay||_<h)){var P=o.forcedAutoLevel;return V===p||-1!==P&&P===p||(K.length&&o.trace("Skipped level(s) ".concat(K.join(",")," of ").concat(r,' max with CODECS and VIDEO-RANGE:"').concat(v[K[0]].codecs,'" ').concat(v[K[0]].videoRange,'; not compatible with "').concat(E,'" ').concat(b)),o.info("switch candidate:".concat(f,"->").concat(V," adjustedbw(").concat(Math.round(g),")-bitrate=").concat(Math.round(g-R)," ttfb:").concat(j.toFixed(1)," avgDuration:").concat(k.toFixed(1)," maxFetchDuration:").concat(h.toFixed(1)," fetchDuration:").concat(_.toFixed(1)," firstSelection:").concat(T," codecSet:").concat(t.codecSet," videoRange:").concat(t.videoRange," hls.loadLevel:").concat(p))),T&&(o.firstSelection=V),{v:V}}},V=r;V>=t;V--)if(0!==(B=H())&&B)return B.v;return-1}},{key:"deriveNextAutoLevel",value:function(e){if(!this.hls)return-1;var t=this.hls,r=t.maxAutoLevel,n=t.minAutoLevel;return Math.min(Math.max(e,n),r)}}])}(Ee),Pr=function(e,t){for(var r=0,n=e.length-1,i=null,a=null;r<=n;){var s=t(a=e[i=(r+n)/2|0]);if(s>0)r=i+1;else{if(!(s<0))return a;n=i-1}}return null};function Dr(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.005,a=null;if(e){a=t[1+e.sn-t[0].sn]||null;var s=e.endDTS-r;s>0&&s<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===Cr(r,n,a)||function(e,t,r){if(0===(null==t?void 0:t.start)&&t.level<e.level&&(t.endPTS||0)>0){var n=t.tagList.reduce(function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e},r);return e.start<=n}return!1}(a,e,Math.min(i,n))))return a;var o=Pr(t,Cr.bind(null,r,n));return!o||o===e&&a?a:o}function Cr(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2?arguments[2]:void 0;if(r.start<=e&&r.start+r.duration>e)return 0;var n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=e?1:r.start-n>e&&r.start?-1:0}function Or(e,t,r){var n=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-n>e}function xr(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var n,i=e.fragments,a=e.fragmentHint;return a&&(i=i.concat(a)),Pr(i,function(e){return e.cc<t?1:e.cc>t?-1:(n=e,e.end<=r?1:e.start>r?-1:0)}),n||null}return null}function Mr(e,t){return t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}var Fr=0,Nr=2,Ur=3,Br=5,Gr=0,jr=1,Kr=2,Hr=4,Vr=8,qr=16,Wr=function(e){function t(e){var r;return c(this,t),(r=u(this,t,["error-controller",e.logger])).hls=void 0,r.playlistError=0,r.hls=e,r.registerListeners(),r}return y(t,e),h(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(B.ERROR,this.onError,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.ERROR,this.onError,this),e.off(B.ERROR,this.onErrorOut,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.hls=null}},{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){this.playlistError=0}},{key:"getVariantLevelIndex",value:function(e){return(null==e?void 0:e.type)===W.MAIN?e.level:this.getVariantIndex()}},{key:"getVariantIndex",value:function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}},{key:"variantHasKey",value:function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(function(e){return n.indexOf(e.groupId)>=0}).some(function(e){var r;return null==(r=e.details)?void 0:r.hasKey(t)})}return!1}},{key:"onManifestLoading",value:function(){this.playlistError=0}},{key:"onLevelUpdated",value:function(){this.playlistError=0}},{key:"onError",value:function(e,t){var r;if(!t.fatal){var n=this.hls,i=t.context;switch(t.details){case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case U.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=Xr());case U.FRAG_GAP:case U.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Nr);case U.PLAYLIST_UNCHANGED_ERROR:case U.LEVEL_EMPTY_ERROR:case U.LEVEL_PARSING_ERROR:var a,s=t.parent===W.MAIN?t.level:n.loadLevel;return void(t.details===U.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(a=a.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,s)));case U.LEVEL_LOAD_ERROR:case U.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case U.AUDIO_TRACK_LOAD_ERROR:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.SUBTITLE_LOAD_ERROR:case U.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){var o=n.loadLevelObj;if(o&&(i.type===q.AUDIO_TRACK&&o.hasAudioGroup(i.groupId)||i.type===q.SUBTITLE_TRACK&&o.hasSubtitleGroup(i.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Nr,void(t.errorAction.flags=jr)}return;case U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:Nr,flags:Kr});case U.KEY_SYSTEM_SESSION_UPDATE_FAILED:case U.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case U.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:Nr,flags:Hr});case U.BUFFER_ADD_CODEC_ERROR:case U.REMUX_ALLOC_ERROR:case U.BUFFER_APPEND_ERROR:return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)));case U.MEDIA_SOURCE_REQUIRES_RESET:return t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),void(t.errorAction.flags|=qr|Vr);case U.INTERNAL_EXCEPTION:case U.BUFFER_APPENDING_ERROR:case U.BUFFER_APPEND_NO_PROGRESS:case U.BUFFER_FULL_ERROR:case U.LEVEL_SWITCH_ERROR:case U.BUFFER_STALLED_ERROR:case U.BUFFER_SEEK_OVER_HOLE:case U.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=Xr())}t.type===N.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Xr())}}},{key:"getPlaylistRetryOrSwitchAction",value:function(e,t){var r=de(this.hls.config.playlistLoadPolicy,e),n=this.playlistError++;if(ve(r,n,le(e),e.response))return{action:Br,flags:Gr,retryConfig:r,retryCount:n};var i=this.getLevelSwitchAction(e,t);return r&&(i.retryConfig=r,i.retryCount=n),i}},{key:"getFragRetryOrSwitchAction",value:function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],i=t.config,a=i.fragLoadPolicy,s=i.keyLoadPolicy,o=de(ue(e)?s:a,e),l=t.levels.reduce(function(e,t){return e+t.fragmentError},0);if(n&&(e.details!==U.FRAG_GAP&&n.fragmentError++,!ce(e)&&ve(o,l,le(e),e.response)))return{action:Br,flags:Gr,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u}},{key:"getLevelSwitchAction",value:function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var n=this.hls.levels[t];if(n){var i,a,s=e.details;n.loadError++,n.loadErrorTime=self.performance.now(),s===U.BUFFER_APPEND_ERROR&&n.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,c=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var h,f,v,g=null==(i=e.frag)?void 0:i.type,p=(g===W.AUDIO&&s===U.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&Yr(e))&&l.some(function(e){var t=e.audioCodec;return n.audioCodec!==t}),y="video"===e.sourceBufferName&&Yr(e)&&l.some(function(e){var t=e.codecSet,r=e.audioCodec;return n.codecSet!==t&&n.audioCodec===r}),m=null!=(a=e.context)?a:{},E=m.type,k=m.groupId,S=function(){var t=(T+u)%l.length;if(t!==u&&t>=c&&t<=d&&(0===l[t].loadError||pe(l[t],r.config.errorPenaltyExpireMs))){var i=l[t];if(s===U.FRAG_GAP&&g===W.MAIN&&e.frag){var a=l[t].details;if(a){var v=Dr(e.frag,a.fragments,e.frag.start);if(null!=v&&v.gap)return 0}}else{if(E===q.AUDIO_TRACK&&i.hasAudioGroup(k)||E===q.SUBTITLE_TRACK&&i.hasSubtitleGroup(k))return 0;if(g===W.AUDIO&&null!=(h=n.audioGroups)&&h.some(function(e){return i.hasAudioGroup(e)})||g===W.SUBTITLE&&null!=(f=n.subtitleGroups)&&f.some(function(e){return i.hasSubtitleGroup(e)})||p&&n.audioCodec===i.audioCodec||y&&n.codecSet===i.codecSet||!p&&n.audioCodec!==i.audioCodec)return 0}return o=t,1}},T=l.length;T--&&(0===(v=S())||1!==v););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:Nr,flags:Gr,nextAutoLevel:o}}return{action:Nr,flags:jr}}},{key:"onErrorOut",value:function(e,t){var r,n;switch(null==(r=t.errorAction)?void 0:r.action){case Fr:break;case Nr:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===U.FRAG_GAP||t.details===U.PLAYLIST_UNCHANGED_ERROR||zr(t)||(t.fatal=!0)}((null==(n=t.errorAction)?void 0:n.flags)||0)&qr&&this.hls.recoverMediaError(),t.fatal&&this.hls.stopLoad()}},{key:"sendAlternateToPenaltyBox",value:function(e){var t=this.hls,r=e.errorAction;if(r){var n=r.nextAutoLevel;if(r.flags===Gr)this.switchLevel(e,n);else if(r.flags&Vr)for(var i=this.hls.levels,a=i.length;a--;)"SDR"!==i[a].videoRange?(i[a].fragmentError++,i[a].loadError++):void 0===n&&(n=a);else if(r.flags&Kr){var s=this.getVariantLevelIndex(e.frag),o=t.levels[s],l=null==o?void 0:o.attrs["HDCP-LEVEL"];r.hdcpLevel=l;var u="NONE"===l;l&&!u?(t.maxHdcpLevel=lr[lr.indexOf(l)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'))):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),r.flags|=Hr)}if(r.flags&Hr){var c=e.decryptdata;if(c){for(var d=this.hls.levels,h=d.length,f=h;f--;){var v,g;if(this.variantHasKey(d[f],c))this.log("Banned key found in level ".concat(f," (").concat(d[f].bitrate,'bps) or audio group "').concat(null==(v=d[f].audioGroups)?void 0:v.join(","),'" (').concat(null==(g=e.frag)?void 0:g.type," fragment) ").concat(ze(c.keyId||[]))),d[f].fragmentError++,d[f].loadError++,this.log("Removing level ".concat(f," with key error (").concat(e.error,")")),this.hls.removeLevel(f)}var p=e.frag;if(this.hls.levels.length<h)r.resolved=!0;else if(p&&p.type!==W.MAIN){var y=p.decryptdata;y&&!c.matches(y)&&(r.resolved=!0)}}}r.resolved||this.switchLevel(e,n)}}},{key:"switchLevel",value:function(e,t){if(void 0!==t&&e.errorAction&&(this.warn("switching to level ".concat(t," after ").concat(e.details)),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===U.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var r=er(e.mimeType),n=this.hls.levels,i=n.length;i--;)n[i]["".concat(e.sourceBufferName,"Codec")]===r&&(this.log("Removing level ".concat(i," for ").concat(e.details,' ("').concat(r,'" not supported)')),this.hls.removeLevel(i))}}])}(Ee);function Yr(e){var t=e.details;return t===U.BUFFER_ADD_CODEC_ERROR||t===U.MEDIA_SOURCE_REQUIRES_RESET||t===U.BUFFER_APPEND_ERROR&&!zr(e)}function zr(e){return e.details===U.BUFFER_APPEND_ERROR&&("QuotaExceededError"===e.error.name||"InvalidStateError"===e.error.name)}function Xr(e){var t={action:Fr,flags:Gr};return e&&(t.resolved=!0),t}var Qr="NOT_LOADED",$r="APPENDING",Jr="PARTIAL",Zr="OK",en=function(){return h(function e(t){c(this,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=t,this._registerListeners()},[{key:"_registerListeners",value:function(){var e=this.hls;e&&(e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.BUFFER_APPENDED,this.onBufferAppended,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.FRAG_LOADED,this.onFragLoaded,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.BUFFER_APPENDED,this.onBufferAppended,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.FRAG_LOADED,this.onFragLoaded,this))}},{key:"destroy",value:function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}},{key:"getAppendedFrag",value:function(e,t){var r=this.activePartLists[t];if(r)for(var n=r.length;n--;){var i=r[n];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}return this.getBufferedFrag(e,t)}},{key:"getBufferedFrag",value:function(e,t){return this.getFragAtPos(e,t,!0)}},{key:"getFragAtPos",value:function(e,t,r){for(var n=this.fragments,i=Object.keys(n),a=i.length;a--;){var s=n[i[a]];if((null==s?void 0:s.body.type)===t&&(!r||s.buffered)){var o=s.body;if(o.start<=e&&e<=o.end)return o}}return null}},{key:"detectEvictedFragments",value:function(e,t,r,n,i,a){var s=this;this.timeRanges&&(this.timeRanges[e]=t);var o=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(i){var l=s.fragments[i];if(l&&s.hls){var u=l.body;if(!(o>=u.sn))if(l.buffered||l.loaded&&!a){var c=l.range[e];if(c)if(0!==c.time.length){if(c.time.some(function(e){var r=!s.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&s.removeFragment(u),r}),n&&n!==u&&Ut()){var d=n.endPTS,h=u.startPTS;if(d&&h&&l.range.video){var f=h-d;f<0&&f>-.1&&(s.removeFragment(u),s.hls.trigger(B.BUFFER_FLUSHING,{startOffset:d+.004,endOffset:1/0,type:"video"}))}}}else s.removeFragment(u)}else u.type===r&&s.removeFragment(u)}})}},{key:"detectPartialFragments",value:function(e){var t=this,r=this.timeRanges,n=e.frag,i=e.part,a=e.id;if(r&&$(n)){var s=rn(n),o=this.fragments[s];if(!(!o||o.buffered&&n.gap)){var l=!n.relurl;Object.keys(r).forEach(function(e){var s=n.elementaryStreams[e];if(s){var u=r[e],c=l||!0===s.partial;o.range[e]=t.getBufferedTimes(n,i,c,u),t.detectEvictedFragments(e,u,a,n,i)}}),o.loaded=null;var u=Object.keys(o.range);if(u.length){if(this.bufferedEnd(o,n),tn(o)||this.removeParts(n.sn-1,n.type),!i){var c=Math.min(.004,n.duration);u.some(function(e){var r,i=null==(r=o.range[e])?void 0:r.time,a=0===i.length||1===i.length&&i[0].endPTS-i[0].startPTS<c;return a&&t.addAsGap(n),a})}}else this.removeFragment(n)}}}},{key:"addAsGap",value:function(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}},{key:"bufferedEnd",value:function(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}},{key:"removeParts",value:function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=nn(r,function(t){return t.fragment.sn>=e}))}},{key:"fragBuffered",value:function(e,t){var r=rn(e),n=this.fragments[r];return!n&&t&&(n=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e)),n}},{key:"getBufferedTimes",value:function(e,t,r,n){for(var i={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<n.length;u++){var c=n.start(u)-this.bufferPadding,d=n.end(u)+this.bufferPadding;if(l>=c&&o<=d){i.time.push({startPTS:Math.max(a,n.start(u)),endPTS:Math.min(s,n.end(u))});break}if(a<d&&s>c){var h=Math.max(a,n.start(u)),f=Math.min(s,n.end(u));f>h&&(i.partial=!0,i.time.push({startPTS:h,endPTS:f}))}else if(s<=c)break}return i}},{key:"getPartialFragment",value:function(e){var t,r,n,i=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach(function(l){var u=o[l];u&&tn(u)&&(r=u.body.start-s,n=u.body.end+s,e>=r&&e<=n&&(t=Math.min(e-r,n-e),a<=t&&(i=u.body,a=t)))}),i}},{key:"isEndListAppended",value:function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||tn(t))}},{key:"getState",value:function(e){var t=rn(e),r=this.fragments[t];return r?r.buffered?tn(r)?Jr:Zr:$r:Qr}},{key:"isTimeBuffered",value:function(e,t,r){for(var n,i,a=0;a<r.length;a++){if(n=r.start(a)-this.bufferPadding,i=r.end(a)+this.bufferPadding,e>=n&&t<=i)return!0;if(t<=n)return!1}return!1}},{key:"onManifestLoading",value:function(){this.removeAllFragments()}},{key:"onFragLoaded",value:function(e,t){if($(t.frag)&&!t.frag.bitrateTest){var r=t.frag,n=t.part?null:t,i=rn(r);this.fragments[i]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}}},{key:"onBufferAppended",value:function(e,t){var r=t.frag,n=t.part,i=t.timeRanges;if($(r)){var a=r.type;if(n){var s=this.activePartLists[a];s||(this.activePartLists[a]=s=[]),s.push(n)}this.timeRanges=i}}},{key:"onFragBuffered",value:function(e,t){this.detectPartialFragments(t)}},{key:"hasFragment",value:function(e){var t=rn(e);return!!this.fragments[t]}},{key:"hasFragments",value:function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var n=r.length;n--;){var i=t[r[n]];if((null==i?void 0:i.body.type)===e)return!0}return!1}},{key:"hasParts",value:function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}},{key:"getBackBufferEvictionEnd",value:function(e,t,r){for(var n=this.fragments,i=0,a=0,s=Object.keys(n),o=0;o<s.length;o++){var l=n[s[o]];if(l&&l.buffered&&l.body.type===t){var u=l.body;if(u.gap)return 0;var c=u.hasStats&&u.stats.loaded||u.byteLength||u.bitrate&&8*u.bitrate*u.duration;if(u.end<=e&&c&&(i+=c,a=Math.max(a,u.end),i>=r))return a}}return a>0?a:0}},{key:"removeFragmentsInRange",value:function(e,t,r,n,i){var a=this;n&&!this.hasGaps||Object.keys(this.fragments).forEach(function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||n&&!l.gap||l.start<t&&l.end>e&&(o.buffered||i)&&a.removeFragment(l)}})}},{key:"removeFragment",value:function(e){var t=rn(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var n=e.sn;this.activePartLists[e.type]=nn(r,function(e){return e.fragment.sn!==n})}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}},{key:"removeAllFragments",value:function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(function(e){return e.clearElementaryStreamInfo()})}}])}();function tn(e){var t,r,n,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(n=e.range.audiovideo)&&n.partial||null!=(i=e.range.subs)&&i.partial)}function rn(e){return"".concat(e.type,"_").concat(e.level,"_").concat(e.sn)}function nn(e,t){return e.filter(function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r})}var an=0,sn=1,on=function(){return h(function e(t,r,n){c(this,e),this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=n},[{key:"decrypt",value:function(e,t){switch(this.aesMode){case an:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case sn:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode ".concat(this.aesMode))}}}])}();var ln=function(){return h(function e(){c(this,e),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()},[{key:"uint8ArrayToUint32Array_",value:function(e){for(var t=new DataView(e),r=new Uint32Array(4),n=0;n<4;n++)r[n]=t.getUint32(4*n);return r}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],i=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],c=o[2],d=o[3],h=new Uint32Array(256),f=0,v=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var p=v^v<<1^v<<2^v<<3^v<<4;p=p>>>8^255&p^99,e[f]=p,t[p]=f;var y=h[f],m=h[y],E=h[m],k=257*h[p]^16843008*p;n[f]=k<<24|k>>>8,i[f]=k<<16|k>>>16,a[f]=k<<8|k>>>24,s[f]=k,k=16843009*E^65537*m^257*y^16843008*f,l[p]=k<<24|k>>>8,u[p]=k<<16|k>>>16,c[p]=k<<8|k>>>24,d[p]=k,f?(f=y^h[h[h[E^y]]],v^=h[h[v]]):f=v=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,n=0;n<t.length&&r;)r=t[n]===this.key[n],n++;if(!r){this.key=t;var i=this.keySize=t.length;if(4!==i&&6!==i&&8!==i)throw new Error("Invalid aes key size="+i);var a,s,o,l,u=this.ksRows=4*(i+6+1),c=this.keySchedule=new Uint32Array(u),d=this.invKeySchedule=new Uint32Array(u),h=this.sBox,f=this.rcon,v=this.invSubMix,g=v[0],p=v[1],y=v[2],m=v[3];for(a=0;a<u;a++)a<i?o=c[a]=t[a]:(l=o,a%i===0?(l=h[(l=l<<8|l>>>24)>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l],l^=f[a/i|0]<<24):i>6&&a%i===4&&(l=h[l>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l]),c[a]=o=(c[a-i]^l)>>>0);for(s=0;s<u;s++)a=u-s,l=3&s?c[a]:c[a-4],d[s]=s<4||a<=4?l:g[h[l>>>24]]^p[h[l>>>16&255]]^y[h[l>>>8&255]]^m[h[255&l]],d[s]=d[s]>>>0}}},{key:"networkToHostOrderSwap",value:function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}},{key:"decrypt",value:function(e,t,r){for(var n,i,a,s,o,l,u,c,d,h,f,v,g,p,y=this.keySize+6,m=this.invKeySchedule,E=this.invSBox,k=this.invSubMix,S=k[0],T=k[1],b=k[2],A=k[3],L=this.uint8ArrayToUint32Array_(r),R=L[0],I=L[1],w=L[2],_=L[3],P=new Int32Array(e),D=new Int32Array(P.length),C=this.networkToHostOrderSwap;t<P.length;){for(d=C(P[t]),h=C(P[t+1]),f=C(P[t+2]),v=C(P[t+3]),o=d^m[0],l=v^m[1],u=f^m[2],c=h^m[3],g=4,p=1;p<y;p++)n=S[o>>>24]^T[l>>16&255]^b[u>>8&255]^A[255&c]^m[g],i=S[l>>>24]^T[u>>16&255]^b[c>>8&255]^A[255&o]^m[g+1],a=S[u>>>24]^T[c>>16&255]^b[o>>8&255]^A[255&l]^m[g+2],s=S[c>>>24]^T[o>>16&255]^b[l>>8&255]^A[255&u]^m[g+3],o=n,l=i,u=a,c=s,g+=4;n=E[o>>>24]<<24^E[l>>16&255]<<16^E[u>>8&255]<<8^E[255&c]^m[g],i=E[l>>>24]<<24^E[u>>16&255]<<16^E[c>>8&255]<<8^E[255&o]^m[g+1],a=E[u>>>24]<<24^E[c>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^m[g+2],s=E[c>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&u]^m[g+3],D[t]=C(n^R),D[t+1]=C(s^I),D[t+2]=C(a^w),D[t+3]=C(i^_),R=d,I=h,w=f,_=v,t+=4}return D.buffer}}])}(),un=function(){return h(function e(t,r,n){c(this,e),this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=r,this.aesMode=n},[{key:"expandKey",value:function(){var e=function(e){switch(e){case an:return"AES-CBC";case sn:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode ".concat(e))}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}])}();var cn=function(){return h(function e(t,r){if(c(this,e),this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,!0!==r)try{var n=self.crypto;n&&(this.subtle=n.subtle||n.webkitSubtle)}catch(i){}this.useSoftware=!this.subtle},[{key:"destroy",value:function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}},{key:"isSync",value:function(){return this.useSoftware}},{key:"flush",value:function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var r=new Uint8Array(e);this.reset();var n,i,a,s=this.decryptRange;return s?0===s.start&&s.end>=r.length?r:r.slice(s.start,s.end):(i=(n=r).byteLength,(a=i&&new DataView(n.buffer).getUint8(i-1))?n.slice(0,i-a):n)}},{key:"reset",value:function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}},{key:"decrypt",value:function(e,t,r,n,i){var a=this;return this.decryptRange=i,this.useSoftware||i?new Promise(function(i,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);a.softwareDecrypt(o,t,r,n);var l=a.flush();l?i(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,n)}},{key:"softwareDecrypt",value:function(e,t,r,n){var i=this.currentIV,a=this.currentResult,s=this.remainderData;if(n!==an||16!==t.byteLength)return Le.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=At(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;i&&(r=i);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new ln),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null}},{key:"webCryptoDecrypt",value:function(e,t,r,n){var i=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,n));this.key=t,this.fastAesKey=new un(this.subtle,t,n)}return this.fastAesKey.expandKey().then(function(t){return i.subtle?(i.logOnce("WebCrypto AES decrypt"),new on(i.subtle,new Uint8Array(r),n).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(a){return Le.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(a.name,": ").concat(a.message)),i.onWebCryptoError(e,t,r,n)})}},{key:"onWebCryptoError",value:function(e,t,r,n){var i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,n);var a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}},{key:"getValidChunk",value:function(e){var t=e,r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}},{key:"logOnce",value:function(e){this.logEnabled&&(Le.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}])}(),dn=Math.pow(2,17),hn=function(){return h(function e(t){c(this,e),this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t},[{key:"destroy",value:function(){this.loader&&(this.loader.destroy(),this.loader=null)}},{key:"abort",value:function(){this.loader&&this.loader.abort()}},{key:"load",value:function(e,t,r,n){var i=this,a=e.url;if(!a)return Promise.reject(new pn({type:N.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(a?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,o=s.fLoader,l=s.loader;return new Promise(function(u,c){if(i.loader&&i.loader.destroy(),e.gap){if(e.tagList.some(function(e){return"GAP"===e[0]}))return void c(gn(e));e.gap=!1}var d=i.loader=o?new o(s):new l(s),h=fn(e,null,t);e.loader=d;var f=fe(s.fragLoadPolicy.default),v={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:dn};d.stats.retry=e.stats.retry,e.stats=d.stats;var g={onSuccess:function(t,r,n,a){i.resetLoader(e,d);var s=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),u({frag:e,part:null,payload:s,networkDetails:a})},onError:function(t,r,n,s){i.resetLoader(e,d),c(new pn({type:N.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:se({url:a,data:void 0},t),error:new Error("HTTP Error ".concat(t.code," ").concat(t.text)),networkDetails:n,stats:s}))},onAbort:function(t,r,n){i.resetLoader(e,d),c(new pn({type:N.NETWORK_ERROR,details:U.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:function(t,r,n){i.resetLoader(e,d),c(new pn({type:N.NETWORK_ERROR,details:U.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after ".concat(v.timeout,"ms")),networkDetails:n,stats:t}))}};if(r){var p=i.gateProgress(r,n);g.onProgress=function(t,r,n,i){return p({frag:e,part:null,payload:n,networkDetails:i})}}d.load(h,v,g)})}},{key:"gateProgress",value:function(e,t){var r=e;if(t){var n=[],i=!1;t.then(function(){i=!0,n.forEach(function(t){return e(t)}),n.length=0}).catch(function(){}),r=function(t){i?e(t):n.push(t)}}return r}},{key:"loadPart",value:function(e,t,r){var n=this;this.abort();var i=this.config,a=i.fLoader,s=i.loader;return new Promise(function(o,l){if(n.loader&&n.loader.destroy(),e.gap||t.gap)l(gn(e,t));else{var u=n.loader=a?new a(i):new s(i),c=fn(e,t);e.loader=u;var d=fe(i.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:dn};t.stats=u.stats,u.load(c,h,{onSuccess:function(i,a,s,l){n.resetLoader(e,u),n.updateStatsFromPart(e,t);var c={frag:e,part:t,payload:i.data,networkDetails:l};r(c),o(c)},onError:function(r,i,a,s){n.resetLoader(e,u),l(new pn({type:N.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:se({url:c.url,data:void 0},r),error:new Error("HTTP Error ".concat(r.code," ").concat(r.text)),networkDetails:a,stats:s}))},onAbort:function(r,i,a){e.stats.aborted=t.stats.aborted,n.resetLoader(e,u),l(new pn({type:N.NETWORK_ERROR,details:U.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,i,a){n.resetLoader(e,u),l(new pn({type:N.NETWORK_ERROR,details:U.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after ".concat(h.timeout,"ms")),networkDetails:a,stats:r}))}})}})}},{key:"updateStatsFromPart",value:function(e,t){var r=e.stats,n=t.stats,i=n.total;if(r.loaded+=n.loaded,i){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/i),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=n.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end}},{key:"resetLoader",value:function(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}])}();function fn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments.length>2?arguments[2]:void 0,n=t||e,i={type:q.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},a=vn(e,t,r);return a.resetIV&&(i.resetIV=!0),a.byteRange&&(i.rangeStart=a.byteRange.start,i.rangeEnd=a.byteRange.end),i}function vn(e){var t,r,n=arguments.length>2?arguments[2]:void 0,i={},a=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:null)||e,s=a.byteRangeStartOffset,o=a.byteRangeEndOffset;if(x(s)&&x(o))if("initSegment"!==e.sn&&!n||"AES-128"!==(r=null==(t=e.decryptdata)?void 0:t.method)&&"AES-256"!==r)i.byteRange={start:s,end:o};else{var l=16*Math.floor(s/16),u=16*Math.ceil(o/16);i.decryptRange={start:s-l,end:o-l},l>=16&&(i.resetIV=!0,l-=16),i.byteRange={start:l,end:u}}return i}function gn(e,t){var r=new Error("GAP ".concat(e.gap?"tag":"attribute"," found")),n={type:N.MEDIA_ERROR,details:U.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new pn(n)}var pn=function(e){function t(e){var r;return c(this,t),(r=u(this,t,[e.error.message])).data=void 0,r.data=e,r}return y(t,e),h(t)}(O(Error)),yn=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,[e,r]))._boundTick=void 0,n._tickTimer=null,n._tickInterval=null,n._tickCallCount=0,n._boundTick=n.tick.bind(n),n}return y(t,e),h(t,[{key:"destroy",value:function(){this.onHandlerDestroying(),this.onHandlerDestroyed()}},{key:"onHandlerDestroying",value:function(){this.clearNextTick(),this.clearInterval()}},{key:"onHandlerDestroyed",value:function(){}},{key:"hasInterval",value:function(){return!!this._tickInterval}},{key:"hasNextTick",value:function(){return!!this._tickTimer}},{key:"setInterval",value:function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}},{key:"clearInterval",value:function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}},{key:"clearNextTick",value:function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}},{key:"tick",value:function(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log("possible exception thrown in task-loop (".concat(this.constructor.name,".doTick)")),this._tickCallCount=0)}},{key:"tickImmediate",value:function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}},{key:"doTick",value:function(){}}])}(Ee),mn=h(function e(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,s=arguments.length>5&&void 0!==arguments[5]&&arguments[5],o=arguments.length>6?arguments[6]:void 0,l=arguments.length>7?arguments[7]:void 0,u=arguments.length>8?arguments[8]:void 0;c(this,e),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=r,this.id=n,this.size=i,this.part=a,this.partial=s,this.duration=o||0,this.decryptRange=u,this.iframe=l||!1});var En={length:0,start:function(){return 0},end:function(){return 0}},kn=function(){function e(){c(this,e)}return h(e,null,[{key:"isBuffered",value:function(t,r){if(t)for(var n=e.getBuffered(t),i=n.length;i--;)if(r>=n.start(i)&&r<=n.end(i))return!0;return!1}},{key:"bufferedRanges",value:function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]}},{key:"timeRangesToArray",value:function(e){for(var t=[],r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}},{key:"bufferInfo",value:function(t,r,n){if(t){var i=e.bufferedRanges(t);if(i.length)return e.bufferedInfo(i,r,n)}return{len:0,start:r,end:r,bufferedIndex:-1}}},{key:"bufferedInfo",value:function(e,t,r){t=Math.max(0,t),e.length>1&&e.sort(function(e,t){return e.start-t.start||t.end-e.end});var n=-1,i=[];if(r)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(n=a);var s=i.length;if(s){var o=i[s-1].end;e[a].start-o<r?e[a].end>o&&(i[s-1].end=e[a].end):i.push(e[a])}else i.push(e[a])}else i=e;for(var l,u=0,c=t,d=t,h=0;h<i.length;h++){var f=i[h].start,v=i[h].end;if(-1===n&&t>=f&&t<=v&&(n=h),t+r>=f&&t<v)c=f,u=(d=v)-t;else if(t+r<f){l=f;break}}return{len:u,start:c||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:n}}},{key:"getBuffered",value:function(e){try{return e.buffered||En}catch(t){return Le.log("failed to get media.buffered",t),En}}}])}(),Sn=/\{\$([a-zA-Z0-9-_]+)\}/g;function Tn(e){return Sn.lastIndex=0,Sn.test(e)}function bn(e,t){if(null!==e.variableList||e.hasVariableRefs){var r=e.variableList;return t.replace(Sn,function(t){var n=t.substring(2,t.length-1),i=null==r?void 0:r[n];return void 0===i?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(n,'"'))),t):i})}return t}function An(e,t,r){var n,i,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){n=t.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(n))throw new Error('"'.concat(n,'" does not match any query parameter in URI: "').concat(r,'"'));i=s.get(n)}catch(o){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(o.message)))}}else n=t.NAME,i=t.VALUE;n in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(n,'"'))):a[n]=i||""}function Ln(e,t,r){var n=t.IMPORT;if(r&&n in r){var i=e.variableList;i||(e.variableList=i={}),i[n]=r[n]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(n,'"')))}var Rn=/^(\d+)x(\d+)$/,In=/(.+?)=(".*?"|.*?)(?:,|$)/g,wn=function(){return h(function e(t,r){c(this,e),"string"==typeof t&&(t=e.parseAttrList(t,r)),ie(this,t)},[{key:"clientAttrs",get:function(){return Object.keys(this).filter(function(e){return"X-"===e.substring(0,2)})}},{key:"decimalInteger",value:function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"hexadecimalInteger",value:function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),n=0;n<t.length/2;n++)r[n]=parseInt(t.slice(2*n,2*n+2),16);return r}return null}},{key:"hexadecimalIntegerAsNumber",value:function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"optionalFloat",value:function(e,t){var r=this[e];return r?parseFloat(r):t}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"enumeratedStringList",value:function(e,t){var r=this[e];return(r?r.split(/[ ,]+/):[]).reduce(function(e,t){return e[t.toLowerCase()]=!0,e},t)}},{key:"bool",value:function(e){return"YES"===this[e]}},{key:"decimalResolution",value:function(e){var t=Rn.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e,t){var r,n={};for(In.lastIndex=0;null!==(r=In.exec(e));){var i=r[1].trim(),a=r[2],s=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,o=!1;if(s)a=a.slice(1,-1);else switch(i){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=bn(t,a);else if(!o&&!s)switch(i){case"CLOSED-CAPTIONS":if("NONE"===a)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Le.warn("".concat(e,": attribute ").concat(i," is missing quotes"))}n[i]=a}return n}}])}();function _n(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function Pn(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var Dn=function(){return h(function e(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(c(this,e),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==r?void 0:r.tagAnchor)||null,this.tagOrder=null!=(n=null==r?void 0:r.tagOrder)?n:i,r){var a=r.attr;for(var s in a)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]!==a[s]){Le.warn('DATERANGE tag attribute: "'.concat(s,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=s;break}t=ie(new wn({}),a,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){var o=(null==r?void 0:r.endDate)||new Date(t["END-DATE"]);x(o.getTime())&&(this._endDate=o)}},[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(Le.warn('Expected tagAnchor Fragment with PDT set for DateRange "'.concat(this.id,'": ').concat(e)),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(x(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&x(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},{key:"invalidReason",get:function(){return this.id?this._badValueForSameId?"Date range ".concat(this._badValueForSameId," mismatch"):x(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}])}(),Cn=function(){return h(function e(t){c(this,e),this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t},[{key:"reloaded",value:function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}},{key:"hasKey",value:function(e){return this.encryptedFragments.some(function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}},{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&x(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function On(e,t){return e.length===t.length&&!e.some(function(e,r){return e!==t[r]})}function xn(e,t){return!e&&!t||!(!e||!t)&&On(e,t)}function Mn(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Fn(e){switch(e){case"AES-128":case"AES-256":return an;case"AES-256-CTR":return sn;default:throw new Error("invalid full segment method ".concat(e))}}function Nn(e){return Uint8Array.from(unescape(encodeURIComponent(e)),function(e){return e.charCodeAt(0)})}function Un(e){var t=function(e,t,r){var n=e[t];e[t]=e[r],e[r]=n};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function Bn(e){var t,r,n=e.split(":"),i=null;if("data"===n[0]&&2===n.length){var a=n[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),i=Qe(l)):(t=Nn(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),i=r)}}return i}var Gn="undefined"!=typeof self?self:void 0,jn={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Kn="org.w3.clearkey",Hn="com.apple.streamingkeydelivery",Vn="com.microsoft.playready",qn="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Wn(e){switch(e){case Hn:return jn.FAIRPLAY;case Vn:return jn.PLAYREADY;case qn:return jn.WIDEVINE;case Kn:return jn.CLEARKEY}}var Yn="edef8ba979d64acea3c827dcd51d21ed";function zn(e){switch(e){case jn.FAIRPLAY:return Hn;case jn.PLAYREADY:return Vn;case jn.WIDEVINE:return qn;case jn.CLEARKEY:return Kn}}function Xn(e){var t=e.drmSystems,r=e.widevineLicenseUrl,n=t?[jn.FAIRPLAY,jn.WIDEVINE,jn.PLAYREADY,jn.CLEARKEY].filter(function(e){return!!t[e]}):[];return!n[jn.WIDEVINE]&&r&&n.push(jn.WIDEVINE),n}var Qn,$n=null!=Gn&&null!=(Qn=Gn.navigator)&&Qn.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Jn(e){var t=$e(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),r=t.substring(t.indexOf("<"),t.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){var i=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(i){var a=Qe(i).subarray(0,16);return Un(a),a}}return null}var Zn={},ei=function(){function e(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[1],a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,s=arguments.length>5?arguments[5]:void 0;c(this,e),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=t,this.uri=r,this.keyFormat=n,this.keyFormatVersions=i,this.iv=a,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!Mn(t),null!=s&&s.startsWith("0x")&&(this.keyId=new Uint8Array(Xe(s)))}return h(e,[{key:"matches",value:function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&On(e.keyFormatVersions,this.keyFormatVersions)&&xn(e.iv,this.iv)&&xn(e.keyId,this.keyId)}},{key:"isSupported",value:function(){if(this.method){if(Mn(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Hn:case qn:case Vn:case Kn:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{key:"getDecryptData",value:function(t,r){var n;if(!this.encrypted||!this.uri)return null;if(Mn(this.method)){var i=this.iv;return i||("number"!=typeof t&&(Le.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),i=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){var a=Zn[this.uri];if(a&&!On(this.keyId,a)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var s,o=Bn(this.uri);if(o)switch(this.keyFormat){case qn:if(this.pssh=o,!this.keyId){var l=Pt(o.buffer).filter(function(e){return e.systemId===Yn});if(l.length){var u,c=l[0];this.keyId=null!=(u=c.kids)&&u.length?c.kids[0]:null}}this.keyId||(this.keyId=ti(r));break;case Vn:var d=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=_t(d,0,o),this.keyId=Jn(o);break;default:var h=o.subarray(0,16);if(16!==h.length){var f=new Uint8Array(16);f.set(h,16-h.length),h=f}this.keyId=h}16!==(null==(n=this.keyId)?void 0:n.byteLength)&&(s=function(e){var t=null==e?void 0:e[qn];if(t)return t.keyId;return null}(r),s||(s=ti(r))||(s=Zn[this.uri]),s&&(this.keyId=s,e.setKeyIdForUri(this.uri,s)));return this}}],[{key:"clearKeyUriToKeyIdMap",value:function(){Zn={}}},{key:"setKeyIdForUri",value:function(e,t){Zn[e]=t}},{key:"addKeyIdForUri",value:function(e){var t=Object.keys(Zn).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),Zn[e]=r,r}}])}();function ti(e){var t=null==e?void 0:e[Vn];if(t){var r=Bn(t.uri);if(r)return Jn(r)}return null}var ri=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,ni=/#EXT-X-MEDIA:(.*)/g,ii=/^#EXT(?:INF|-X-TARGETDURATION):/m,ai=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),si=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),oi=function(){function e(){c(this,e)}return h(e,null,[{key:"findGroup",value:function(e,t){for(var r=0;r<e.length;r++){var n=e[r];if(n.id===t)return n}}},{key:"resolve",value:function(e,t){return H.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"isMediaPlaylist",value:function(e){return ii.test(e)}},{key:"parseMasterPlaylist",value:function(t,r){var n,i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Tn(t)},a=[];if(ri.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;for(;null!=(n=ri.exec(t));)if(n[1]){var s=li(new wn(n[1],i),n[2],r,i,a);s&&i.levels.push(s)}else if(n[3]){var o=n[3],l=n[4];switch(o){case"I-FRAME-STREAM-INF":var u=new wn(l,i),c=li(u,u.URI,r,i,a,!0);c&&i.iframeVariants.push(c);break;case"SESSION-DATA":var d=new wn(l,i),h=d["DATA-ID"];h&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[h]=d);break;case"SESSION-KEY":var f=di(l,r,i);f.encrypted&&f.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(f)):Le.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(l,'"'));break;case"DEFINE":An(i,new wn(l,i),r);break;case"CONTENT-STEERING":var v=new wn(l,i);i.contentSteering={uri:e.resolve(v["SERVER-URI"],r),pathwayId:v["PATHWAY-ID"]||"."};break;case"START":i.startTimeOffset=hi(l)}}var g=a.length>0&&a.length<i.levels.length;return i.levels=g?a:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}},{key:"parseMasterPlaylistMedia",value:function(t,r,n){var i,a={},s=n.levels,o={AUDIO:s.map(function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}}),SUBTITLES:s.map(function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}}),"CLOSED-CAPTIONS":[]},l=0;for(ni.lastIndex=0;null!==(i=ni.exec(t));){var u=new wn(i[1],n),c=u.TYPE;if(c){var d=o[c],h=a[c]||[];a[c]=h;var f=u.LANGUAGE,v=u["ASSOC-LANGUAGE"],g=u.CHANNELS,p=u.CHARACTERISTICS,y=u["INSTREAM-ID"],m={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||f||"",type:c,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:f,url:u.URI?e.resolve(u.URI,r):""};if(v&&(m.assocLang=v),g&&(m.channels=g),p&&(m.characteristics=p),y&&(m.instreamId=y),null!=d&&d.length){var E=e.findGroup(d,m.groupId)||d[0];vi(m,E,"audioCodec"),vi(m,E,"textCodec")}h.push(m)}}return a}},{key:"parseLevelPlaylist",value:function(e,t,r,n,i,a){var s,o,l,u,c,d={url:t},h=new Cn(t),f=h.fragments,v=[],g=null,p=0,y=0,m=0,E=0,k=0,S=null,T=new ee(n,d),b=-1,A=!1,L=null;if(ai.lastIndex=0,h.m3u8=e,h.hasVariableRefs=Tn(e),"#EXTM3U"!==(null==(s=ai.exec(e))?void 0:s[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(o=ai.exec(e));){A&&(A=!1,(T=new ee(n,d)).playlistOffset=m,T.setStart(m),T.sn=p,T.cc=E,k&&(T.bitrate=k),T.level=r,g&&(T.initSegment=g,g.rawProgramDateTime&&(T.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),L&&(T.setByteRange(L),L=null)));var R=o[1];if(R){T.duration=parseFloat(R);var I=(" "+o[2]).slice(1);T.title=I||null,T.tagList.push(I?["INF",R,I]:["INF",R])}else if(o[3]){if(x(T.duration)){var w;T.playlistOffset=m,T.setStart(m),u&&yi(T,u,h),T.sn=p,T.level=r,T.cc=E;var _=(" "+o[3]).slice(1);T.relurl=bn(h,_),gi(T,S,v),S=T,m+=T.duration,p++,y=0;var P=T.byteRange;if(2===P.length&&(T.bitrate=8*(P[1]-P[0])/T.duration|0),h.iframesOnly&&P[0]&&(null==(w=g)?void 0:w.cc)!==E){var D=new ee(n,d);D.relurl=T.relurl,D.setByteRange("".concat(Math.min(P[0],1316),"@0")),D.level=r,D.sn="initSegment",u&&(D.levelkeys=u,u.identity&&(D._decryptdata=u.identity.getDecryptData(0))),g=D,T.initSegment=g}f.push(T),A=!0}}else{if(!(o=o[0].match(si))){Le.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<o.length&&void 0===o[l];l++);var C=(" "+o[l]).slice(1),O=(" "+o[l+1]).slice(1),M=o[l+2]?(" "+o[l+2]).slice(1):null;switch(C){case"BYTERANGE":S?T.setByteRange(O,S):T.setByteRange(O);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=O,T.tagList.push(["PROGRAM-DATE-TIME",O]),-1===b&&(b=f.length);break;case"PLAYLIST-TYPE":h.type&&mi(h,C,o),h.type=O.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?mi(h,C,o):null!==S&&Ei(h,C,o),h.startSN=parseInt(O),p=h.startSN+h.skippedSegments;break;case"SKIP":h.skippedSegments&&mi(h,C,o);var F=new wn(O,h),N=F.decimalInteger("SKIPPED-SEGMENTS");if(x(N)){h.skippedSegments+=N;for(var U=N;U--;)f.push(null);p+=N}var B=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");B&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(B.split("\t")));break;case"TARGETDURATION":0!==h.targetduration&&mi(h,C,o),h.targetduration=Math.max(parseInt(O),1);break;case"VERSION":null!==h.version&&mi(h,C,o),h.version=parseInt(O);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":h.iframesOnly=!0;break;case"ENDLIST":h.live||mi(h,C,o),h.live=!1;break;case"#":(O||M)&&T.tagList.push(M?[O,M]:[O]);break;case"DISCONTINUITY":E++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([C]);break;case"BITRATE":T.tagList.push([C,O]),k=1e3*parseInt(O),x(k)?T.bitrate=k:k=0;break;case"DATERANGE":var G=new wn(O,h),j=new Dn(G,h.dateRanges[G.ID],h.dateRangeTagCount);h.dateRangeTagCount++,j.isValid||h.skippedSegments?h.dateRanges[j.id]=j:Le.log("Ignoring invalid DATERANGE tag: ".concat(j.invalidReason,": ").concat(O)),T.tagList.push(["EXT-X-DATERANGE",O]);break;case"DEFINE":var K=new wn(O,h);"IMPORT"in K?Ln(h,K,a):An(h,K,t);break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC&&mi(h,C,o),h.startCC=E=parseInt(O),f.forEach(function(e){return e&&(e.cc=E)});break;case"KEY":var H=di(O,t,h);if(H.isSupported()){if("NONE"===H.method){u=void 0;break}u||(u={});var V=u[H.keyFormat];null!=V&&V.matches(H)||(V&&(u=ie({},u)),u[H.keyFormat]=H)}else Le.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(O,'"'));break;case"START":h.startTimeOffset=hi(O);break;case"MAP":var q=new wn(O,h);if(T.duration){var W=new ee(n,d);pi(W,q,r,u),g=W,T.initSegment=g,g.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=g.rawProgramDateTime)}else{var Y=T.byteRangeEndOffset;if(Y){var z=T.byteRangeStartOffset;L="".concat(Y-z,"@").concat(z)}else L=null;pi(T,q,r,u),g=T,A=!0}g.cc=E;break;case"SERVER-CONTROL":c&&mi(h,C,o),c=new wn(O),h.canBlockReload=c.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=c.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&c.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=c.optionalFloat("PART-HOLD-BACK",0),h.holdBack=c.optionalFloat("HOLD-BACK",0);break;case"PART-INF":h.partTarget&&mi(h,C,o);var X=new wn(O);h.partTarget=X.decimalFloatingPoint("PART-TARGET");break;case"PART":var Q=h.partList;Q||(Q=h.partList=[]);var $=y>0?Q[Q.length-1]:void 0,J=y++,Z=new wn(O,h),re=new te(Z,T,d,J,$);Q.push(re),T.duration+=re.duration;break;case"PRELOAD-HINT":var ne=new wn(O,h);h.preloadHint=ne;break;case"RENDITION-REPORT":var ae=new wn(O,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(ae);break;default:Le.warn("line parsed but not handled: ".concat(o))}}}S&&!S.relurl?(f.pop(),m-=S.duration,h.partList&&(h.fragmentHint=S)):h.partList&&(gi(T,S,v),T.cc=E,h.fragmentHint=T,u&&yi(T,u,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));var se=f.length,oe=f[0],le=f[se-1];if((m+=h.skippedSegments*h.targetduration)>0&&se&&le){h.averagetargetduration=m/se;var ue=le.sn;h.endSN="initSegment"!==ue?ue:0,h.live||(le.endList=!0),b>0&&(!function(e,t,r){if(r||(r=e[t]),!r)return;for(var n=t;n--;){var i=e[n];if(!i)return;i.programDateTime=r.programDateTime-1e3*i.duration,r=i}}(f,b,b>se-1?T:null),oe&&v.unshift(oe))}return h.fragmentHint&&(m+=h.fragmentHint.duration),h.totalduration=m,v.length&&h.dateRangeTagCount&&oe&&ui(v,h),h.endCC=E,h}}])}();function li(e,t,r,n,i,a){var s;if(void 0===t)return null;var o=bn(n,t),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:oi.resolve(o,r)},u=e.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),fi(e.CODECS,l);var c=e["SUPPLEMENTAL-CODECS"];return c&&(l.supplemental={},fi(c,l.supplemental)),null!=(s=l.unknownCodecs)&&s.length||i.push(l),a&&(l.iframes=!0),l}function ui(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var n=t.fragments[t.fragments.length-1];e.push(n),r++}for(var i=e[r-1],a=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),o=s.length;o--;){var l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=i.ref;for(var c=r;c--;){var d;if((null==(d=e[c])?void 0:d.sn)<t.startSN)break;var h=ci(t,u,e,c,a);if(h){l.tagAnchor=h.ref;break}}}}function ci(e,t,r,n,i){var a=r[n];if(a){var s,o=a.programDateTime;if(t>=o||0===n)if(t<=o+1e3*(((null==(s=r[n+1])?void 0:s.start)||i)-a.start)){var l=a.sn-e.startSN,u=e.fragments;if(l>=0&&l<u.length){if(u.length>r.length)for(var c=r[n+1]||u[u.length-1],d=Math.min(c.sn-e.startSN,u.length-1);d>l;d--){var h=u[d].programDateTime;if(t>=h&&t<h+1e3*u[d].duration)return u[d]}return u[l]}}}return null}function di(e,t,r){var n,i,a=new wn(e,r),s=null!=(n=a.METHOD)?n:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,c=null!=(i=a.KEYFORMAT)?i:"identity";o&&a.IV&&!l&&Le.error("Invalid IV: ".concat(a.IV));var d=o?oi.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new ei(s,d,c,h,l,a.KEYID)}function hi(e){var t=new wn(e).decimalFloatingPoint("TIME-OFFSET");return x(t)?t:null}function fi(e,t){var r=(e||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text","image"].forEach(function(e){var n=r.filter(function(t){return jt(t,e)});n.length&&(t["".concat(e,"Codec")]=n.map(function(e){return e.split("/")[0]}).join(","),r=r.filter(function(e){return-1===n.indexOf(e)}))}),t.unknownCodecs=r}function vi(e,t,r){var n=t[r];n&&(e[r]=n)}function gi(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function pi(e,t,r,n){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",n&&(e.levelkeys=n),e.initSegment=null}function yi(e,t,r){e.levelkeys=t;var n=r.encryptedFragments;n.length&&n[n.length-1].levelkeys===t||!Object.keys(t).some(function(e){return t[e].isCommonEncryption})||n.push(e)}function mi(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must not appear more than once (").concat(r[0],")"))}function Ei(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must appear before the first Media Segment (").concat(r[0],")"))}function ki(e,t){var r=t.startPTS;if(x(r)){var n,i=0;t.sn>e.sn?(i=r-e.start,n=e):(i=e.start-r,n=t),n.duration!==i&&n.setDuration(i)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function Si(e,t,r,n,i,a,s,o){n-r<=0&&(o.warn("Fragment should have a positive duration",t),n=r+t.duration,a=i+t.duration);var l=r,u=n,c=t.startPTS,d=t.endPTS;if(x(c)){var h=Math.abs(c-r);e&&h>e.totalduration?o.warn("media timestamps and playlist times differ by ".concat(h,"s for level ").concat(t.level," ").concat(e.url)):x(t.deltaPTS)?t.deltaPTS=Math.max(h,t.deltaPTS):t.deltaPTS=h,l=Math.max(r,c),r=Math.min(r,c),i=void 0!==t.startDTS?Math.min(i,t.startDTS):i,u=Math.min(n,d),n=Math.max(n,d),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var f=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=l,t.startDTS=i,t.endPTS=n,t.minEndPTS=u,t.endDTS=a;var v,g=t.sn;if(!e||g<e.startSN||g>e.endSN)return 0;var p=g-e.startSN,y=e.fragments;for(y[p]=t,v=p;v>0;v--)ki(y[v],y[v-1]);for(v=p;v<y.length-1;v++)ki(y[v],y[v+1]);return e.fragmentHint&&ki(y[y.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,f}function Ti(e,t,r){if(e!==t){for(var n,i=null,a=e.fragments,s=a.length-1;s>=0;s--){var o=a[s].initSegment;if(o){i=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var n,i=t.skippedSegments,a=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=null!=(n=e.fragmentHint)&&n.duration?e.fragments.concat(e.fragmentHint):e.fragments,c=a;c<=s;c++){var d=u[o+c],h=l[c];if(i&&!h&&d&&(h=t.fragments[c]=d),d&&h){r(d,h,c,l);var f=d.relurl,v=h.relurl;if(f&&Pi(f,v))return void(t.playlistParsingError=bi("media sequence mismatch ".concat(h.sn,":"),e,t,d,h));if(d.cc!==h.cc)return void(t.playlistParsingError=bi("discontinuity sequence mismatch (".concat(d.cc,"!=").concat(h.cc,")"),e,t,d,h))}}}(e,t,function(e,r,a,s){if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){for(var o=e.cc-r.cc,l=a;l<s.length;l++)s[l].cc+=o;t.endCC=s[s.length-1].cc}x(e.startPTS)&&x(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(n=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,i=e.initSegment)});var l=t.fragments,u=t.fragmentHint?l.concat(t.fragmentHint):l;if(i&&u.forEach(function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(function(e){return!e}),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var c=t.skippedSegments;c--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){var n=t.dateRanges,i=t.recentlyRemovedDateranges,a=ie({},e);i&&i.forEach(function(e){delete a[e]});var s=Object.keys(a).length;if(!s)return n;return Object.keys(n).forEach(function(e){var t=a[e],i=new Dn(n[e].attr,t);i.isValid?(a[e]=i,t||(i.tagOrder+=s)):r.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(mr(n[e].attr),'"'))}),a}(e.dateRanges,t,r));var d=e.fragments.filter(function(e){return e.rawProgramDateTime});if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var h=1;h<u.length;h++)null===u[h].programDateTime&&gi(u[h],u[h-1],d);ui(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,v=Ri(e,t.startSN-1);t.startCC=null!=(f=null==v?void 0:v.cc)?f:l[0].cc}if(function(e,t,r){if(e&&t)for(var n=0,i=0,a=e.length;i<a;i++){var s=e[i],o=t[i+n];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?r(s,o):n--}}(e.partList,t.partList,function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap}),n){t.iframesOnly&&(n.type,W.MAIN);Si(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,0,r)}else Ai(e,t);l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var g=t.advancedDateTime;if(t.advanced&&g){var p=t.edge;t.driftStart||(t.driftStartTime=g,t.driftStart=p),t.driftEndTime=g,t.driftEnd=p}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function bi(e,t,r,n,i){return new Error("".concat(e," ").concat(i.url,"\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8,"\n\nPlaylist starting @").concat(r.startSN,"\n").concat(r.m3u8))}function Ai(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,i=t.startSN+t.skippedSegments-e.startSN,a=e.fragments,s=i>=0,o=0;if(s&&i<a.length)o=a[i].start,null==n||n.log("Aligning playlists based on SN ".concat(t.startSN," (diff: ").concat(o,")"));else if(s&&t.startSN===e.endSN+1)o=e.fragmentEnd,null==n||n.log("Aligning playlists based on first/last SN ".concat(t.startSN," (diff: ").concat(o,")"));else if(s&&r)o=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return o;o=e.fragmentStart,null==n||n.log("Aligning playlists based on first SN ".concat(t.startSN," (diff: ").concat(o,")"))}return function(e,t){if(t){for(var r=e.fragments,n=e.skippedSegments;n<r.length;n++)r[n].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,o),o}function Li(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=1e3*e.targetduration;if(e.updated){var n=e.fragments;if(n.length&&4*r>t){var i=1e3*n[n.length-1].duration;i>0&&i<r&&(r=i)}}else r/=2;return Math.round(r)}function Ri(e,t,r){var n;if(!e)return null;var i=e.fragments[t-e.startSN];return i||((null==(n=i=e.fragmentHint)?void 0:n.sn)===t?i:r&&t<e.startSN&&r.sn===t?r:null)}function Ii(e,t,r){return e?wi(e.partList,t,r):null}function wi(e,t,r){if(e)for(var n=e.length;n--;){var i=e[n];if(i.index===r&&i.fragment.sn===t)return i}return null}function _i(e){e.forEach(function(e,t){var r;null==(r=e.details)||r.fragments.forEach(function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function Pi(e,t){return!(e===t||!t)&&Di(e)!==Di(t)}function Di(e){return e.replace(/\?[^?]*$/,"")}function Ci(e,t){for(var r=0,n=e.length;r<n;r++){var i;if((null==(i=e[r])?void 0:i.cc)===t)return e[r]}return null}function Oi(e,t){var r=e.start+t;e.setStart(r)}function xi(e,t){for(var r=t.fragments,n=0,i=r.length;n<i;n++)Oi(r[n],e);t.fragmentHint&&Oi(t.fragmentHint,e),t.alignedSliding=!0}function Mi(e,t,r){e&&(!function(e,t,r){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;var n=Math.min(t.endCC,e.endCC),i=Ci(t.fragments,n),a=Ci(e.fragments,n);if(!i||!a)return;var s=i.start-a.start;r.log("Aligning playlists using dicontinuity sequence ".concat(n," (diff: ").concat(s,")")),xi(s,e)}(t,e,r),t.alignedSliding||function(e,t,r){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;var n,i,a=e.fragments,s=t.fragments;if(!a.length||!s.length)return;var o=Math.min(t.endCC,e.endCC);t.startCC<o&&e.startCC<o&&(n=Ci(s,o),i=Ci(a,o));n&&i||(i=Ci(a,(n=s[Math.floor(s.length/2)]||s.filter(function(e){return!!e})[0]).cc)||a[Math.floor(a.length/2)]);var l=n.programDateTime,u=i.programDateTime;if(!l||!u)return;var c=(u-l)/1e3;if(Math.abs(c)>Math.max(60,e.totalduration))return void r.log("Cannot align playlists using PDT without overlap (".concat(Math.abs(c)," > ").concat(e.totalduration,")"));var d=c-(i.start-n.start);r.log("Aligning playlists using PDT (diff: ".concat(d,")")),xi(d,e)}(t,e,r),t.alignedSliding||t.skippedSegments||Ai(e,t,!1,r))}function Fi(e,t,r){Ni(e,t,r),e.addEventListener(t,r)}function Ni(e,t,r){e.removeEventListener(t,r)}function Ui(e){for(var t="",r=e.length,n=0;n<r;n++)t+="[".concat(e.start(n).toFixed(3),"-").concat(e.end(n).toFixed(3),"]");return t}var Bi="STOPPED",Gi="IDLE",ji="KEY_LOADING",Ki="FRAG_LOADING",Hi="FRAG_LOADING_WAITING_RETRY",Vi="WAITING_TRACK",qi="PARSING",Wi="PARSED",Yi="ENDED",zi="ERROR",Xi="WAITING_INIT_PTS",Qi="WAITING_LEVEL",$i=function(e){function t(e,r,n,i,a){var s;return c(this,t),(s=u(this,t,[i,e.logger])).hls=void 0,s.fragPrevious=null,s.fragCurrent=null,s.fragPlaying=null,s.fragmentTracker=void 0,s.transmuxer=null,s._state=Bi,s.playlistType=void 0,s.media=null,s.mediaBuffer=null,s.config=void 0,s.bitrateTest=!1,s.lastCurrentTime=0,s.nextLoadPosition=0,s.startPosition=-1,s.startTimeOffset=null,s.retryDate=0,s.levels=null,s.fragmentLoader=void 0,s.initFragmentLoader=void 0,s.keyLoader=void 0,s.levelLastLoaded=null,s.startFragRequested=!1,s.decrypter=void 0,s.initPTS=[],s.buffering=!0,s.loadingParts=!1,s.loopSn=void 0,s.onMediaSeeking=function(){var e=s,t=e.config,r=e.fragCurrent,n=e.media,i=e.mediaBuffer,a=e.state,o=n?n.currentTime:0,l=kn.bufferInfo(i||n,o,t.maxBufferHole),u=l.len;if(s.log("Media seeking to ".concat(o,", state: ").concat(a,", ").concat(u?"in":"out of"," buffer")),s.state===Yi)s.resetLoadingState();else if(r){var c=t.maxFragLookUpTolerance,d=r.start-c,h=r.start+r.duration+c;if(!u||h<l.start||d>l.end){var f=o<d,v=o>h;(f||v)&&(!r.loader||!v&&s.isFragmentNearlyDownloaded(r)?s.fragPrevious=null:(s.log("Cancelling fragment load for seek (sn: ".concat(r.sn,") - ").concat(f?"backward":"forward"," seek")),r.abortRequests(),s.resetLoadingState()))}}if(n&&(s.fragmentTracker.removeFragmentsInRange(o,1/0,s.playlistType,!0),o>s.lastCurrentTime&&(s.lastCurrentTime=o),!s.loadingParts)){var g=Math.max(l.end,o),p=s.shouldLoadParts(s.getLevelDetails(),g);p&&(s.log("LL-Part loading ON after seeking to ".concat(o," with buffer @").concat(g)),s.loadingParts=p)}var y=!kn.isBuffered(n,o);s.hls.hasEnoughToStart&&!y||(s.log("Setting ".concat(y?"startPosition":"nextLoadPosition"," to ").concat(o," for seek without enough to start")),s.nextLoadPosition=o,y&&(s.startPosition=o)),u<1&&s.state===Gi&&s.tickImmediate()},s.onMediaEnded=function(){s.log("setting startPosition to 0 because media ended"),s.startPosition=s.lastCurrentTime=0},s.playlistType=a,s.hls=e,s.fragmentLoader=new hn(e.config),s.initFragmentLoader=new hn(e.config),s.keyLoader=n,s.fragmentTracker=r,s.config=e.config,s.decrypter=new cn(e.config),s}return y(t,e),h(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.ERROR,this.onError,this)}},{key:"doTick",value:function(){this.onTickEnd()}},{key:"onTickEnd",value:function(){}},{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){if(this.state!==Bi){this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Bi}}},{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;if(-1===t&&e){var r=this.getLevelDetails();return null!=r&&r.live?(this.hls.liveSyncPosition||r.fragmentStart)+this.timelineOffset:e}return t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"backtrackFragment",get:function(){},set:function(e){}},{key:"couldBacktrack",get:function(){return!1},set:function(e){}},{key:"pauseBuffering",value:function(){this.buffering=!1}},{key:"resumeBuffering",value:function(){this.buffering=!0}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"_streamEnded",value:function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,n=this.config.timelineOffset||0;if(r<=n)return!1;var i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=kn.bufferedInfo(i,e.start,0));var a=e.nextStart;if(a&&a>n&&a<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var s=t.partList;if(null!=s&&s.length){var o=s[s.length-1];return kn.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(l.type)}},{key:"getLevelDetails",value:function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"onMediaAttached",value:function(e,t){var r=this.media=this.mediaBuffer=t.media;Fi(r,"seeking",this.onMediaSeeking),Fi(r,"ended",this.onMediaEnded);var n=this.config;this.levels&&n.autoStartLoad&&this.state===Bi&&this.startLoad(n.startPosition)}},{key:"onMediaDetaching",value:function(e,t){this.fragPlaying=null;var r=!!t.transferMedia,n=this.media;if(null!==n){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ni(n,"seeking",this.onMediaSeeking),Ni(n,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}},{key:"onManifestLoading",value:function(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}},{key:"onError",value:function(e,t){}},{key:"onManifestLoaded",value:function(e,t){this.startTimeOffset=t.startTimeOffset}},{key:"onHandlerDestroying",value:function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),R(t,"onHandlerDestroying",this)([]),this.hls=this.onMediaSeeking=this.onMediaEnded=null}},{key:"onHandlerDestroyed",value:function(){this.state=Bi,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,R(t,"onHandlerDestroyed",this)([])}},{key:"loadFragment",value:function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}},{key:"_loadFragForPlayback",value:function(e,t,r){var n=this;this._doFragLoad(e,t,r,function(e){var t=e.frag;if(n.fragContextChanged(t))return n.warn("".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(n.fragInfo(t,!1,e.part)," was dropped during download.")),void n.fragmentTracker.removeFragment(t);var r=++t.stats.chunkCount;n.log("load progress ".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(n.fragInfo(t,!1,e.part)," chunk: ").concat(r)),n._handleFragmentLoadProgress(e)}).then(function(e){if(e){var t=n.state,r=e.frag;n.fragContextChanged(r)?(t===Ki||!n.fragCurrent&&t===qi)&&(n.fragmentTracker.removeFragment(r),n.state=Gi):("payload"in e&&(n.log("Loaded ".concat(r.type," sn: ").concat(r.sn," of ").concat(n.playlistLabel()," ").concat(r.level," (bytes ").concat(r.stats.loaded,")")),n.hls.trigger(B.FRAG_LOADED,e)),n._handleFragmentLoadComplete(e))}}).catch(function(t){n.state!==Bi&&n.state!==zi&&(n.log("Frag error ".concat(e.type," sn:").concat(e.sn," cc:").concat(e.cc,": ").concat((null==t?void 0:t.message)||t)),n.resetFragmentLoading(e))})}},{key:"clearTrackerIfNeeded",value:function(e){var t,r=this.fragmentTracker;if(r.getState(e)===$r){var n=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,n),a=Math.max(e.duration,i?i.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?e.sn-s.sn:0)||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===Jr&&r.removeFragment(e))}},{key:"checkLiveUpdate",value:function(e){if(e.updated&&!e.live){var t=this.fragmentTracker,r=e.fragments[e.fragments.length-1];if(r.endList&&!t.isEndListAppended(this.playlistType)){var n=t.getPartialFragment(r.end);n&&(t.removeFragment(n),t.fragBuffered(r,!0))}t.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}},{key:"waitForLive",value:function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}},{key:"flushMainBuffer",value:function(e,t){if(e-t){var r={startOffset:e,endOffset:t,type:arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(B.BUFFER_FLUSHING,r)}}},{key:"_loadInitSegment",value:function(e){var t=this,r=this.hls;return this.initFragmentLoader.abort(),r.trigger(B.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(function(e){var r,n=e.frag;if(!t.levels||!Z(n,null==(r=t.fragCurrent)?void 0:r.initSegment))throw new pn({type:N.NETWORK_ERROR,details:U.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:n,networkDetails:null});return e}).then(function(e){var n=e.frag,i=e.payload,a=n.decryptdata;if(i&&i.byteLength>0&&null!=a&&a.key&&a.iv&&Mn(a.method)){var s=self.performance.now(),o=vn(n,null,t.iframesOnly).decryptRange;return t.decrypter.decrypt(new Uint8Array(i),a.key.buffer,a.iv.buffer,Fn(a.method),o).catch(function(e){throw r.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:n}),t.fragmentLoader.abort(),e}).then(function(i){var a=self.performance.now();return r.trigger(B.FRAG_DECRYPTED,{frag:n,part:null,payload:i,stats:{tstart:s,tdecrypt:a}}),e.payload=i,t.completeInitSegmentLoad(e)})}return t.completeInitSegmentLoad(e)})}},{key:"completeInitSegmentLoad",value:function(e){var t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}},{key:"loadInitSegmentIfNeeded",value:function(e){var t,r=this,n=e.initSegment;if(!this.bitrateTest&&$(e)&&n&&!n.data)return(!n.encrypted||null!=(t=n.decryptdata)&&t.key?this._loadInitSegment(n):this.keyLoader.load(n).then(function(){return r._loadInitSegment(n)})).catch(function(t){if(r.state===Bi||r.state===zi)throw t;throw"data"in t&&(t.data.frag=e,r.fragmentLoader.abort(),r.handleFragLoadError(t)),r.resetFragmentLoading(e),t})}},{key:"unhandledEncryptionError",value:function(e,t){var r,n,i=e.tracks;if(i&&!t.encrypted&&(null!=(r=i.audio)&&r.encrypted||null!=(n=i.video)&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var a=this.media,s=new Error("Encrypted track with no key in ".concat(this.fragInfo(t)," (media ").concat(a?"attached mediaKeys: "+a.mediaKeys:"detached",")"));return this.warn(s.message),!a||a.mediaKeys?!1:(this.hls.trigger(B.ERROR,{type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}},{key:"fragContextChanged",value:function(e){var t=this.fragCurrent;return!e||!Z(e,t)}},{key:"fragBufferedComplete",value:function(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)," > buffer:").concat(r?Ui(kn.getBuffered(r)):"(detached)",")")),$(e)){var n;if(e.type!==W.SUBTITLE){var i=e.elementaryStreams;if(!Object.keys(i).some(function(e){return!!i[e]}))return void(this.state=Gi)}var a=null==(n=this.levels)?void 0:n[e.level];null!=a&&a.fragmentError&&(t||this.fragmentTracker.getState(e)!==Jr)&&(this.log("Resetting level fragment error count of ".concat(a.fragmentError," on frag buffered")),a.fragmentError=0,e.stats.retry=0)}this.state=Gi}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this.transmuxer;if(t){var r=e.frag,n=e.part,i=e.partsLoaded,a=!i||0===i.length||i.some(function(e){return!e}),s=vn(r,n).decryptRange,o=new mn(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!a,r.duration,this.iframesOnly,s);this.log("load complete ".concat(r.type," sn: ").concat(r.sn).concat(n?" part: "+n.index:""," of ").concat(this.fragInfo(r,!1,n))),t.flush(o)}}},{key:"_handleFragmentLoadProgress",value:function(e){}},{key:"loadKeyFor",value:function(e,t,r){var n,i=this,a=null;return!e.encrypted||null!=(n=e.decryptdata)&&n.key?e.encrypted||(a=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag sn: ".concat(e.sn," load until media-keys acquired")):(this.log("Loading key for ".concat(e.sn," of [").concat(t.startSN,"-").concat(t.endSN,"], ").concat(this.playlistLabel()," ").concat(e.level)),this.state=ji,a=this.keyLoader.load(e,r).then(function(e){if(!i.fragContextChanged(e.frag))return i.hls.trigger(B.KEY_LOADED,e),i.state===ji&&(i.state=Gi),e}),this.hls.trigger(B.KEY_LOADING,{frag:e})),a}},{key:"_doFragLoad",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3?arguments[3]:void 0;this.fragCurrent=e;var a=t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level".concat(a?"":" detail","s"));var s,o=this.fragPrevious;if(!J(e,o)){var l=this.shouldLoadParts(t.details,e.end);l!==this.loadingParts&&(this.log("LL-Part loading ".concat(l?"ON":"OFF"," loading sn ").concat(null==o?void 0:o.sn,"->").concat(e.sn)),this.loadingParts=l)}if(n=Math.max(e.start,n||0),this.loadingParts){var u=a.partList;if(u&&i){n>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);var c=this.getNextPart(u,e,n);if(c>-1){var d=u[c];if(!J(e=this.fragCurrent=d.fragment,o)&&!this.shouldLoadParts(t.details,e.end))return this.log("LL-Part loading OFF @".concat(this.playhead," next part: ").concat(this.fragInfo(e,!1,d))),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(d,t.details))return Promise.resolve(null);var h,f=this.loadKeyFor(e,a);if(this.fragContextChanged(e))return Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," part: ").concat(d.index," (").concat(c,"/").concat(u.length-1,") of ").concat(this.fragInfo(e,!1,d)," cc: ").concat(e.cc," [").concat(a.startSN,"-").concat(a.endSN,"], target: ").concat(n).concat(d.byteRange.length?" range:".concat(d.byteRange.join("-")):"")),this.nextLoadPosition=d.start+d.duration,this.state=Ki;var v=this.loadInitSegmentIfNeeded(e);if(f||v){var g=!!f;h=Promise.all([f,v]).then(function(n){var a=L(n,1)[0];return!g||a&&!r.fragContextChanged(a.frag)?r.doFragPartsLoad(e,d,t,i):null}).catch(function(e){return r.handleFragLoadError(e)})}else h=this.doFragPartsLoad(e,d,t,i).catch(function(e){return r.handleFragLoadError(e)});return this.hls.trigger(B.FRAG_LOADING,{frag:e,part:d,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(u,n))return Promise.resolve(null)}}if(this.loadingParts)this.log("LL-Part loading OFF after next part miss @".concat(n," Check buffer at sn: ").concat(e.sn," loaded parts: ").concat(null==(s=a.partList)?void 0:s.filter(function(e){return e.loaded}).map(function(e){return"[".concat(e.start,"-").concat(e.end,"]")}))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);var p,y=this.loadInitSegmentIfNeeded(e),m=this.loadKeyFor(e,a,y);if(this.fragContextChanged(e))return this.log("Context changed in KEY_LOADING sn: ".concat(e.sn," ").concat(e.relurl," > ").concat(null==(p=this.fragCurrent)?void 0:p.relurl)),null==y||y.catch(function(){return null}),null==m||m.catch(function(){return null}),Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," of ").concat(this.fragInfo(e,!1)," cc: ").concat(e.cc," ").concat("["+a.startSN+"-"+a.endSN+"]",", target: ").concat(n).concat(e.byteRange.length?" range:".concat(e.byteRange.join("-")):"")),x(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Ki;var E,k=this.config.progressive&&e.type!==W.SUBTITLE;return E=k&&m?m.then(function(t){return!t||r.fragContextChanged(t.frag)?null:r.fragmentLoader.load(e,r.iframesOnly,i,y)}).catch(function(e){return r.handleFragLoadError(e)}):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,k?i:void 0,k?y:void 0),m,y]).then(function(e){var t=L(e,1)[0];return!k&&i&&i(t),t}).catch(function(e){return r.handleFragLoadError(e)}),this.hls.trigger(B.FRAG_LOADING,{frag:e,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([E,y]).then(function(e){return L(e,1)[0]})}},{key:"doFragPartsLoad",value:function(e,t,r,n){var i=this;return new Promise(function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,c=function(t){i.fragmentLoader.loadPart(e,t,n).then(function(n){l[t.index]=n;var s=n.part;i.hls.trigger(B.FRAG_LOADED,n);var o=Ii(r.details,e.sn,t.index+1)||wi(u,e.sn,t.index+1);if(!o)return a({frag:e,part:s,partsLoaded:l});c(o)}).catch(s)};c(t)})}},{key:"handleFragLoadError",value:function(e){if("data"in e){var t=e.data;t.frag&&t.details===U.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===N.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(B.ERROR,t)}else this.hls.trigger(B.ERROR,{type:N.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}},{key:"_handleTransmuxerFlush",value:function(e){var t=this.getCurrentContext(e);if(t&&this.state===qi){var r=t.frag,n=t.part,i=t.level,a=self.performance.now();r.stats.parsing.end=a,n&&(n.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading ".concat(o?"ON":"OFF"," after parsing segment ending @").concat(r.end)),this.loadingParts=o),this.updateLevelTiming(r,n,i,e)}else this.fragCurrent||this.state===Bi||this.state===zi||(this.state=Gi)}},{key:"shouldLoadParts",value:function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var r,n=e.partList[0];if(t>=n.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0))if(this.playhead>n.start-n.fragment.duration)return!0}}return!1}},{key:"getCurrentContext",value:function(e){var t=this.levels,r=this.fragCurrent,n=e.level,i=e.sn,a=e.part;if(null==t||!t[n])return this.warn("Levels object was unset while buffering fragment ".concat(i," of ").concat(this.playlistLabel()," ").concat(n,". The current chunk will not be buffered.")),null;var s=t[n],o=s.details,l=a>-1?Ii(o,i,a):null,u=l?l.fragment:Ri(o,i,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null}},{key:"bufferFragmentData",value:function(e,t,r,n,i){if(this.state===qi){$(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);var a=e.data1,s=e.data2,o=a;if(s&&(o=At(a,s)),o.length){var l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:r,chunkMeta:n,offset:u,parent:t.type,data:o};if(this.hls.trigger(B.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(i)return;this.flushBufferGap(t)}}}}},{key:"flushBufferGap",value:function(e){var t=this.media;if(t)if(kn.isBuffered(t,t.currentTime)){var r=t.currentTime,n=kn.bufferInfo(t,r,0),i=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),s=Math.max(Math.min(e.start-a,n.end-a),r+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)}},{key:"getFwdBufferInfo",value:function(e,t){var r,n=this.playhead,i=this.lastCurrentTime>n||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,i)}},{key:"getFwdBufferInfoAtPos",value:function(e,t,r,n){var i=kn.bufferInfo(e,t,n);if(0===i.len&&void 0!==i.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(i.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(i.nextStart,a.end)-t,n);return kn.bufferInfo(e,t,s)}}return i}},{key:"getMaxBufferLength",value:function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)}},{key:"exceedsMaxBuffer",value:function(e,t,r){var n=e.nextStart;if(n&&r.start>n){var i=e.buffered;if(i){for(var a=e.len,s=e.bufferedIndex,o=i.length-1;o>s;o--)i[o].start<r.start&&(a+=i[o].end-i[o].start);return a>=t}}return!1}},{key:"reduceMaxBufferLength",value:function(e,t){var r=this.config,n=Math.max(Math.min(e-t,r.maxBufferLength),t/2),i=Math.max(e-3*t,r.maxMaxBufferLength/2,n);return i>=n&&(r.maxMaxBufferLength=i,this.warn("Reduce max buffer length to ".concat(i,"s")),!0)}},{key:"getAppendedFrag",value:function(e){var t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}},{key:"getNextFragment",value:function(e,t){var r=t.fragments,n=r.length;if(!n)return null;var i=this.config,a=t.fragmentStart,s=i.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=i.initialLiveManifestSize;if(n<l)return this.warn("Not enough fragments to start playback (have: ".concat(n,", need: ").concat(l,")")),null;if(this.startFragRequested||!s||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var u;o=this.getInitialLiveFragment(t);var c,d,h=this.config.startPosition,f=this.hls.startPosition,v=this.hls.liveSyncPosition,g=(null==(u=o)?void 0:u.start)||0;if(-1!==f&&f>=a?(c=f,d=f===h?"config":"next load start"):v?(c=v,d="live edge"):(c=e,d="buffer pos"),c<g&&(c=g,d="live frag start"),c<a&&(c=a,d="playlist start"),this.startPosition!=c||this.nextLoadPosition!=c){var p=t.live&&!this.filterReplacedPrimary(o,t)?-1:c;this.log("Setting startPosition to ".concat(p," next load ").concat(c," ").concat(-1===f?"":"(from ".concat(h,") "),"based on ").concat(d,". live edge: ").concat(v," live frag start: ").concat(g," playlist start: ").concat(a," buffer pos: ").concat(e)),this.startPosition=p,this.nextLoadPosition=c}}}else e<=a&&(o=r[0]);if(!o){var y=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,y,t)}var m=this.filterReplacedPrimary(o,t);return!m&&o&&(m=Mr(t,o.sn))&&(this.nextLoadPosition=m.start),m}},{key:"isLoopLoading",value:function(e,t){if(this.nextLoadPosition<=t)return!1;var r=this.fragmentTracker.getState(e);if(r===Zr)return!0;if(r===Jr){if(e.gap)return!0;if(e.stats.retry>1)return!0}return!1}},{key:"getNextFragmentLoopLoading",value:function(e,t,r,n,i){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&r.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n,0);if(null!==s&&r.len+s.len>=i){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'.concat(n,'" playlist starting at sn: ').concat(o)),this.loopSn=o),null}}return this.loopSn=void 0,a}},{key:"primaryPrefetch",get:function(){var e;if(Zi(this.config)&&(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))return!0;return!1}},{key:"filterReplacedPrimary",value:function(e,t){if(!e)return e;if(Zi(this.config)&&("type"in e?e:e.fragment).type!==W.SUBTITLE){var r=this.hls.interstitialsManager,n=null==r?void 0:r.bufferingItem;if(n){var i=n.event;if(i){if(!i.appendInPlace&&(Math.abs(e.start-n.start)>1||0===n.start))return null}else{if(e.end<=n.start&&!1===(null==t?void 0:t.live))return null;if(e.start>=n.end&&n.nextEvent&&(n.nextEvent.appendInPlace&&!n.nextEvent.hasPlayed||e.start-n.end>1))return null}}if(Ji(e,null==r?void 0:r.playerQueue,this.playhead))return null}return e}},{key:"getNextPart",value:function(e,t,r){for(var n=-1,i=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,n>-1&&r<l.start)break;var u=l.loaded||l.gap;u?n=-1:(i||(l.independent||a)&&l.fragment===t)&&(n=s),i=u&&!l.gap}var c=e[n];return c&&c.fragment!==t&&this.log("Need buffer at ".concat(r," but next unloaded part starts at ").concat(c.start," (sn: ").concat(t.sn," -> ").concat(c.fragment.sn,")")),n}},{key:"loadedEndOfParts",value:function(e,t){for(var r,n=e.length;n--;){if(!(r=e[n]).loaded)return!1;if(t>r.start)return!0}return!1}},{key:"getInitialLiveFragment",value:function(e){var t=e.fragments,r=this.fragPrevious,n=null;if(r){if(e.hasProgramDateTime&&(n=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!x(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var n=0;n<e.length;++n){var i=e[n];if(Or(t,r,i))return i}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance),n&&this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(r.programDateTime))),!n){var i=r.sn+1;if(i>=e.startSN&&i<=e.endSN){var a=t[i-e.startSN];r.cc===a.cc&&(n=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(n.sn)))}n||(n=xr(e,r.cc,r.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(n.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(n=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}},{key:"getFragmentAtPosition",value:function(e,t,r){var n,i,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,c=a.maxFragLookUpTolerance,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&u);(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),s&&this.fragmentTracker.getState(s)===Qr&&(s=null),e<t)?n=Dr(s,o,e,e<this.lastCurrentTime||e>t-c||null!=(i=this.media)&&i.paused||!this.startFragRequested?0:c):n=o[o.length-1];if(n){var f=n.sn-r.startSN,v=this.fragmentTracker.getState(n);if((v===Zr||v===Jr&&n.gap)&&(s=n),J(n,s)&&(!h||d[0].fragment.sn>n.sn||!r.live)){var g=o[f+1];n=n.sn<l&&this.fragmentTracker.getState(g)!==Zr?g:null}}return n}},{key:"alignPlaylists",value:function(e,t,r){var n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;var i=e.fragmentStart,a=!t,s=e.alignedSliding&&x(i);if(a||!s&&!i){Mi(r,e,this);var o=e.fragmentStart;return this.log("Live playlist sliding: ".concat(o," start-sn: ").concat(t?t.startSN:"na","->").concat(e.startSN," fragments: ").concat(n)),o}return i}},{key:"waitForCdnTuneIn",value:function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}},{key:"setStartPosition",value:function(e,t){var r=this.startPosition;r<t&&(r=-1);var n=this.timelineOffset;if(-1===r){var i=null!==this.startTimeOffset,a=i?this.startTimeOffset:e.startTimeOffset;if(null!==a&&x(a))r=t+a,a<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Setting startPosition to ".concat(r," for start time offset ").concat(a," found in ").concat(i?"multivariant":"media"," playlist")),this.startPosition=r;else if(e.live){var s=this.hls.liveSyncPosition;r=s||t,this.log("Setting startPosition to -1 to start at ".concat(s?"live edge":"playlist start"," ").concat(r)),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=r=0;this.lastCurrentTime=r+n}this.nextLoadPosition=r+n}},{key:"getLoadPosition",value:function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t&&!this.iframesOnly?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}},{key:"playhead",get:function(){var e;if(null!=(e=this.hls)&&e.hasEnoughToStart){var t,r=null==(t=this.media)?void 0:t.currentTime;return x(r)?r:this.lastCurrentTime}return this.getLoadPosition()}},{key:"iframesOnly",get:function(){var e;if(this.playlistType!==W.MAIN)return!1;var t=this.getLevelDetails();return t?t.iframesOnly:null==(e=this.levelLastLoaded)?void 0:e.iframes}},{key:"handleFragLoadAborted",value:function(e,t){this.transmuxer&&e.type===this.playlistType&&$(e)&&e.stats.aborted&&(this.log("Fragment ".concat(e.sn).concat(t?" part "+t.index:""," of ").concat(this.playlistLabel()," ").concat(e.level," was aborted")),this.resetFragmentLoading(e))}},{key:"resetFragmentLoading",value:function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Hi)||(this.state=Gi)}},{key:"onFragmentOrKeyLoadError",value:function(e,t){if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var n=t.frag,i=t.part;if(n&&this.levels&&n.type===e)if(this.fragContextChanged(n)){var a;this.warn("Frag load error must match current frag to retry ".concat(n.relurl," > ").concat(null==(a=this.fragCurrent)?void 0:a.relurl))}else{var s=t.details===U.FRAG_GAP;s&&this.fragmentTracker.addAsGap(n);var o=t.errorAction;if(o){var l=o.action,u=o.flags,c=o.retryCount,d=void 0===c?0:c,h=o.retryConfig,f=!!h,v=f&&l===Br,g=f&&!o.resolved&&u&jr,p=this.hls.latestLevelDetails,y=null==p?void 0:p.live;if(!v&&g&&$(n)&&y&&n.sn<p.endSN&&!ce(t))this.resetFragmentErrors(e),i?i.gap=!0:this.treatAsGap(n),o.resolved=!0;else if((v||g)&&d<h.maxNumRetry){var m,E=ge(null==(m=t.response)?void 0:m.code),k=he(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+k,this.state=Hi,o.resolved=!0,E)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn("Fragment ".concat(n.sn," of ").concat(e," ").concat(n.level," errored with ").concat(t.details,", retrying loading ").concat(d+1,"/").concat(h.maxNumRetry," in ").concat(k,"ms"))}else if(h){if(this.resetFragmentErrors(e),!(d<h.maxNumRetry))return void this.warn("".concat(t.details," reached or exceeded max retry (").concat(d,")"));s||l===Ur||(o.resolved=!0)}else this.state=l===Nr?Qi:zi;this.tickImmediate()}else this.state=zi}}},{key:"checkRetryDate",value:function(){var e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!ge(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Gi)}},{key:"reduceLengthAndFlushBuffer",value:function(e){if(this.state===qi||this.state===Wi){var t=e.frag,r=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,r),i=n&&n.len>.5;i&&this.reduceMaxBufferLength(n.len,(null==t?void 0:t.duration)||10);var a=!i;return a?this.warn("Buffer full error while media.currentTime (".concat(this.playhead,") is not buffered, flush ").concat(r," buffer")):n.nextStart&&t&&n.nextStart>t.start&&this.flushMainBuffer(n.nextStart,Number.POSITIVE_INFINITY,r===W.AUDIO?r:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}},{key:"resetFragmentErrors",value:function(e){e===W.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Bi&&(this.state=Gi)}},{key:"afterBufferFlushed",value:function(e,t){if(e){var r=kn.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,this.playlistType),this.state===Yi&&this.resetLoadingState()}}},{key:"resetLoadingState",value:function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Bi&&(this.state=Gi)}},{key:"resetStartWhenNotLoaded",value:function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.getLevelDetails();null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}},{key:"resetWhenMissingContext",value:function(e){this.log("Loading context changed while buffering sn ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(-1===e.level?"<removed>":e.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}},{key:"removeUnbufferedFrags",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}},{key:"updateLevelTiming",value:function(e,t,r,n){var i=this,a=r.details;if(a){this.log("update level timing ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)));var s=Object.keys(e.elementaryStreams).reduce(function(t,s){var o=e.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return i.warn("Could not parse fragment ".concat(e.sn," ").concat(s," duration reliably (").concat(l,")")),t||!1;var u=n.partial?0:Si(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,i.iframesOnly,i);return i.hls.trigger(B.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1);if(!s){var o,l,u,c,d=null===(null==(o=this.transmuxer)?void 0:o.error),h=null!=(null==(l=this.transmuxer)?void 0:l.error),f=(null!=(u=null==(c=this.levels)?void 0:c.length)?u:0)>1;if((0===r.fragmentError||d&&(r.fragmentError<2||e.endList)||h&&f)&&this.treatAsGap(e,r),d){var v=new Error("Found no media in ".concat(this.playlistLabel()," ").concat(e.level," ").concat(t?"part: ".concat(t.index," of "):"","sn: ").concat(e.sn," at playlist time: ").concat(e.start,". Resetting transmuxer to fallback to playlist timing"));if(this.warn(v.message),this.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,error:v,frag:e,reason:"Found no media in msn ".concat(e.sn," of ").concat(this.playlistLabel(),' "').concat(r.url,'"')}),!this.hls)return;this.resetTransmuxer()}}this.state=Wi,this.log("Parsed ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t))),this.hls.trigger(B.FRAG_PARSED,{frag:e,part:t,chunkMeta:n})}else this.warn("level.details undefined")}},{key:"playlistLabel",value:function(){return"".concat(this.playlistType," playlist")}},{key:"fragInfo",value:function(e){var t,r,n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2?arguments[2]:void 0;return"".concat(this.playlistLabel()," ").concat(e.level," (").concat(i?"part":"frag",":[").concat(null!=(t=n&&!i?e.startPTS:(i||e).start)?t:NaN,"-").concat(null!=(r=n&&!i?e.endPTS:(i||e).end)?r:NaN,"]").concat(i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):"",")")}},{key:"treatAsGap",value:function(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}},{key:"resetTransmuxer",value:function(){var e;null==(e=this.transmuxer)||e.reset()}},{key:"isFragmentNearlyDownloaded",value:function(e){var t,r=null==(t=e.loader)?void 0:t.stats;if(!r)return!1;var n=r.loading.first>0,i=(r.total-r.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return n&&i<=.15}},{key:"recoverWorkerError",value:function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log("".concat(t,"->").concat(e)))}},{key:"calculateOptimalSwitchPoint",value:function(e,t){var r=0,n=this.hls,i=this.media,a=this.config,s=this.levels,o=this.playlistType,l=this.getLevelDetails();if(i&&!i.paused&&s){var u,c=o===W.AUDIO?ar(e.audioCodec,128e3):e.maxBitrate,d=1+n.ttfbEstimate/1e3,h=n.bandwidthEstimate*a.abrBandWidthUpFactor;r=d+c*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(u=this.fragCurrent)?void 0:u.duration)||6)/h,e.details||(r+=d)}var f=this.playhead;return{fetchdelay:r,okToFlushForwardBuffer:!(null!=l&&l.live)||t.end-f>1.5*r}}},{key:"scheduleTrackSwitch",value:function(e,t,r){var n=this.media,i=this.playlistType;if(n&&e){var a=r?this.getBufferedFrag(this.playhead+t):null;if(a){var s=this.followingBufferedFrag(a);if(s){var o;this.abortCurrentFrag();var l=s.maxStartPTS?s.maxStartPTS:s.start,u=s.duration,c=Math.max(a.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if(((null==(o=this.getLevelDetails())?void 0:o.fragmentStart)||0)>c)return;var d=i===W.MAIN?null:"audio";this.flushMainBuffer(c,Number.POSITIVE_INFINITY,d),this.cleanupBackBuffer()}}}}},{key:"cleanupBackBuffer",value:function(){var e=this.media,t=this.playlistType;if(e){var r=this.getAppendedFrag(this.playhead);if(r&&r.start>1){var n=t===W.AUDIO;this.flushMainBuffer(0,r.start-(n?0:1),n?"audio":null)}}}},{key:"getBufferedFrag",value:function(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.end+.5):null}},{key:"abortCurrentFrag",value:function(){var e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case ji:case Ki:case Hi:case qi:case Wi:this.state=Gi}this.nextLoadPosition=this.playhead}},{key:"checkFragPlaying",value:function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(kn.isBuffered(e,r)?t=this.getAppendedFrag(r):kn.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t&&(this.backtrackFragment=void 0,!J(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}},{key:"getBufferOutput",value:function(){return null}},{key:"nextLevelSwitch",value:function(){var e=this.levels,t=this.media,r=this.hls,n=this.config,i=this.playlistType;if(null!=t&&t.readyState&&e&&r&&n){var a=this.getBufferOutput(),s=this.getFwdBufferInfo(a,i);if(!s)return;var o=e[i===W.AUDIO?r.nextAudioTrack:r.nextLoadLevel],l=this.calculateOptimalSwitchPoint(o,s),u=l.fetchdelay,c=l.okToFlushForwardBuffer;this.scheduleTrackSwitch(s,u,c)}this.tickImmediate()}}])}(yn);function Ji(e,t,r){if(t)for(var n=t.length;n--;){var i=t[n].interstitial,a=i.startTime,s=Math.min(a+i.duration,i.resumeTime);if(i.appendInPlace){if(e.start>=a&&e.end<=s)return!0;if(r>e.start&&e.end>a&&e.start<s)return!0}}return!1}function Zi(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var ea=function(){return h(function e(){c(this,e),this.chunks=[],this.dataLength=0},[{key:"push",value:function(e){this.chunks.push(e),this.dataLength+=e.length}},{key:"flush",value:function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),n=0,i=0;i<e.length;i++){var a=e[i];r.set(a,n),n+=a.length}return r}(t,r),this.reset(),e):new Uint8Array(0)}},{key:"reset",value:function(){this.chunks.length=0,this.dataLength=0}}])}();var ta,ra={exports:{}};var na=(ta||(ta=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,n,a,s){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new i(n,a||e,s),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,s=new Array(a);i<a;i++)s[i]=n[i].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},o.prototype.emit=function(e,t,n,i,a,s){var o=r?r+e:e;if(!this._events[o])return!1;var l,u,c=this._events[o],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,s),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,f=c.length;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},o.prototype.on=function(e,t,r){return a(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return a(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn!==t||i&&!o.once||n&&o.context!==n||s(this,a);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||i&&!o[l].once||n&&o[l].context!==n)&&u.push(o[l]);u.length?this._events[a]=1===u.length?u[0]:u:s(this,a)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(ra)),ra.exports),ia=G(na),aa="1.7.3",sa={};function oa(e,t){return 255===e[t]&&240==(246&e[t+1])}function la(e,t){return 1&e[t+1]?7:9}function ua(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function ca(e,t){return t+1<e.length&&oa(e,t)}function da(e,t){if(ca(e,t)){var r=la(e,t);if(t+r>=e.length)return!1;var n=ua(e,t);if(n<=r)return!1;var i=t+n;return i===e.length||ca(e,i)}return!1}function ha(e,t,r,n,i){if(!e.samplerate){var a=function(e,t,r,n){var i=t[r+2],a=i>>2&15;if(!(a>12)){var s,o=1+(i>>6&3),l=t[r+3]>>6&3|(1&i)<<2,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],c=a;5!==o&&29!==o||(c-=3);var d=(14&c)>>1,h=(1&c)<<7|l<<3,f=0;if(1===o&&a>=6){var v=a-3;s=[(f=5)<<3|d,h|(14&v)>>1,(1&v)<<7|8,0]}else s=[o<<3|d,h];var g="mp4a.40."+(f||o);return Le.log("manifest codec:".concat(n,", parsed codec:").concat(g,", channels:").concat(l,", rate:").concat(u," (ADTS object type:").concat(o," sampling index:").concat(a," esds config:[").concat(s.join(","),"])")),{config:s,samplerate:u,channelCount:l,codec:g,parsedCodec:g,manifestCodec:n}}var p=new Error("invalid ADTS sampling index:".concat(a));e.emit(B.ERROR,B.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message})}(t,r,n,i);if(!a)return;ie(e,a)}}function fa(e){return 9216e4/e}function va(e,t,r,n,i){var a,s=n+i*fa(e.samplerate),o=function(e,t){var r=la(e,t);if(t+r<=e.length){var n=ua(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,c=u+l,d=Math.max(0,r+c-t.length);d?(a=new Uint8Array(c-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+c);var h={unit:a,pts:s};return d||e.samples.push(h),{sample:h,length:c,missing:d}}var f=t.length-r;return(a=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}var ga=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function pa(){return{type:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",id:-1,pid:-1,inputTimeScale:arguments.length>1&&void 0!==arguments[1]?arguments[1]:9e4,sequenceNumber:-1,samples:[],dropped:0}}var ya=function(){return h(function e(){c(this,e),this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null},[{key:"resetInitSegment",value:function(e,t,r,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}},{key:"resetTimeStamp",value:function(e){this.initPTS=e,this.resetContiguity()}},{key:"resetContiguity",value:function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}},{key:"canParse",value:function(e,t){return!1}},{key:"appendFrame",value:function(e,t,r){}},{key:"demux",value:function(e,t){this.cachedData&&(e=At(this.cachedData,e),this.cachedData=null);var r,n=Ue(e,0),i=n?n.length:0,a=this._audioTrack,s=this._id3Track,o=n?Ye(n):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&x(o))&&(this.basePTS=ma(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:ga.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){var u=this.appendFrame(a,e,i);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r=i+=u.length):i=l}else Fe(e,i)?(n=Ue(e,i),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:ga.audioId3,duration:Number.POSITIVE_INFINITY}),r=i+=n.length):i++;if(i===l&&r!==l){var c=e.slice(r);this.cachedData?this.cachedData=At(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:pa(),id3Track:s,textTrack:pa()}}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("[".concat(this,"] This demuxer does not support Sample-AES decryption")))}},{key:"flush",value:function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:pa(),id3Track:this._id3Track,textTrack:pa()}}},{key:"destroy",value:function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}])}(),ma=function(e,t,r){return x(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},Ea=[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],ka=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Sa=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ta=[0,1,1,4];function ba(e,t,r,n,i){if(!(r+24>t.length)){var a=Aa(t,r);if(a&&r+a.frameLength<=t.length){var s=n+i*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function Aa(e,t){var r=e[t+1]>>3&3,n=e[t+1]>>1&3,i=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==i&&15!==i&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Ea[14*(3===r?3-n:3===n?3:4)+i-1],u=ka[3*(3===r?0:2===r?1:2)+a],c=3===o?1:2,d=Sa[r][n],h=Ta[n],f=8*d*h,v=Math.floor(d*l/u+s)*h,g=Ut();return!!g&&g<=87&&2===n&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:c,frameLength:v,samplesPerFrame:f}}}function La(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Ra(e,t){return t+1<e.length&&La(e,t)}function Ia(e,t){if(t+1<e.length&&La(e,t)){var r=Aa(e,t),n=4;null!=r&&r.frameLength&&(n=r.frameLength);var i=t+n;return i===e.length||Ra(e,i)}return!1}var wa=function(){return h(function e(t,r,n){c(this,e),this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new cn(r,!0)},[{key:"decryptBuffer",value:function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,an,{start:0,end:e.byteLength})}},{key:"decryptAacSample",value:function(e,t,r){var n=this,i=e[t].unit;if(!(i.length<=16)){var a=i.subarray(16,i.length-i.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then(function(a){var s=new Uint8Array(a);i.set(s,16),n.decrypter.isSync()||n.decryptAacSamples(e,t+1,r)}).catch(r)}}},{key:"decryptAacSamples",value:function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),n=0,i=32;i<e.length-16;i+=160,n+=16)r.set(e.subarray(i,i+16),n);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){for(var r=new Uint8Array(t),n=0,i=32;i<e.length-16;i+=160,n+=16)e.set(r.subarray(n,n+16),i);return e}},{key:"decryptAvcSample",value:function(e,t,r,n,i){var a=this,s=wt(i.data),o=this.getAvcEncryptedData(s);this.decryptBuffer(o.buffer).then(function(o){i.data=a.getAvcDecryptedUnit(s,o),a.decrypter.isSync()||a.decryptAvcSamples(e,t,r+1,n)}).catch(n)}},{key:"decryptAvcSamples",value:function(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void n();for(var i=e[t].units;!(r>=i.length);r++){var a=i[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,n,a),this.decrypter.isSync())))return}}}}])}(),_a=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t)).observer=void 0,n.config=void 0,n.sampleAes=null,n.observer=e,n.config=r,n}return y(t,e),h(t,[{key:"resetInitSegment",value:function(e,r,n,i){R(t,"resetInitSegment",this)([e,r,n,i]),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&oa(e,t)&&ua(e,t)<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){ha(e,this.observer,t,r,e.manifestCodec);var n=va(e,t,r,this.basePTS,this.frameIndex);if(0===(null==n?void 0:n.missing))return n}},{key:"demuxSampleAes",value:function(e,t,r){var n=this.demux(e,r),i=this.sampleAes=new wa(this.observer,this.config,t);return new Promise(function(e){i.decryptAacSamples(n.audioTrack.samples,0,function(){e(n)})})}}],[{key:"probe",value:function(e,t){if(!e)return!1;var r=Ue(e,0),n=(null==r?void 0:r.length)||0;if(Ia(e,n))return!1;for(var i=e.length;n<i;n++)if(da(e,n))return t.log("ADTS sync word found !"),!0;return!1}}])}(ya),Pa=function(e,t){var r=0,n=5;t+=n;for(var i=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);n>0;){s[0]=e[t];var o=Math.min(n,8),l=8-o;a[0]=4278190080>>>24+l<<l,i[0]=(s[0]&a[0])>>l,r=r?r<<o|i[0]:i[0],t+=1,n-=o}return r},Da=function(e){function t(e){var r;return c(this,t),(r=u(this,t)).observer=void 0,r.observer=e,r}return y(t,e),h(t,[{key:"resetInitSegment",value:function(e,r,n,i){R(t,"resetInitSegment",this)([e,r,n,i]),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return t+64<e.length}},{key:"appendFrame",value:function(e,t,r){var n=Ca(e,t,r,this.basePTS,this.frameIndex);if(-1!==n)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}}],[{key:"probe",value:function(e){if(!e)return!1;var t=Ue(e,0);if(!t)return!1;var r=t.length;if(11===e[r]&&119===e[r+1]&&void 0!==Ye(t)){if(Pa(e,r)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}])}(ya);function Ca(e,t,r,n,i){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var a=t[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[r+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+a];if(r+l>t.length)return-1;var u=t[r+6]>>5,c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));var d=(t[r+6]<<8|t[r+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[r+5]>>3,v=7&t[r+5],g=new Uint8Array([a<<6|f<<1|v>>2,(3&v)<<6|u<<3|d<<2|o>>4,o<<4&224]),p=n+i*(1536/s*9e4),y=t.subarray(r,r+l);return e.config=g,e.channelCount=h,e.samplerate=s,e.samples.push({unit:y,pts:p}),l}var Oa=function(e){function t(){return c(this,t),u(this,t,arguments)}return y(t,e),h(t,[{key:"resetInitSegment",value:function(e,r,n,i){R(t,"resetInitSegment",this)([e,r,n,i]),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return La(e,t)&&4<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){if(null!==this.basePTS)return ba(e,t,r,this.basePTS,this.frameIndex)}}],[{key:"probe",value:function(e){if(!e)return!1;var t=Ue(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==Ye(t)&&Pa(e,r)<=16)return!1;for(var n=e.length;r<n;r++)if(Ia(e,r))return Le.log("MPEG Audio sync word found !"),!0;return!1}}])}(ya),xa=/\/emsg[-/]ID3/i,Ma=function(){return h(function e(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Le;c(this,e),this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=r,this.logger=i},[{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(e,t,r,n){var i=this.videoTrack=pa("video",1),a=this.audioTrack=pa("audio",1),s=this.txtTrack=pa("text",1);if(this.id3Track=pa("id3",1),this.initData=void 0,this.timeOffset=0,null!=e&&e.byteLength){var o=this.initData=vt(e);if(o.video){var l=o.video,u=l.id,c=l.timescale,d=l.codec,h=l.supplemental;i.id=u,i.timescale=s.timescale=c,i.codec=d,i.supplemental=h}if(o.audio){var f=o.audio,v=f.id,g=f.timescale,p=f.codec;a.id=v,a.timescale=g,a.codec=p}s.id=tt.text,i.sampleDuration=0,i.duration=a.duration=n}}},{key:"resetContiguity",value:function(){this.remainderData=null}},{key:"demux",value:function(e,t,r){this.timeOffset=t;var n=e,i=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=At(this.remainderData,e));var s=function(e){var t={valid:null,remainder:null},r=dt(e,["moof"]);if(r.length<2)return t.remainder=e,t;var n=r[r.length-1];return t.valid=e.slice(0,n.byteOffset-8),t.remainder=e.slice(n.byteOffset-8),t}(n);this.remainderData=s.remainder,i.samples=s.valid||new Uint8Array}else i.samples=n;var o=this.extractID3Track(i,t),l=this.parseFragment(i,a,t,r);return{videoTrack:i,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}},{key:"flush",value:function(e,t){var r=this.timeOffset,n=this.videoTrack,i=this.txtTrack;n.samples=this.remainderData||new Uint8Array,this.remainderData=null;var a=this.extractID3Track(n,this.timeOffset),s=this.parseFragment(n,i,r,t);return{videoTrack:n,audioTrack:pa(),id3Track:a,textTrack:pa(),initData:this.initData,sampleData:s}}},{key:"parseFragment",value:function(e,t,r,n){var i=this.initData;if(i&&n){var a=function(e,t,r,n){var i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=[];return{samples:a,sampleData:{includeSampleDetails:i,tracks:bt(t.samples,r,n,i,{isHEVCFlavor:Lt(t.codec),samples:a,timeOffset:e,timescale:t.timescale,trackId:t.id})}}}(r,e,i,this.logger,n.iframe),s=a.samples,o=a.sampleData;return t.samples=s,o}t.samples=function(e,t){var r=[],n=t.samples,i=t.timescale,a=t.id,s=!1;return dt(n,["moof"]).map(function(o){var l=o.byteOffset-8;dt(o,["traf"]).map(function(o){var u=dt(o,["tfdt"]).map(function(e){var t=e[0],r=nt(e,4);return 1===t&&(r*=Math.pow(2,32),r+=nt(e,8)),r/i})[0];return void 0!==u&&(e=u),dt(o,["tfhd"]).map(function(u){var c=nt(u,4),d=16777215&nt(u,0),h=!!(1&d),f=0,v=!!(2&d),g=!!(8&d),p=0,y=!!(16&d),m=0,E=!!(32&d),k=!h&&!!(131072&d),S=8;c===a&&(h?(f=nt(u,S),S+=4,f*=Math.pow(2,32),f+=nt(u,S),S+=4):k&&(f=l),v&&(S+=4),g&&(p=nt(u,S),S+=4),y&&(m=nt(u,S),S+=4),E&&(S+=4),"video"===t.type&&(s=Lt(t.codec)),dt(o,["trun"]).map(function(a){var o=a[0],l=16777215&nt(a,0),u=!!(1&l),c=0,d=!!(4&l),h=!!(256&l),v=0,g=!!(512&l),y=0,E=!!(1024&l),k=!!(2048&l),S=0,T=nt(a,4),b=8;u&&(c=nt(a,b),b+=4),d&&(b+=4);for(var A=f+c,L=0;L<T;L++){if(h?(v=nt(a,b),b+=4):v=p,g?(y=nt(a,b),b+=4):y=m,E&&(b+=4),k&&(S=0===o?nt(a,b):st(a,b),b+=4),t.type===z)for(var R=0;R<y;){var I=nt(n,A);Rt(s,n[A+=4])&&It(n.subarray(A,A+I),s?2:1,e+S/i,r),A+=I,R+=I+4}e+=v/i}}))})})}),r}(r,e)}},{key:"extractID3Track",value:function(e,t){var r=this,n=this.id3Track;if(e.samples.length){var i=dt(e.samples,["emsg"]);i&&i.forEach(function(e){var i=function(e){var t,r=e[0],n="",i="",a=0,s=0,o=0,l=0,u=4;if(0===r){var c=at(e,u),d=null!==c?at(e,u+c.length):null;null!==c&&null!==d?(n=c,i=d,a=nt(e,u+=c.length+d.length),s=nt(e,u+=4),o=nt(e,u+=4),l=nt(e,u+=4),u+=4):(Le.warn("Unterminated ".concat(null===c?"scheme_id_uri":"value"," in parsing emsg box: version 0 box ends inside a string, dropping all of its fields")),u=e.length)}else if(1===r){a=nt(e,u);var h=nt(e,u+=4),f=nt(e,u+=4);u+=4,t=Math.pow(2,32)*h+f,M(t)||(t=Number.MAX_SAFE_INTEGER,Le.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=nt(e,u),l=nt(e,u+=4);var v=at(e,u+=4),g=null!==v?at(e,u+v.length):null;null!==v&&(n=v,u+=v.length),null!==g?(i=g,u+=g.length):(Le.warn("Unterminated ".concat(null===v?"scheme_id_uri":"value"," in parsing emsg box: version 1 box ends inside a string, dropping its ").concat(null===v?"strings and payload":"value and payload")),u=e.length)}return{schemeIdUri:n,value:i,timeScale:a,presentationTime:t,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(xa.test(i.schemeIdUri)){var a=Fa(i,t),s=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=i.payload;n.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:ga.emsg,duration:s})}else if(r.config.enableEmsgKLVMetadata){var l=r.config.emsgKLVSchemaUri||ga.misbklv;if(i.schemeIdUri.startsWith(l)){var u=Fa(i,t);n.samples.push({data:i.payload,len:i.payload.byteLength,dts:u,pts:u,type:ga.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return n}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}},{key:"destroy",value:function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}],[{key:"probe",value:function(e){return function(e,t){for(var r=e.byteLength,n=0;n<r;){var i=nt(e,n);if(i>8&&nt(e,n+4)===et[t])return!0;n=i>1?n+i:r}return!1}(e,"moof")}}])}();function Fa(e,t){return x(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var Na=function(){return h(function e(){c(this,e),this.VideoSample=null},[{key:"createVideoSample",value:function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}},{key:"getLastNalUnit",value:function(e){var t,r,n=this.VideoSample;if(n&&0!==n.units.length||(n=e[e.length-1]),null!=(t=n)&&t.units){var i=n.units;r=i[i.length-1]}return r}},{key:"pushAccessUnit",value:function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,n=r.length;if(!n)return void t.dropped++;var i=r[n-1];e.pts=i.pts,e.dts=i.dts}t.samples.push(e)}}},{key:"parseNALu",value:function(e,t,r){var n=t.byteLength;if(0===n)return[];var i=e.naluState||0,a=-1===i?0:i,s=[],o=0,l=0,u=-1,c=0;for(-1===i&&(u=0,c=this.getNALuType(t,0),l=1);l<n;){var d=t.indexOf(1,l);if(-1===d)break;l=d+1;for(var h=d;h>0&&0===t[h-1];)h--;if(!(d-h+(0===h?a:0)<2)){if(u>=0)s.push({data:t.subarray(u,h),type:c});else{var f=this.getLastNalUnit(e.samples);f&&(h>0?f.data=At(f.data,t.subarray(0,h)):a>0&&(f.data=f.data.subarray(0,f.data.byteLength-a)),f.state=0)}if(!(l<n)){o=-1,u=-1;break}u=l,c=this.getNALuType(t,l)}}if(-1!==o){for(var v=n;v>0&&0===t[v-1];)v--;o=n-v+(0===v?a:0)}if(u>=0)s.push({data:t.subarray(u),type:c,state:o});else if(0===s.length&&-1!==o){var g=this.getLastNalUnit(e.samples);g&&(g.data=At(g.data,t),g.state=o)}return e.naluState=o,s}}])}(),Ua=function(){return h(function e(t){c(this,e),this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0},[{key:"loadWord",value:function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,n=new Uint8Array(4),i=Math.min(4,t);if(0===i)throw new Error("no bytes available");n.set(e.subarray(r,r+i)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=8*i,this.bytesAvailable-=i}},{key:"skipBits",value:function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&Le.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?r<<t|this.readBits(t):r}},{key:"skipLZ",value:function(){var e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}}])}(),Ba=function(e){function t(){return c(this,t),u(this,t,arguments)}return y(t,e),h(t,[{key:"parsePES",value:function(e,t,r,n,i){var a,s=this,o=i.iframe,l=this.parseNALu(e,r.data,n),u=this.VideoSample,c=!1;r.data=null,u&&l.length&&!e.audFound&&(this.pushAccessUnit(u,e),u=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),l.forEach(function(n){var i,l;switch(n.type){case 1:if(o)break;var d=!1;a=!0;var h,f=n.data;if(c&&f.length>4){var v=s.readSliceType(f);2!==v&&4!==v&&7!==v&&9!==v||(d=!0)}if(d)null!=(h=u)&&h.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null);u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.frame=!0,u.key=d;break;case 5:a=!0,null!=(i=u)&&i.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null),u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.key=!0,u.frame=!0;break;case 6:if(o)break;a=!0,It(n.data,1,r.pts,t.samples);break;case 7:var g,p;a=!0,c=!0;var y=n.data,m=s.readSPS(y);if(!e.sps||e.width!==m.width||e.height!==m.height||(null==(g=e.pixelRatio)?void 0:g[0])!==m.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[y];for(var E=y.subarray(1,4),k="avc1.",S=0;S<3;S++){var T=E[S].toString(16);T.length<2&&(T="0"+T),k+=T}e.codec=k}break;case 8:a=!0,e.pps=[n.data];break;case 9:a=!0,e.audFound=!0,null!=(l=u)&&l.frame&&(s.pushAccessUnit(u,e),u=null),u||(u=s.VideoSample=s.createVideoSample(!1,r.pts,r.dts));break;case 12:a=!0;break;default:a=!1}u&&a&&u.units.push(n)}),n&&u&&(this.pushAccessUnit(u,e),this.VideoSample=null)}},{key:"getNALuType",value:function(e,t){return 31&e[t]}},{key:"readSliceType",value:function(e){var t=new Ua(e);return t.readUByte(),t.readUEG(),t.readUEG()}},{key:"skipScalingList",value:function(e,t){for(var r=8,n=8,i=0;i<e;i++)0!==n&&(n=(r+t.readEG()+256)%256),r=0===n?r:n}},{key:"readSPS",value:function(e){var t,r,n,i=new Ua(e),a=0,s=0,o=0,l=0,u=i.readUByte.bind(i),c=i.readBits.bind(i),d=i.readUEG.bind(i),h=i.readBoolean.bind(i),f=i.skipBits.bind(i),v=i.skipEG.bind(i),g=i.skipUEG.bind(i),p=this.skipScalingList.bind(this);u();var y=u();if(c(5),f(3),u(),g(),100===y||110===y||122===y||244===y||44===y||83===y||86===y||118===y||128===y){var m=d();if(3===m&&f(1),g(),g(),f(1),h())for(r=3!==m?8:12,n=0;n<r;n++)h()&&p(n<6?16:64,i)}g();var E=d();if(0===E)d();else if(1===E)for(f(1),v(),v(),t=d(),n=0;n<t;n++)v();g(),f(1);var k=d(),S=d(),T=c(1);0===T&&f(1),f(1),h()&&(a=d(),s=d(),o=d(),l=d());var b=[1,1];if(h()&&h())switch(u()){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=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(k+1)-2*a-2*s),height:(2-T)*(S+1)*16-(T?2:4)*(o+l),pixelRatio:b}}}])}(Na),Ga=function(e){function t(){var e;c(this,t);for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return(e=u(this,t,[].concat(n))).initVPS=null,e}return y(t,e),h(t,[{key:"parsePES",value:function(e,t,r,n){var i,a=this,s=this.parseNALu(e,r.data,n),o=this.VideoSample,l=!1;r.data=null;var u=function(e){return o=a.VideoSample=a.createVideoSample(e,r.pts,r.dts)};s.forEach(function(n,s){var c,d;if(a.startsNewAccessUnit(o,e,n,s)){a.pushAccessUnit(o,e);var h=n.type>=16&&n.type<=23;o=u(h),l=!1}switch(n.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=u(!1)),o.frame=!0,i=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var f;if(i=!0,l)null!=(f=o)&&f.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=u(!0)),o.key=!0,o.frame=!0;break;case 19:case 20:i=!0,null!=(c=o)&&c.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=u(!0)),o.key=!0,o.frame=!0;break;case 39:i=!0,It(n.data,2,r.pts,t.samples);break;case 32:i=!0,e.vps||("object"!==_(e.params)&&(e.params={}),e.params=ie(e.params,a.readVPS(n.data)),a.initVPS=n.data),e.vps=[n.data];break;case 33:if(i=!0,l=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],n.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var v=a.readSPS(n.data);for(var g in e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],"object"!==_(e.params)&&(e.params={}),v.params)e.params[g]=v.params[g]}a.pushParameterSet(e.sps,n.data,e.vps),o||(o=u(!1));break;case 34:if(i=!0,"object"===_(e.params)){if(!e.pps){e.pps=[];var p=a.readPPS(n.data);for(var y in p)e.params[y]=p[y]}a.pushParameterSet(e.pps,n.data,e.vps)}break;case 35:i=!0,e.audFound=!0,null!=(d=o)&&d.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=u(!1));break;default:i=!1}o&&i&&o.units.push(n)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"pushParameterSet",value:function(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}},{key:"startsNewAccessUnit",value:function(e,t,r,n){if(!e)return!1;if(!t.audFound&&0===n)return!0;if(!e.frame)return!1;var i=r.type,a=r.data;return!!(i>=32&&i<=35||39===i||i>=41&&i<=44||i>=48&&i<=55)||i<=31&&a.length>2&&!!(128&a[2])}},{key:"getNALuType",value:function(e,t){return(126&e[t])>>>1}},{key:"ebsp2rbsp",value:function(e){for(var t=new Uint8Array(e.byteLength),r=0,n=0;n<e.byteLength;n++)n>=2&&3===e[n]&&0===e[n-1]&&0===e[n-2]||(t[r]=e[n],r++);return new Uint8Array(t.buffer,0,r)}},{key:"pushAccessUnit",value:function(e,r){R(t,"pushAccessUnit",this)([e,r]),this.initVPS&&(this.initVPS=null)}},{key:"readVPS",value:function(e){var t=new Ua(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}},{key:"readSPS",value:function(e){var t=new Ua(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var n=t.readBits(2),i=t.readBoolean(),a=t.readBits(5),s=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),v=t.readUByte(),g=t.readUByte(),p=t.readUByte(),y=[],m=[],E=0;E<r;E++)y.push(t.readBoolean()),m.push(t.readBoolean());if(r>0)for(var k=r;k<8;k++)t.readBits(2);for(var S=0;S<r;S++)y[S]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),m[S]&&t.readUByte();t.readUEG();var T=t.readUEG();3==T&&t.skipBits(1);var b=t.readUEG(),A=t.readUEG(),L=t.readBoolean(),R=0,I=0,w=0,_=0;L&&(R+=t.readUEG(),I+=t.readUEG(),w+=t.readUEG(),_+=t.readUEG());for(var P=t.readUEG(),D=t.readUEG(),C=t.readUEG(),O=t.readBoolean()?0:r;O<=r;O++)t.skipUEG(),t.skipUEG(),t.skipUEG();if((t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean())&&t.readBoolean())for(var x=0;x<4;x++)for(var M=0;M<(3===x?2:6);M++){if(t.readBoolean()){var F=Math.min(64,1<<4+(x<<1));x>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var U=t.readUEG(),B=0,G=0;G<U;G++){var j=!1;if(0!==G&&(j=t.readBoolean()),j){G===U&&t.readUEG(),t.readBoolean(),t.readUEG();for(var K=0,H=0;H<=B;H++){var V=t.readBoolean(),q=!1;V||(q=t.readBoolean()),(V||q)&&K++}B=K}else{var W=t.readUEG(),Y=t.readUEG();B=W+Y;for(var z=0;z<W;z++)t.readUEG(),t.readBoolean();for(var X=0;X<Y;X++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var Q=t.readUEG(),$=0;$<Q;$++){for(var J=0;J<C+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,re=!0,ne=1,ie=0;t.readBoolean(),t.readBoolean();if(t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean())t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte());if(t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean())if(ne=t.readBits(32),ie=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean()){var se=t.readBoolean(),oe=t.readBoolean(),le=!1;(se||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=r;ue++){var ce=!1;(re=t.readBoolean())||t.readBoolean()?t.readEG():ce=t.readBoolean();var de=ce?1:t.readUEG()+1;if(se)for(var he=0;he<de;he++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(oe)for(var fe=0;fe<de;fe++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var ve=b,ge=A;if(L){var pe=1,ye=1;1===T?pe=ye=2:2==T&&(pe=2),ve=b-pe*I-pe*R,ge=A-ye*_-ye*w}for(var me=n?["A","B","C"][n]:"",Ee=s<<24|o<<16|l<<8|u,ke=0,Se=0;Se<32;Se++)ke=(ke|(Ee>>Se&1)<<31-Se)>>>0;var Te=ke.toString(16);1===a&&"2"===Te&&(Te="6");var be=i?"H":"L";return{codecString:"hvc1.".concat(me).concat(a,".").concat(Te,".").concat(be).concat(p,".B0"),params:{general_tier_flag:i,general_profile_idc:a,general_profile_space:n,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[c,d,h,f,v,g],general_level_idc:p,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:Z,chroma_format_idc:T,frame_rate:{fixed:re,fps:ie/ne}},width:ve,height:ge,pixelRatio:[ee,te]}}},{key:"readPPS",value:function(e){var t=new Ua(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);var r=t.readBoolean(),n=t.readBoolean(),i=1;return n&&r?i=0:n?i=3:r&&(i=2),{parallelismType:i}}},{key:"matchSPS",value:function(e,t){return $e(e).substring(3)===$e(t).substring(3)}}])}(Na),ja=188,Ka=function(){function e(t,r,n,i){c(this,e),this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=r,this.typeSupported=n,this.logger=i,this.videoParser=null}return h(e,[{key:"resetInitSegment",value:function(t,r,n,i,a,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new Qa(this.logger):null,this._audioTrack=e.createTrack("audio",i),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n,t&&this.demux(t,0,s,"SAMPLE-AES"===(null==a?void 0:a.method))}},{key:"resetTimeStamp",value:function(){}},{key:"resetContiguity",value:function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}},{key:"demux",value:function(t,r,n){var i,a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];a||(this.sampleAes=null);var o=this._videoTrack,l=this.videoIntegrityChecker,u=this._audioTrack,c=this._id3Track,d=this._txtTrack,h=n.iframe,f=o.pid,v=o.pesData,g=u.pid,p=c.pid,y=this._klvPid,m=u.pesData,E=c.pesData,k=null,S=null,T=this.pmtParsed,b=this._pmtId,A=t.length;if(this.remainderData&&(A=(t=At(this.remainderData,t)).length,this.remainderData=null),A<ja&&!s)return this.remainderData=t,{audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};var L=Math.max(0,e.syncOffset(t));(A-=(A-L)%ja)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,A,t.buffer.byteLength-A));for(var R=0,I=L;I<A;I+=ja)if(71===t[I]){var w=!!(64&t[I+1]),_=Ha(t,I),P=void 0;if((48&t[I+3])>>4>1){if((P=I+5+t[I+4])===I+ja)continue}else P=I+4;switch(_){case f:w&&(!v||null!=l&&l.isCorrupted||!(i=za(v,this.logger))||(this.readyVideoParser(o.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(o,d,i,!1,n)),v={data:[],size:0},null==l||l.reset(f)),null==l||l.handlePacket(t.subarray(I)),v&&(v.data.push(t.subarray(P,I+ja)),v.size+=I+ja-P);break;case g:if(h)break;if(w){if(m&&(i=za(m,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,i,n);break;case"mp3":this.parseMPEGPES(u,i);break;case"ac3":this.parseAC3PES(u,i)}m={data:[],size:0}}m&&(m.data.push(t.subarray(P,I+ja)),m.size+=I+ja-P);break;case p:if(h)break;w&&(E&&(i=za(E,this.logger))&&this.parseID3PES(c,i),E={data:[],size:0}),E&&(E.data.push(t.subarray(P,I+ja)),E.size+=I+ja-P);break;case y:if(h)break;w&&(k&&(i=za(k,this.logger))&&this.parseKlvPES(c,i),k={data:[],size:0}),k&&(k.data.push(t.subarray(P,I+ja)),k.size+=I+ja-P);break;case 0:w&&(P+=t[P]+1),b=this._pmtId=Va(t,P);break;case b:w&&(P+=t[P]+1);var D=qa(t,P,this.typeSupported,a,this.observer,this.logger,this.config,n);(f=D.videoPid)>0&&(o.pid=f,o.segmentCodec=D.segmentVideoCodec),(g=D.audioPid)>0&&(u.pid=g,u.segmentCodec=D.segmentAudioCodec),(p=D.id3Pid)>0&&(c.pid=p),(y=D.klvPid)>0&&(this._klvPid=y),null===S||T||(this.logger.warn("MPEG-TS PMT found at ".concat(I," after unknown PID '").concat(S,"'. Backtracking to sync byte @").concat(L," to parse all TS packets.")),S=null,I=L-188),T=this.pmtParsed=!0;break;case 17:case 8191:break;default:S=_}}else R++;R>0&&Wa(this.observer,new Error("Found ".concat(R," TS packet/s that do not start with 0x47")),n,void 0,this.logger),o.pesData=v,u.pesData=m,c.pesData=E;var C={audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};return s&&this.extractRemainingSamples(C,n),C}},{key:"flush",value:function(e,t){var r,n=this.remainderData;return this.remainderData=null,r=n?this.demux(n,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r,t),this.sampleAes?this.decrypt(r,this.sampleAes):r}},{key:"extractRemainingSamples",value:function(e,t){var r,n=e.audioTrack,i=e.videoTrack,a=e.id3Track,s=e.textTrack,o=i.pesData,l=n.pesData,u=a.pesData,c=this.videoIntegrityChecker;if(!o||null!=c&&c.isCorrupted||!(r=za(o,this.logger))?i.pesData=o:(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,s,r,!0,t),i.pesData=null)),l&&(r=za(l,this.logger))){switch(n.segmentCodec){case"aac":this.parseAACPES(n,r,t);break;case"mp3":this.parseMPEGPES(n,r);break;case"ac3":this.parseAC3PES(n,r)}n.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),n.pesData=l;u&&(r=za(u,this.logger))?(this.parseID3PES(a,r),a.pesData=null):a.pesData=u}},{key:"demuxSampleAes",value:function(e,t,r,n){var i=this.demux(e,r,n,!0,!this.config.progressive),a=this.sampleAes=new wa(this.observer,this.config,t);return this.decrypt(i,a)}},{key:"readyVideoParser",value:function(e){null===this.videoParser&&("avc"===e?this.videoParser=new Ba:"hevc"===e&&(this.videoParser=new Ga))}},{key:"decrypt",value:function(e,t){return new Promise(function(r){var n=e.audioTrack,i=e.videoTrack;n.samples&&"aac"===n.segmentCodec?t.decryptAacSamples(n.samples,0,function(){i.samples?t.decryptAvcSamples(i.samples,0,0,function(){r(e)}):r(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,function(){r(e)})})}},{key:"destroy",value:function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}},{key:"parseAACPES",value:function(e,t,r){var n,i,a,s=0,o=this.aacOverFlow,l=t.data;if(o){this.aacOverFlow=null;var u=o.missing,c=o.sample.unit.byteLength;if(-1===u)l=At(o.sample.unit,l);else{var d=c-u;o.sample.unit.set(l.subarray(0,u),d),e.samples.push(o.sample),s=o.missing}}for(n=s,i=l.length;n<i-1&&!ca(l,n);n++);if(n!==s){var h,f=n<i-1;if(h=f?"AAC PES did not start with ADTS header,offset:".concat(n):"No ADTS header found in AAC PES",Wa(this.observer,new Error(h),r,f,this.logger),!f)return}if(ha(e,this.observer,l,n,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!o)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var v=fa(e.samplerate);a=o.sample.pts+v}for(var g,p=0;n<i;){if(n+=(g=va(e,l,n,a,p)).length,g.missing){this.aacOverFlow=g;break}for(p++;n<i-1&&!ca(l,n);n++);}}},{key:"parseMPEGPES",value:function(e,t){var r=t.data,n=r.length,i=0,a=0,s=t.pts;if(void 0!==s)for(;a<n;)if(Ra(r,a)){var o=ba(e,r,a,s,i);if(!o)break;a+=o.length,i++}else a++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}},{key:"parseAC3PES",value:function(e,t){var r=t.data,n=t.pts;if(void 0!==n)for(var i,a=r.length,s=0,o=0;o<a&&(i=Ca(e,r,o,n,s++))>0;)o+=i;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")}},{key:"parseID3PES",value:function(e,t){if(void 0!==t.pts){var r=ie({},t,{type:this._videoTrack?ga.emsg:ga.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")}},{key:"parseKlvPES",value:function(e,t){var r,n=null!=(r=t.pts)?r:t.dts;if(void 0!==n){var i=t.data;if(i.length<16)this.logger.warn("[tsdemuxer]: KLV PES payload too short");else for(var a=0;a<i.length;){var s;if(a+16>i.length)break;var o=a;if((a+=16)>=i.length)break;var l=i[a];a+=1;var u=0;if(128&l){var c=127&l;if(0===c||c>4||a+c>i.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(var d=0;d<c;d++)u=u<<8|i[a+d];a+=c}else u=l;if(a+u>i.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}var h=a+u,f=i.subarray(o,h),v={data:f,len:f.byteLength,pts:n,dts:null!=(s=t.dts)?s:n,type:ga.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(v),a=h}}else this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS")}}],[{key:"probe",value:function(t,r){var n=e.syncOffset(t);return n>0&&r.warn("MPEG2-TS detected but first sync word found @ offset ".concat(n)),-1!==n}},{key:"syncOffset",value:function(e){for(var t=e.length,r=Math.min(940,t-ja)+1,n=0;n<r;){for(var i=!1,a=-1,s=0,o=n;o<t;o+=ja){if(71!==e[o]||t-o!==ja&&71!==e[o+ja]){if(s)return-1;break}if(s++,-1===a&&0!==(a=o)&&(r=Math.min(a+18612,e.length-ja)+1),i||(i=0===Ha(e,o)),i&&s>1&&(0===a&&s>2||o+ja>r))return a}n++}return-1}},{key:"createTrack",value:function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:tt[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}}])}();function Ha(e,t){return((31&e[t+1])<<8)+e[t+2]}function Va(e,t){return(31&e[t+10])<<8|e[t+11]}function qa(e,t,r,n,i,a,s,o){var l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<u;){var c=Ha(e,t),d=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!n){Ya("ADTS AAC",a);break}case 15:-1===l.audioPid&&(l.audioPid=c);break;case 21:-1===l.id3Pid&&(l.id3Pid=c);break;case 219:if(!n){Ya("H.264",a);break}case 27:-1===l.videoPid&&(l.videoPid=c);break;case 3:case 4:r.mpeg||r.mp3?-1===l.audioPid&&(l.audioPid=c,l.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!n){Ya("AC-3",a);break}case 129:r.ac3?-1===l.audioPid&&(l.audioPid=c,l.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(d>0)for(var h=t+5,f=d;f>2;){switch(e[h]){case 106:-1===l.audioPid&&(!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=c,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&s.enableEmsgKLVMetadata&&(l.klvPid=c,a.log("KLV metadata PID found: ".concat(c)))}var v=e[h+1]+2;h+=v,f-=v}break;case 194:case 135:return Wa(i,new Error("Unsupported EC-3 in M2TS found"),o,void 0,a),l;case 36:-1===l.videoPid&&(l.videoPid=c,l.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=d+5}return l}function Wa(e,t,r,n,i){i.warn("parsing error: ".concat(t.message)),e.emit(B.ERROR,B.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,chunkMeta:r,error:t,reason:t.message})}function Ya(e,t){t.log("".concat(e," with AES-128-CBC encryption found in unencrypted stream"))}function za(e,t){var r,n,i,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=At(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((n=(r[4]<<8)+r[5])&&n>e.size-6)return null;var u=r[7];192&u&&(a=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?a-(s=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(t.warn("".concat(Math.round((a-s)/9e4),"s delta between PTS and DTS, align them")),a=s):s=a);var c=(i=r[8])+9;if(e.size<=c)return null;e.size-=c;for(var d=new Uint8Array(e.size),h=0,f=l.length;h<f;h++){var v=(r=l[h]).byteLength;if(c){if(c>v){c-=v;continue}r=r.subarray(c),v-=c,c=0}d.set(r,o),o+=v}return n&&(n-=i+3),{data:d,pts:a,dts:s,len:n}}return null}var Xa,Qa=function(){return h(function e(t){c(this,e),this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t},[{key:"isCorrupted",get:function(){return"ok"!==this.integrityState}},{key:"reset",value:function(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}},{key:"handlePacket",value:function(e){if(!(e.byteLength<4)){var t=Ha(e,0);if(t===this.pid){var r=(48&e[3])>>4;if(0!==r){var n=15&e[3],i=this.lastContinuityCounter;this.lastContinuityCounter=n;var a=!!(1&r);if(!(!!(2&r)&&0!=e[4]&&!!(128&e[5])||i<0)){var s=a?i+1&15:i;return n!==s?(this.logger.warn("MPEG-TS Continuity Counter check failed for PID='".concat(t,"', CC=").concat(n,", Expected-CC=").concat(s," Last-CC=").concat(i)),void(this.integrityState="cc-failed")):128&e[1]?(this.logger.warn("MPEG-TS Packet had TEI flag set for PID='".concat(t,"'")),void(this.integrityState="tei-bit")):void 0}}}else this.logger.debug("Packet PID mismatch, expected ".concat(this.pid," got ").concat(t))}}}])}(),$a=function(){return h(function e(){c(this,e)},null,[{key:"getSilentFrame",value:function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}])}(),Ja={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Za=new Uint8Array([0,0,0,0,0,0,0,0]),es=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),ts=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),rs=new Uint8Array([0,0,0,0,0,0,0,0]),ns=new Uint8Array([0,0,0,0,0,0,0,1]),is=new Uint8Array([105,115,111,109]),as=new Uint8Array([97,118,99,49]),ss=new Uint8Array([0,0,0,1]),os=function(){function e(){c(this,e)}return h(e,null,[{key:"box",value:function(e){for(var t=8,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];for(var a=n.length,s=a;a--;)t+=n[a].byteLength;var o=new Uint8Array(t);for(ot(o,0,t),ot(o,4,e),a=0,t=8;a<s;a++)o.set(n[a],t),t+=n[a].byteLength;return o}},{key:"hdlr",value:function(t){return e.box(et.hdlr,Ja[t])}},{key:"mdat",value:function(t){return e.box(et.mdat,t)}},{key:"mdhd",value:function(t,r){r*=t;var n=Math.floor(r/(Ze+1)),i=Math.floor(r%(Ze+1));return e.box(et.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,n>>24,n>>16&255,n>>8&255,255&n,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(et.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(et.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{key:"minf",value:function(t){return"audio"===t.type?e.box(et.minf,e.box(et.smhd,rs),e.DINF,e.stbl(t)):e.box(et.minf,e.box(et.vmhd,ts),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,n){return e.box(et.moof,e.mfhd(t),e.traf(n,r))}},{key:"moov",value:function(t){for(var r=t.length,n=[];r--;)n[r]=e.trak(t[r]);return e.box.apply(null,[et.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(n).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,n=[];r--;)n[r]=e.trex(t[r]);return e.box.apply(null,[et.mvex].concat(n))}},{key:"mvhd",value:function(t,r){r*=t;var n=Math.floor(r/(Ze+1)),i=Math.floor(r%(Ze+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,n>>24,n>>16&255,n>>8&255,255&n,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(et.mvhd,a)}},{key:"sdtp",value:function(t){var r,n,i=t.samples||[],a=new Uint8Array(4+i.length);for(r=0;r<i.length;r++)n=i[r].flags,a[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return e.box(et.sdtp,a)}},{key:"stbl",value:function(t){return e.box(et.stbl,e.stsd(t),e.box(et.stts,Za),e.box(et.stsc,Za),e.box(et.stsz,es),e.box(et.stco,Za))}},{key:"avc1",value:function(t){var r,n,i,a=[],s=[];for(r=0;r<t.sps.length;r++)i=(n=t.sps[r]).byteLength,a.push(i>>>8&255),a.push(255&i),a=a.concat(Array.prototype.slice.call(n));for(r=0;r<t.pps.length;r++)i=(n=t.pps[r]).byteLength,s.push(i>>>8&255),s.push(255&i),s=s.concat(Array.prototype.slice.call(n));var o=e.box(et.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,c=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(et.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,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,e.box(et.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(et.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}},{key:"esds",value:function(e){var t=e.config,r=t.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5,r].concat(I(t),[6,1,2]))}},{key:"audioStsd",value:function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}},{key:"mp4a",value:function(t){return e.box(et.mp4a,e.audioStsd(t),e.box(et.esds,e.esds(t)))}},{key:"mp3",value:function(t){return e.box(et[".mp3"],e.audioStsd(t))}},{key:"ac3",value:function(t){return e.box(et["ac-3"],e.audioStsd(t),e.box(et.dac3,t.config))}},{key:"stsd",value:function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(et.stsd,ns,e.mp4a(t));if("ac3"===r&&t.config)return e.box(et.stsd,ns,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(et.stsd,ns,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===r)return e.box(et.stsd,ns,e.avc1(t));if("hevc"===r&&t.vps)return e.box(et.stsd,ns,e.hvc1(t))}throw new Error("unsupported ".concat(t.type," segment codec (").concat(r,"/").concat(t.codec,")"))}},{key:"tkhd",value:function(t){var r=t.id,n=(t.duration||0)*(t.timescale||0),i=t.width||0,a=t.height||0,s=Math.floor(n/(Ze+1)),o=Math.floor(n%(Ze+1));return e.box(et.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,a>>8&255,255&a,0,0]))}},{key:"traf",value:function(t,r){var n=e.sdtp(t),i=t.id,a=Math.floor(r/(Ze+1)),s=Math.floor(r%(Ze+1));return e.box(et.traf,e.box(et.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),e.box(et.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,n.length+16+20+8+16+8+8),n)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(et.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(et.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,r){var n,i,a,s,o,l,u=t.samples||[],c=u.length,d=12+16*c,h=new Uint8Array(d);for(r+=8+d,h.set(["video"===t.type?1:0,0,15,1,c>>>24&255,c>>>16&255,c>>>8&255,255&c,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),n=0;n<c;n++)a=(i=u[n]).duration,s=i.size,o=i.flags,l=i.cts,h.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*n);return e.box(et.trun,h)}},{key:"initSegment",value:function(t){var r=e.moov(t);return At(e.FTYP,r)}},{key:"hvc1",value:function(t){for(var r=t.params,n=[t.vps,t.sps,t.pps],i=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),n.length]),a=i.length,s=0;s<n.length;s+=1){a+=3;for(var o=0;o<n[s].length;o+=1)a+=2+n[s][o].length}var l=new Uint8Array(a);l.set(i,0),a=i.length;for(var u=n.length-1,c=0;c<n.length;c+=1){l.set(new Uint8Array([32+c|(c===u?128:0),0,n[c].length]),a),a+=3;for(var d=0;d<n[c].length;d+=1)l.set(new Uint8Array([n[c][d].length>>8,255&n[c][d].length]),a),a+=2,l.set(n[c][d],a),a+=n[c][d].length}var h=e.box(et.hvcC,l),f=t.width,v=t.height,g=t.pixelRatio[0],p=t.pixelRatio[1];return e.box(et.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,f>>8&255,255&f,v>>8&255,255&v,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]),h,e.box(et.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(et.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,255&g,p>>24,p>>16&255,p>>8&255,255&p])))}}])}();Xa=os,os.FTYP=Xa.box(et.ftyp,is,ss,is,as),os.DINF=Xa.box(et.dinf,Xa.box(et.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));function ls(e,t){var r=e*t*(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1);return arguments.length>3&&void 0!==arguments[3]&&arguments[3]?Math.round(r):r}function us(e){return ls(e,1e3,1/9e4,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}function cs(e){var t=e.baseTime,r=e.timescale,n=e.trackId;return"".concat(t/r," (").concat(t,"/").concat(r,") trackId: ").concat(n)}var ds=8589934592;function hs(e,t,r,n){return{duration:t,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}var fs=function(e){function t(e,r,n,i){var a;return c(this,t),(a=u(this,t,["mp4-remuxer",i])).observer=void 0,a.config=void 0,a.typeSupported=void 0,a.ISGenerated=!1,a._initPTS=null,a._initDTS=null,a.nextVideoTs=null,a.nextAudioTs=null,a.videoSampleDuration=null,a.isAudioContiguous=!1,a.isVideoContiguous=!1,a.videoTrackConfig=void 0,a.observer=e,a.config=r,a.typeSupported=n,a.ISGenerated=!1,a}return y(t,e),h(t,[{key:"destroy",value:function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}},{key:"resetTimeStamp",value:function(e){var t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log("Reset initPTS: ".concat(t?cs(t):t," > ").concat(e?cs(e):e)),this._initPTS=this._initDTS=e}},{key:"resetNextTimestamp",value:function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}},{key:"resetInitSegment",value:function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}},{key:"getVideoStartPts",value:function(e){var t=!1,r=e[0].pts,n=e.reduce(function(e,n){var i=n.pts,a=i-e;return a<-4294967296&&(t=!0,a=(i=vs(i,r))-e),a>0?e:i},r);return t&&this.debug("PTS rollover detected"),n}},{key:"remux",value:function(e,t,r,n,i,a,s,o,l){var u,c,d,h,f,v,g=i,p=i,y=!l.iframe&&e.pid>-1,m=t.pid>-1,E=t.samples.length,k=e.samples.length>0,S=s&&E>0||E>1;if((!y||k)&&(!m||S)||this.ISGenerated||s){if(this.ISGenerated){var T,b,A,L,R=this.videoTrackConfig;(R&&(t.width!==R.width||t.height!==R.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(b=R.pixelRatio)?void 0:b[0])||(null==(A=t.pixelRatio)?void 0:A[1])!==(null==(L=R.pixelRatio)?void 0:L[1]))||!R&&S||null===this.nextAudioTs&&k)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,i,a));var I,w=this.isVideoContiguous,_=-1;if(S&&(_=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!w&&this.config.forceKeyFrameOnDiscontinuity))if(v=!0,_>0){this.warn("Dropped ".concat(_," out of ").concat(E," video samples due to a missing keyframe"));var P=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(_),t.dropped+=_,I=p+=(t.samples[0].pts-P)/t.inputTimeScale}else-1===_&&(this.warn("No keyframe found out of ".concat(E," video samples")),v=!1);if(this.ISGenerated){if(k&&S&&i){var D=this.getVideoStartPts(t.samples),C=(vs(e.samples[0].pts,D)-D)/t.inputTimeScale;g+=Math.max(0,C),p+=Math.max(0,-C)}if(k){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,i,a)),c=this.remuxAudio(e,g,this.isAudioContiguous,a,m||S||o===W.AUDIO?p:void 0,l),S){var O=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,i,a)),u=this.remuxVideo(t,p,w,O,l)}}else S&&(u=this.remuxVideo(t,p,w,0,l));u&&(u.firstKeyFrame=_,u.independent=-1!==_,u.firstKeyFramePTS=I)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=gs(r,i,this._initPTS,this._initDTS)),n.samples.length&&(h=ps(n,i,this._initPTS))),{audio:c,video:u,initSegment:d,independent:v,text:h,id3:f}}},{key:"computeInitPts",value:function(e,t,r,n){var i=Math.round(r*t),a=vs(e,i);if(a<i)for(this.log("Adjusting PTS for rollover in timeline near ".concat((i-a)/t," ").concat(n));a<i;)a+=ds;return a-i}},{key:"generateIS",value:function(e,t,r,n){var i,a,s,o=e.samples,l=t.samples,u=this.typeSupported,c={},d=this._initPTS,h=!d||n,f="audio/mp4",v=-1;if(h&&(i=a=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(f="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}if(c.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):os.initSegment([e]),metadata:{channelCount:e.channelCount}},h){v=e.id,s=e.inputTimeScale;var g=this.computeInitPts(o[0].pts,s,r,"audio");(!d||s!==d.timescale||0===r&&g<d.baseTime)&&(i=a=g)}}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:os.initSegment([t]),metadata:{width:t.width,height:t.height}},h){v=t.id,s=t.inputTimeScale;var p=this.getVideoStartPts(l),y=vs(l[0].dts,p),m=this.computeInitPts(y,s,r,"video"),E=this.computeInitPts(p,s,r,"video");(!d||s!==d.timescale||x(i)||0===r&&E<d.baseTime)&&(a=Math.min(a,m),i=Math.min(i,m))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h&&x(i)?(d&&this.warn("Timestamps at playlist time: ".concat(n?"":"~").concat(r," ").concat(i/s," != initPTS: ").concat(d.baseTime/d.timescale," (").concat(d.baseTime,"/").concat(d.timescale,") trackId: ").concat(d.trackId)),this.log("Found initPTS at playlist time: ".concat(r," offset: ").concat(i/s," (").concat(i,"/").concat(s,") trackId: ").concat(v)),this._initPTS={baseTime:i,timescale:s,trackId:v},this._initDTS={baseTime:a,timescale:s,trackId:v}):i=s=void 0,{tracks:c,initPTS:i,timescale:s,trackId:v}}},{key:"remuxVideo",value:function(e,t,r,n,i){var a,s,o=e.inputTimeScale,l=e.samples,u=[],c=l.length,d=this._initPTS,h=d.baseTime*o/d.timescale,f=this.nextVideoTs,v=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,m=!1;if(!r||null===f){var E=h+t*o,k=l[0].pts-vs(l[0].dts,l[0].pts);Ut()&&null!==f&&Math.abs(E-k-(f+h))<15e3?r=!0:f=E-k-h}for(var S=f+h,T=0;T<c;T++){var b=l[T];b.pts=vs(b.pts,S),b.dts=vs(b.dts,S),b.dts<l[T>0?T-1:T].dts&&(m=!0)}m&&l.sort(function(e,t){var r=e.dts-t.dts,n=e.pts-t.pts;return r||n}),a=l[0].dts;var A=(s=l[l.length-1].dts)-a,L=A?Math.round(A/(c-1)):g||e.inputTimeScale/30;if(r){var R=a-S,I=R>L,w=R<-1;if((I||w)&&(I?this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(us(R,!0)," ms (").concat(R,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(us(-R,!0)," ms (").concat(R,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!w||S>=l[0].pts||Ut())){a=S;var _=l[0].pts-R;if(I)l[0].dts=a,l[0].pts=_;else for(var P=!0,D=0;D<l.length&&!(l[D].dts>_&&P);D++){var C=l[D].pts;if(l[D].dts-=R,l[D].pts-=R,D<l.length-1){var O=l[D+1].pts;P=O<=l[D].pts==O<=C}}this.log("Video: Initial PTS/DTS adjusted: ".concat(us(_,!0),"/").concat(us(a,!0),", delta: ").concat(us(R,!0)," ms"))}}for(var x=0,M=0,F=a=Math.max(0,a),G=0;G<c;G++){for(var j=l[G],K=j.units,H=K.length,V=0,q=0;q<H;q++)V+=K[q].data.length;M+=V,x+=H,j.length=V,j.dts<F?(j.dts=F,F+=L/4|0||1):F=j.dts,p=Math.min(j.pts,p),y=Math.max(j.pts,y)}s=l[c-1].dts;var W,Y=M+4*x+8;try{W=new Uint8Array(Y)}catch(Re){return void this.observer.emit(B.ERROR,B.ERROR,{type:N.MUX_ERROR,details:U.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:i,error:Re,bytes:Y,reason:"fail allocating video mdat ".concat(Y)})}ot(W,0,Y),ot(W,4,et.mdat);for(var z=!1,X=Number.POSITIVE_INFINITY,Q=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,J=Number.NEGATIVE_INFINITY,Z=0;Z<c;Z++){for(var ee=l[Z],te=ee.units,re=0,ne=0,ae=te.length;ne<ae;ne++){var se=te[ne],oe=se.data,le=se.data.byteLength;ot(W,v,le),v+=4,W.set(oe,v),v+=le,re+=4+le}var ue=void 0;if(Z<c-1)g=l[Z+1].dts-ee.dts,ue=l[Z+1].pts-ee.pts;else{var ce=this.config,de=Z>0?ee.dts-l[Z-1].dts:L;if(ue=Z>0?ee.pts-l[Z-1].pts:L,ce.stretchShortVideoTrack&&null!==this.nextAudioTs){var he=Math.floor(ce.maxBufferHole*o),fe=(n?p+n*o:this.nextAudioTs+h)-ee.pts;fe>he?((g=fe-de)<0?g=de:z=!0,this.log("It is approximately ".concat(fe/90," ms to the next segment; using duration ").concat(g/90," ms for the last video frame."))):g=de}else g=de}var ve=Math.round(ee.pts-ee.dts);if(X=Math.min(X,g),$=Math.max($,g),Q=Math.min(Q,ue),J=Math.max(J,ue),!r&&0===Z&&ve>g){var ge=Math.round(ve/L)*L;ge-ve===1&&(this.log("pad first CTS ".concat(ve," -> ").concat(ge," of sn: ").concat(i.sn)),ve=ge)}u.push(hs(ee.key,g,re,ve))}if(u.length){var pe=Ut();if(pe){if(pe<70){var ye=u[0].flags;ye.dependsOn=2,ye.isNonSync=0}}else if(function(){if(void 0===xt){var e=Mt.match(/Safari\/(\d+)/i);xt=e?parseInt(e[1]):0}return xt}()&&J-Q<$-X&&L/$<.025&&0===u[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var me=a,Ee=0,ke=u.length;Ee<ke;Ee++){var Se=me+u[Ee].duration,Te=me+u[Ee].cts;if(Ee<ke-1){var be=Se+u[Ee+1].cts;u[Ee].duration=be-Te}else u[Ee].duration=Ee?u[Ee-1].duration:L;u[Ee].cts=0,me=Se}}}var Ae=s+(g=z||!g?L:g);this.nextVideoTs=f=Ae-h,this.videoSampleDuration=g,this.isVideoContiguous=!0,i.iframe&&(1===u.length?(u[0].duration=g=i.duration*o,this.nextVideoTs=f=a+g-h):this.warn("Not adjusting IFrame duration (sample count ".concat(u.length,")")));var Le={data1:os.moof(i.sn,a,ie(e,{samples:u})),data2:W,startPTS:(p-h)/o,endPTS:(y+g-h)/o,startDTS:(a-h)/o,endDTS:f/o,type:"video",hasAudio:!1,hasVideo:!0,nb:u.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Le}},{key:"getSamplesPerFrame",value:function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}},{key:"remuxAudio",value:function(e,t,r,n,i,a){var s=e.inputTimeScale,o=s/(e.samplerate?e.samplerate:s),l=this.getSamplesPerFrame(e),u=l*o,c=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,h=[],f=void 0!==i,v=e.samples,g=d?0:8,p=this.nextAudioTs||-1,y=c.baseTime*s/c.timescale,m=y+t*s;if(this.isAudioContiguous=r=r||v.length&&p>0&&(n&&Math.abs(m-(p+y))<9e3||Math.abs(vs(v[0].pts,m)-(p+y))<20*u),v.forEach(function(e){e.pts=vs(e.pts,m)}),!r||p<0){var E=v.length;if(v=v.filter(function(e){return e.pts>=0}),E!==v.length&&this.warn("Removed ".concat(v.length-E," of ").concat(E," samples (initPTS ").concat(y," / ").concat(s,")")),!v.length)return;p=0===i?0:n&&!f?Math.max(0,m-y):v[0].pts-y}if("aac"===e.segmentCodec)for(var k=this.config.maxAudioFramesDrift,S=0,T=p+y;S<v.length;S++){var b=v[S],A=b.pts,L=A-T,R=Math.abs(1e3*L/s);if(L<=-k*u&&f)0===S&&(this.warn("Audio frame @ ".concat((A/s).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*L/s)," ms.")),this.nextAudioTs=p=A-y,T=A);else if(L>=k*u&&R<1e4&&f){var I=Math.round(L/u);for(T=A-I*u;T<0&&I&&u;)I--,T+=u;0===S&&(this.nextAudioTs=p=T-y),this.warn("Injecting ".concat(I," audio frames @ ").concat(((T-y)/s).toFixed(3),"s due to ").concat(Math.round(1e3*L/s)," ms gap."));for(var w=0;w<I;w++){var _=$a.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);_||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),_=b.unit.subarray()),v.splice(S,0,{unit:_,pts:T}),T+=u,S++}}b.pts=T,T+=u}for(var P,D=null,C=null,O=0,x=v.length;x--;)O+=v[x].unit.byteLength;for(var M=0,F=v.length;M<F;M++){var G=v[M],j=G.unit,K=G.pts;if(null!==C){h[M-1].duration=Math.round((K-C)/o)}else{if(r&&"aac"===e.segmentCodec&&(K=p+y),D=K,!(O>0))return;O+=g;try{P=new Uint8Array(O)}catch(Q){return void this.observer.emit(B.ERROR,B.ERROR,{type:N.MUX_ERROR,details:U.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:Q,bytes:O,reason:"fail allocating audio mdat ".concat(O)})}d||(ot(P,0,O),ot(P,4,et.mdat))}P&&P.set(j,g);var H=j.byteLength;g+=H,h.push(hs(!0,l,H,0)),C=K}var V=h.length;if(V){var q=h[h.length-1];p=C-y,this.nextAudioTs=p+o*q.duration;var W=d?new Uint8Array(0):os.moof(e.sequenceNumber++,D/o,ie({},e,{samples:h}));e.samples=[];var Y=(D-y)/s,z=this.nextAudioTs/s,X={data1:W,data2:P,startPTS:Y,endPTS:z,startDTS:Y,endDTS:z,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,X}}}])}(Ee);function vs(e,t){var r;if(null===t)return e;for(r=t<e?-8589934592:ds;Math.abs(e-t)>4294967296;)e+=r;return e}function gs(e,t,r,n){var i=e.samples.length;if(i){for(var a=e.inputTimeScale,s=0;s<i;s++){var o=e.samples[s];o.pts=vs(o.pts-r.baseTime*a/r.timescale,t*a)/a,o.dts=vs(o.dts-n.baseTime*a/n.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function ps(e,t,r){var n=e.samples.length;if(n){for(var i=e.inputTimeScale,a=0;a<n;a++){var s=e.samples[a];s.pts=vs(s.pts-r.baseTime*i/r.timescale,t*i)/i}e.samples.sort(function(e,t){return e.pts-t.pts});var o=e.samples;return e.samples=[],{samples:o}}}var ys,ms=function(e){function t(e,r,n,i){var a;return c(this,t),(a=u(this,t,["passthrough-remuxer",i])).observer=void 0,a.emitInitSegment=!1,a.audioCodec=void 0,a.videoCodec=void 0,a.initData=void 0,a.initPTS=null,a.initTracks=void 0,a.lastEndTime=null,a.isVideoContiguous=!1,a.videoOnlyRemux=!1,a.decryptdata=null,a.pendingInitSegment=void 0,a.observer=e,a}return y(t,e),h(t,[{key:"destroy",value:function(){this.observer&&this.observer.removeAllListeners(),this.observer=null}},{key:"resetTimeStamp",value:function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}},{key:"resetNextTimestamp",value:function(){this.isVideoContiguous=!1,this.lastEndTime=null}},{key:"resetInitSegment",value:function(e,t,r,n){this.audioCodec=t,this.videoCodec=r,this.decryptdata=n,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}},{key:"generateInitSegment",value:function(e,t,r){this.videoOnlyRemux=!1;var n=this.audioCodec,i=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var a=this.initData=r||vt(e),s=a.audio,o=a.video;if(t)!function(e,t){if(e&&t){var r=t.keyId;16===(null==r?void 0:r.byteLength)&&t.isCommonEncryption&&kt(e,function(e,t){var n=e.subarray(8,24);n.some(function(e){return 0!==e})||(Le.log("[eme] Patching keyId in 'enc".concat(t?"a":"v",">sinf>>tenc' box: ").concat(ze(n)," -> ").concat(ze(r))),e.set(r,8))})}}(e,t);else{var l=s||o;null!=l&&l.encrypted&&this.warn('Init segment with encrypted track with has no key ("'.concat(l.codec,'")!'))}s&&(n=ks(s,Y,this)),o&&(i=ks(o,z,this));var u={};s&&o?u.audiovideo={container:"video/mp4",codec:n+","+i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:s?u.audio={container:"audio/mp4",codec:n,encrypted:s.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}},{key:"remux",value:function(e,t,r,n,i,a,s,o,l,u,c){var d,h,f=this.initPTS,v=this.lastEndTime,g={audio:void 0,video:void 0,text:void 0,id3:r,initSegment:void 0};x(v)||(v=this.lastEndTime=i||0);var p=t.samples;if(!p.length)return g;var y=this.pendingInitSegment;y&&(this.pendingInitSegment=void 0,this.generateInitSegment(y,this.decryptdata,u));var m={initPTS:void 0,timescale:void 0,trackId:void 0},E=this.initData;if(null!=(d=E)&&d.length||(this.generateInitSegment(p),E=this.initData),null==(h=E)||!h.length)return this.warn("Failed to generate initSegment."),g;if(l.iframe&&E.audio&&E.video){var k,S,T=null==(k=this.initTracks)||null==(k=k.audiovideo)?void 0:k.initSegment,b=T?function(e){var t=dt(e,["moov"]);if(1!==t.length||dt(e,["moof"]).length)return null;for(var r=e.byteOffset,n=[],i=[],a=!1,s=dt(t[0],["trak"]),o=0;o<s.length;o++){var l=s[o],u=dt(l,["mdia","hdlr"])[0];if("vide"!==(u?$e(u.subarray(8,12)):"")){var c=dt(l,["tkhd"])[0];if(!c)return null;var d=c[0];i.push(nt(c,0===d?12:20)),n.push(ut(l,r))}else a=!0}if(!a||!n.length)return null;var h=dt(t[0],["mvex"])[0],f=0;if(h)for(var v=dt(h,["trex"]),g=0;g<v.length;g++){var p=v[g];-1!==i.indexOf(nt(p,4))&&(n.push(ut(p,r)),f+=p.byteLength+8)}var y=ct(e,n),m=y.result,E=y.dropped,k=y.droppedBefore;if(ot(m,t[0].byteOffset-r-8,t[0].byteLength+8-E),h&&f){var S=h.byteOffset-r-8;ot(m,S-k(S),h.byteLength+8-f)}return m}(T):null;if(b)this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(b,this.decryptdata),null!=(S=this.initData)&&S.length&&(E=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}this.emitInitSegment&&(m.tracks=this.initTracks,g.initSegment=m,this.emitInitSegment=!1);var A=l.iframe,L=!c||A&&!c.includeSampleDetails?function(e,t,r,n){return bt(e,t,n,!(arguments.length>4&&void 0!==arguments[4])||arguments[4])}(p,E,l,this,A):c.tracks,R=E.audio?L[E.audio.id]:null,w=E.video?L[E.video.id]:null,_=!!E.audio,P=!!E.video,D="";_&&(D+="audio"),P&&(D+="video");var C,O=Es(w,1/0),M=Es(R,1/0),F=Es(w,0,!0),N=Es(R,0,!0),U=0;w&&R&&E.audio&&(M>F||O>N)&&this.warn("audio and video track sample timestamps do not overlap. v: ".concat(O,"-").concat(F," a: ").concat(M,"-").concat(N,"}"),w,R);var B=!!R&&(!w||!f&&M<O||!!f&&f.trackId===E.audio.id),G=B?R:w;if(!G)return this.log("No media samples found in ".concat(o," ").concat(l.level," ").concat(-1===l.part?"":"part: ".concat(l.part," of")," sn: ").concat(l.sn," at playlist time: ").concat(i)),g;var j,K=p;if(w&&w.sampleCount>=1&&E.video&&l.iframe){var H,V=w.trun,q=w.start,W=1===V.length,Y=V.length?W?V[0].samples:(H=V[0].samples).concat.apply(H,I(V.slice(1).map(function(e){return e.samples}))):[];if(Y.length){for(var z=V[0],X=z,Q=V.length;Q--;)if(V[Q].samples.length){X=V[Q];break}var $=X.lastSampleDurationOffset,J=z.defaultSampleDurationOffset,Z=Math.abs(l.duration-(F-O))>.05,ee=Y.length<w.sampleCount;if(Z||ee||this.videoOnlyRemux||!W){var te=ee?X.sampleOffset+X.samples.reduce(function(e,t){return e+t.size},0):void 0,re=Z?l.duration:F-O,ne=function(e,t,r,n){if(void 0!==r){for(var i=e[e.length-1],a=t,s=0;s<e.length-1;s++)a-=e[s].duration;return a<=0&&(a=i.duration),i.duration=a,{durationOffset:r,value:a}}if(void 0===n)return;for(var o=Math.round(t/e.length),l=0;l<e.length;l++)e[l].duration=o;return{durationOffset:n,value:o}}(Y,re*E.video.timescale,$,J),ie=function(e,t,r,n,i){if(r<1)return null;var a=dt(e,["moof"]);if(1!==a.length)return null;for(var s=a[0],o=e.byteOffset,l=[],u=[],c=dt(s,["traf"]),d=!0,h=0;h<c.length;h++){var f=c[h],v=dt(f,["tfhd"])[0];if(!v)return null;nt(v,4)===t?(l.push(f),131072&nt(v,0)||(d=!1)):u.push(ut(f,o))}if(!l.length)return null;if(u.length&&!d)return null;if(void 0!==n){for(var g=r,p=0;p<l.length;p++){for(var y=l[p],m=0,E=dt(y,["trun"]),k=0;k<E.length;k++){var S=E[k],T=Math.min(g,nt(S,4));if(T){ot(e,S.byteOffset-o+4,T);var b=16777215&nt(S,0);lt(e,S,8+(1&b?4:0)+(4&b?4:0)+T*((256&b?4:0)+(512&b?4:0)+(1024&b?4:0)+(2048&b?4:0)))}else ot(e,S.byteOffset-o-4,et.free);g-=T,m+=T}var A=dt(y,["senc"])[0];A&&ot(e,A.byteOffset-o+4,m);var L=dt(y,["saiz"])[0];if(L){var R=4;1&(L[1]<<16|L[2]<<8|L[3])&&(R+=8);var I=L[R];R+=1,ot(e,L.byteOffset-o+R,m),lt(e,L,R+4+(0===I?m:0))}}var w=dt(e,["mdat"]);if(1===w.length){var _=w[0].byteOffset-o-8;ot(e,_,n-_)}}var P=e,D=0,C=function(){return 0};if(u.length){var O=ct(e,u);P=O.result,D=O.dropped,C=O.droppedBefore,ot(P,s.byteOffset-o-8,s.byteLength+8-D);for(var x=0;x<l.length;x++){for(var M=l[x],F=C(M.byteOffset-o),N=dt(M,["trun"]),U=0;U<N.length;U++){var B=N[U];1&nt(B,0)&&ot(P,B.byteOffset-o-F+8,nt(B,8)-D)}if(F)for(var G=dt(M,["saio"]),j=0;j<G.length;j++){var K=G[j],H=0===K[0]?4:8,V=1&nt(K,0)?12:4,q=nt(K,V);for(V+=4;q--;V+=H){var W=V+H-4;ot(P,K.byteOffset-o-F+W,nt(K,W)-F)}}}}if(i){var Y=i.durationOffset,z=i.value;ot(P,Y-C(Y),z)}return void 0!==n?P.subarray(0,n-D):P}(p,E.video.id,Y.length,te,ne);ie?(K=ie,j=function(e,t){for(var r=e,n=e,i=0;i<t.length;i++){var a=t[i],s=a.cts,o=a.duration;n=Math.max(n,r+(s||0)+o),r+=o}return n}(q,Y)):this.warn("IFrame remux skipped (sn ".concat(l.sn,"); using native sample duration")),U=ie&&ne?re:F-O}else U=F-O}else this.warn("Could not remux IFrame track fragment (no samples in range, trun count ".concat(V.length,")")),U=F-O}else U=B?N-M:F-O;if(this.videoOnlyRemux&&K===p)return this.warn("Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ".concat(l.sn,")")),g;var ae=G.timescale,se=G.start-i*ae,oe=B?E.audio.id:E.video.id;if(C=G.start/ae,(a||!f)&&(function(e,t,r,n){if(null===e)return!0;var i=Math.max(n,1),a=t-e.baseTime/e.timescale;return Math.abs(a-r)>=i}(f,C,i,U)||ae!==f.timescale)){var le=!1,ue=B?"audio":"video";if(f){var ce=0!==i?C/i:1+C/1;le=C>=0&&Math.abs(1-ce)<.001,this.log("".concat(ue," timestamps in track ").concat(oe," at playlist time: ").concat(a?"":"~").concat(i," maps to ").concat(C," with initPTS: ").concat(f.baseTime/f.timescale," (").concat(se/ae-f.baseTime/f.timescale,"s diff) (").concat(D,") drift estimate: ").concat(ce," ").concat(le?"(ignoring drift)":"remapping timestamps (initPTS)"))}le||(this.log("Found initPTS in ".concat(ue," track ").concat(oe," at playlist time: ").concat(i," offset: ").concat(C-i," (").concat(se,"/").concat(ae,")")),f=null,m.initPTS=se,m.timescale=ae,m.trackId=oe)}f?(m.initPTS=f.baseTime,m.timescale=f.timescale,m.trackId=f.trackId):(m.timescale&&void 0!==m.trackId&&void 0!==m.initPTS||(this.warn("Could not set initPTS"),m.initPTS=C,m.timescale=1,m.trackId=-1),this.initPTS=f={baseTime:m.initPTS,timescale:m.timescale,trackId:m.trackId});var de=C-f.baseTime/f.timescale,he=de+U,fe=P&&void 0!==(null==G?void 0:G.ptsMin)?G.ptsMin/G.timescale-f.baseTime/f.timescale:de,ve=void 0!==j&&w?j/w.timescale-f.baseTime/f.timescale:P&&null!=G&&G.ptsMax?G.ptsMax/G.timescale-f.baseTime/f.timescale:he;U>0?this.lastEndTime=he:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var ge={data1:K,data2:void 0,startPTS:fe,startDTS:de,endPTS:ve,endDTS:he,type:D,hasAudio:_,hasVideo:P,nb:1,dropped:0,encrypted:!!E.audio&&E.audio.encrypted||!!E.video&&E.video.encrypted};g.audio=_&&!P?ge:void 0,g.video=P?ge:void 0;var pe=this.isVideoContiguous,ye=null==w?void 0:w.sampleCount;if(ye){var me=w.keyFrameIndex,Ee=-1!==me;ge.nb=ye,ge.dropped=0===me||pe?0:Ee?me:ye,ge.independent=Ee,ge.firstKeyFrame=me,Ee&&w.keyFrameStart&&(ge.firstKeyFramePTS=(w.keyFrameStart-f.baseTime)/f.timescale),pe||(g.independent=Ee),this.isVideoContiguous||(this.isVideoContiguous=Ee),ge.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(me,"/").concat(ye," dropped: ").concat(ge.dropped," start: ").concat(ge.firstKeyFramePTS||"NA"))}return g.initSegment=m,g.id3=gs(r,i,f,f),n.samples.length&&(g.text=ps(n,i,f)),g}}])}(Ee);function Es(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function ks(e,t,r){var n=e.codec;if(n&&n.length>4)return n;if(t===Y){if("ec-3"===n||"ac-3"===n||"alac"===n)return n;if("fLaC"===n||"Opus"===n){return Xt(n,!1)}return r.warn('Unhandled audio codec "'.concat(n,'" in mp4 MAP')),n||"mp4a"}return"mjpg"===n?n:(r.warn('Unhandled video codec "'.concat(n,'" in mp4 MAP')),n||"avc1")}try{ys=self.performance.now.bind(self.performance)}catch(Ry){ys=Date.now}var Ss=[{demux:Ma,remux:ms},{demux:Ka,remux:fs},{demux:_a,remux:fs},{demux:Oa,remux:fs}];Ss.splice(2,0,{demux:Da,remux:fs});var Ts=function(){return h(function e(t,r,n,i,a,s){c(this,e),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=t,this.typeSupported=r,this.config=n,this.id=a,this.logger=s},[{key:"configure",value:function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}},{key:"push",value:function(e,t,r,n){var i=this;if(!this.observer)return bs(r);var a=r.transmuxing;a.executeStart=ys();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;n&&(this.currentTransmuxState=n);var u=n||o,c=u.contiguous,d=u.discontinuity,h=u.trackSwitch,f=u.accurateTimeOffset,v=u.timeOffset,g=u.initSegmentChange,p=l.audioCodec,y=l.videoCodec,m=l.defaultInitPts,E=l.duration,k=l.initSegmentData,S=function(e,t){var r=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t);return r}(s,t);if(S&&Mn(S.method)){var T=this.getDecrypter(),b=Fn(S.method);return this.asyncResult=!0,this.decryptionPromise=T.decrypt(s,S.key.buffer,S.iv.buffer,b,r.decryptRange).then(function(e){var t=i.push(e,null,r);return i.decryptionPromise=null,t}),this.decryptionPromise}var A=this.needsProbing(d,h);if(A){var L=r.iframe&&k&&Ka.probe(k,this.logger)?k:s,R=this.configureTransmuxer(L);if(R)return this.logger.warn("[transmuxer] ".concat(R.message)),this.observer.emit(B.ERROR,B.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),a.executeEnd=ys(),bs(r)}(d||h||g||A)&&this.resetInitSegment(k,p,y,E,t,r),(d||g||A)&&this.resetInitialTimestamp(m),c||this.resetContiguity();var I=this.transmux(s,S,v,f,r);this.asyncResult=As(I);var w=this.currentTransmuxState;return w.contiguous=!0,w.discontinuity=!1,w.trackSwitch=!1,a.executeEnd=ys(),I}},{key:"flush",value:function(e){var t=this,r=e.transmuxing;r.executeStart=ys();var n=this.decrypter,i=this.currentTransmuxState,a=this.decryptionPromise;if(a)return this.asyncResult=!0,a.then(function(){return t.flush(e)});var s=[],o=i.timeOffset;if(n){var l=n.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,c=this.remuxer;if(!u||!c){r.executeEnd=ys();var d=[bs(e)];return this.asyncResult?Promise.resolve(d):d}var h=u.flush(o,e);return As(h)?(this.asyncResult=!0,h.then(function(r){return t.flushRemux(s,r,e),s})):(this.flushRemux(s,h,e),this.asyncResult?Promise.resolve(s):s)}},{key:"flushRemux",value:function(e,t,r){if(this.remuxer){var n=t.audioTrack,i=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed ".concat(this.id," sn: ").concat(r.sn).concat(r.part>-1?" part: "+r.part:""," of ").concat(this.id," playlist ").concat(r.level));var c=this.remuxer.remux(n,i,a,s,u,l,!0,this.id,r,t.initData,t.sampleData);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=ys()}}},{key:"resetInitialTimestamp",value:function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}},{key:"resetContiguity",value:function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}},{key:"resetInitSegment",value:function(e,t,r,n,i,a){var s=this.demuxer,o=this.remuxer;s&&o&&(s.resetInitSegment(e,t,r,n,i,a),o.resetInitSegment(e,t,r,i))}},{key:"destroy",value:function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}},{key:"transmux",value:function(e,t,r,n,i){return"SAMPLE-AES"===(null==t?void 0:t.method)?this.transmuxSampleAes(e,t,r,n,i):this.transmuxUnencrypted(e,r,n,i)}},{key:"transmuxUnencrypted",value:function(e,t,r,n){var i=this.demuxer,a=this.remuxer;if(!i||!a)return bs(n);var s=i.demux(e,t,n,!1,!this.config.progressive),o=s.audioTrack,l=s.videoTrack,u=s.id3Track,c=s.textTrack;return{remuxResult:a.remux(o,l,u,c,t,r,!1,this.id,n,s.initData,s.sampleData),chunkMeta:n}}},{key:"transmuxSampleAes",value:function(e,t,r,n,i){var a=this;return this.demuxer?this.demuxer.demuxSampleAes(e,t,r,i).then(function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,n,!1,a.id,i,e.initData,e.sampleData),chunkMeta:i}}):Promise.reject(new Error("no demuxer"))}},{key:"configureTransmuxer",value:function(e){var t=this.config,r=this.observer,n=this.typeSupported;if(r){var i;try{for(var a=0,s=Ss.length;a<s;a++){var o;if(null!=(o=Ss[a].demux)&&o.probe(e,this.logger)){i=Ss[a];break}}}catch(h){return h}if(!i)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,u=this.remuxer,c=i.demux,d=i.remux;l&&l instanceof c||(this.logger.log("Using ".concat(c.name)),this.demuxer=new c(r,t,n,this.logger),this.probe=c.probe),u&&u instanceof d||(this.logger.log("Using ".concat(d.name)),this.remuxer=new d(r,t,n,this.logger))}}},{key:"needsProbing",value:function(e,t){return!this.demuxer||!this.remuxer||e||t}},{key:"getDecrypter",value:function(){var e=this.decrypter;return e||(e=this.decrypter=new cn(this.config)),e}}])}();var bs=function(e){return{remuxResult:{},chunkMeta:e}};function As(e){return"then"in e&&e.then instanceof Function}var Ls=h(function e(t,r,n,i,a){c(this,e),this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=r,this.initSegmentData=n,this.duration=i,this.defaultInitPts=a||null}),Rs=h(function e(t,r,n,i,a,s){c(this,e),this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=r,this.accurateTimeOffset=n,this.trackSwitch=i,this.timeOffset=a,this.initSegmentChange=s}),Is=0,ws=function(){return h(function e(t,r,n,i){var a=this;c(this,e),this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Is++,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=function(e){var t=e.data,r=a.hls;if(r&&null!=t&&t.event&&t.instanceNo===a.instanceNo)switch(t.event){case"init":var n,i=null==(n=a.workerContext)?void 0:n.objectURL;i&&self.URL.revokeObjectURL(i);break;case"transmuxComplete":a.handleTransmuxComplete(t.data);break;case"flush":a.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=a.frag,t.data.part=a.part,t.data.id=a.id,r.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(a.hls){var t=new Error("".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")"));a.hls.config.enableWorker=!1,a.hls.logger.warn('Error in "'.concat(a.id,'" Web Worker, fallback to inline')),a.hls.trigger(B.ERROR,{type:N.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var s=t.config;this.hls=t,this.id=r,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=n,this.onFlush=i;var o=function(e,t){(t=t||{}).frag=a.frag||void 0,e===B.ERROR&&(t.parent=a.id,t.part=a.part,a.error=t.error),a.hls.trigger(e,t)};this.observer=new ia,this.observer.on(B.FRAG_DECRYPTED,o),this.observer.on(B.ERROR,o);var l=Zt(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var u=this.hls.logger;if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(u.log("loading Web Worker ".concat(s.workerPath,' for "').concat(r,'"')),this.workerContext=function(e){var t=sa[e];if(t)return t.clientCount++,t;var r=new self.URL(e,self.location.href).href,n={worker:new self.Worker(r),scriptURL:r,clientCount:1};return sa[e]=n,n}(s.workerPath)):(u.log('injecting Web Worker for "'.concat(r,'"')),this.workerContext=function(){var e=sa[aa];if(e)return e.clientCount++,e;var t=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(".concat(__HLS_WORKER_BUNDLE__.toString(),")(true);")],{type:"text/javascript"}),r=self.URL.createObjectURL(t),n={worker:new self.Worker(r),objectURL:r,clientCount:1};return sa[aa]=n,n}());var d=this.workerContext.worker;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:r,config:mr(s)})}catch(Ry){u.warn('Error setting up "'.concat(r,'" Web Worker, fallback to inline'),Ry),this.terminateWorker(),this.error=null,this.transmuxer=new Ts(this.observer,l,s,"",r,t.logger)}return}}this.transmuxer=new Ts(this.observer,l,s,"",r,t.logger)},[{key:"reset",value:function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=Is++;var t=this.hls.config,r=Zt(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:mr(t)})}}},{key:"terminateWorker",value:function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){var t=sa[e||aa];if(t&&1===t.clientCount--){var r=t.worker,n=t.objectURL;delete sa[e||aa],n&&self.URL.revokeObjectURL(n),r.terminate()}}(this.hls.config.workerPath)}}},{key:"destroy",value:function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}},{key:"push",value:function(e,t,r,n,i,a,s,o,l,u){var c,d,h=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,v=this.transmuxer,g=a?a.start:i.start,p=i.decryptdata,y=this.frag,m=!y||i.cc!==y.cc,E=!y||l.level!==y.level,k=y?l.sn-y.sn:-1,S=this.part?l.part-this.part.index:-1,T=0===k&&l.id>1&&l.id===(null==y?void 0:y.stats.chunkCount),b=!E&&(1===k||0===k&&(1===S||T&&S<=0)),A=self.performance.now();(E||k||0===i.stats.parsing.start)&&(i.stats.parsing.start=A),!a||!S&&b||(a.stats.parsing.start=A);var L=!(y&&(null==(c=i.initSegment)?void 0:c.url)===(null==(d=y.initSegment)?void 0:d.url)),R=new Rs(m,b,o,E,g,L);if(!b||m||L){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for ".concat(i.type," sn: ").concat(l.sn).concat(l.part>-1?" part: "+l.part:""," ").concat(this.id," playlist: ").concat(l.level," id: ").concat(l.id,"\n discontinuity: ").concat(m,"\n trackSwitch: ").concat(E,"\n contiguous: ").concat(b,"\n accurateTimeOffset: ").concat(o,"\n timeOffset: ").concat(g,"\n initSegmentChange: ").concat(L));var I=new Ls(r,n,t,s,u);this.configureTransmuxer(I)}if(this.frag=i,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(v){var w=v.push(e,p,l,R);As(w)?w.then(function(e){h.handleTransmuxComplete(e)}).catch(function(e){h.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(w)}}},{key:"flush",value:function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,n=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(n){var i=n.flush(e);As(i)?i.then(function(r){t.handleFlushResult(r,e)}).catch(function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}},{key:"transmuxerError",value:function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}},{key:"handleFlushResult",value:function(e,t){var r=this;e.forEach(function(e){r.handleTransmuxComplete(e)}),this.onFlush(t)}},{key:"configureTransmuxer",value:function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}},{key:"handleTransmuxComplete",value:function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}])}(),_s=function(e){function t(e,r,n){var i;return c(this,t),(i=u(this,t,[e,r,n,"audio-stream-controller",W.AUDIO])).mainAnchor=null,i.mainFragLoading=null,i.audioOnly=!1,i.bufferedTrack=null,i.switchingTrack=null,i.trackId=-1,i.nextTrackId=-1,i.waitingData=null,i.mainDetails=null,i.flushing=!1,i.bufferFlushed=!1,i.cachedTrackLoadedData=null,i.registerListeners(),i}return y(t,e),h(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),R(t,"onHandlerDestroying",this)([]),this.resetItem()}},{key:"resetItem",value:function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}},{key:"registerListeners",value:function(){R(t,"registerListeners",this)([]);var e=this.hls;e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(B.BUFFER_RESET,this.onBufferReset,this),e.on(B.BUFFER_CREATED,this.onBufferCreated,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(B.FRAG_LOADING,this.onFragLoading,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(R(t,"unregisterListeners",this)([]),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(B.BUFFER_RESET,this.onBufferReset,this),e.off(B.BUFFER_CREATED,this.onBufferCreated,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(B.FRAG_LOADING,this.onFragLoading,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this))}},{key:"onInitPtsFound",value:function(e,t){var r=t.frag,n=t.id,i=t.initPTS,a=t.timescale,s=t.trackId,o=t.timestampOffsets;if(n===W.MAIN){var l=r.cc,u=this.fragCurrent;if(this.initPTS=o,this.log("InitPTS for cc: ".concat(l," found from main: ").concat(i/a," (").concat(i,"/").concat(a,") trackId: ").concat(s)),this.mainAnchor=r,this.state===Xi){var c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==l)&&this.syncWithAnchor(r,null==c?void 0:c.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==l?(u.abortRequests(),this.syncWithAnchor(r,u)):this.state===Gi&&this.tick()}}},{key:"getLoadPosition",value:function(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(e=this.switchingTrack)?void 0:e.flushImmediate)?this.nextLoadPosition:R(t,"getLoadPosition",this)([])}},{key:"syncWithAnchor",value:function(e,t){var r,n=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==n?void 0:n.cc)!==t.cc){var i=(n||e).cc,a=xr(this.getLevelDetails(),i,this.getLoadPosition());a&&(this.log("Syncing with main frag at ".concat(a.start," cc ").concat(a.cc)),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===Gi&&this.doTickIdle())}}},{key:"startLoad",value:function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=Bi);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r),this.state=Gi,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}},{key:"doTick",value:function(){switch(this.state){case Gi:this.doTickIdle();break;case Vi:var e=this.levels,r=this.trackId,n=null==e?void 0:e[r],i=null==n?void 0:n.details;if(i&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(i))break;this.state=Xi}break;case Hi:this.checkRetryDate();break;case Xi:var a=this.waitingData;if(a){var s=a.frag,o=a.part,l=a.cache,u=a.complete,c=this.mainAnchor;if(void 0!==this.initPTS[s.cc]){this.waitingData=null,this.state=Ki;var d={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(d),u&&R(t,"_handleFragmentLoadComplete",this)([d])}else c&&c.cc!==a.frag.cc&&this.syncWithAnchor(c,a.frag)}else this.state=Gi}this.onTickEnd()}},{key:"resetLoadingState",value:function(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),R(t,"resetLoadingState",this)([])}},{key:"onTickEnd",value:function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}},{key:"doTickIdle",value:function(){var e,t=this.hls,r=this.levels,n=this.media,i=this.trackId,a=t.config;if(this.buffering&&(n||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[i]){var s=r[i],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=Vi,void(this.startFragRequested=!1);var l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Y));var u=this.getFwdBufferInfo();if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(B.BUFFER_EOS,{type:"audio"}),void(this.state=Yi);var c=u.len,d=t.maxBufferLength,h=o.fragments,f=h[0].start,v=this.getLoadPosition(),g=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?v:u.end;if(this.switchingTrack&&n){var p=v;o.PTSKnown&&p<f&&p>=this.timelineOffset&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track ".concat(p," -> ").concat(f," + 0.05")),n.currentTime=f+.05)}if(!(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)){var y=this.getNextFragment(g,o);if(y&&this.isLoopLoading(y,g)&&(y=this.getNextFragmentLoopLoading(y,o,u,W.MAIN,d)),y){if(!this.exceedsMaxBuffer(u,d,y)){var m=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&m&&$(y)&&!y.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(m)===Zr&&(this.mainFragLoading=m=null),m&&$(m))){if(y.start>m.end){var E=this.fragmentTracker.getFragAtPos(g,W.MAIN);E&&E.end>m.end&&(m=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(y.start>m.end)return}this.loadFragment(y,s,g)}}else this.bufferFlushed=!0}}}}},{key:"onMediaDetaching",value:function(e,r){this.bufferFlushed=this.flushing=!1,R(t,"onMediaDetaching",this)([e,r])}},{key:"onAudioTracksUpdated",value:function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map(function(e){return new gr(e)})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=!!t.url;this.trackId=t.id;var n=this.fragCurrent;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),r?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==Bi&&(this.setInterval(100),this.state=Gi,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}},{key:"onManifestLoading",value:function(){R(t,"onManifestLoading",this)([]),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details;var r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(B.AUDIO_TRACK_LOADED,r))}},{key:"onAudioTrackLoaded",value:function(e,t){var r,n=this.levels,i=t.details,a=t.id,s=t.groupId,o=t.track;if(n){var l=this.mainDetails;if(!l||i.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==Bi&&(this.state=Vi));this.cachedTrackLoadedData=null,this.log("Audio track ".concat(a,' "').concat(o.name,'" of "').concat(s,'" loaded [').concat(i.startSN,",").concat(i.endSN,"]").concat(i.lastPartSn?"[part-".concat(i.lastPartSn,"-").concat(i.lastPartIndex,"]"):"",",duration:").concat(i.totalduration));var u=n[a],c=0;if(i.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;var d;if(u.details)c=this.alignPlaylists(i,u.details,null==(d=this.levelLastLoaded)?void 0:d.details);i.alignedSliding||(Mi(l,i,this),c=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(B.AUDIO_TRACK_UPDATED,{details:i,id:a,groupId:t.groupId}),this.state!==Vi||this.waitForCdnTuneIn(i)||(this.state=Gi),this.tick()}else this.warn("Audio tracks reset while loading track ".concat(a,' "').concat(o.name,'" of "').concat(s,'"'))}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,n=e.part,i=e.payload,a=this.config,s=this.trackId,o=this.levels;if(o){var l=o[s];if(l){var u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var c=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new ws(this.hls,W.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){var v=n?n.index:-1,g=-1!==v,p=new mn(r.level,r.sn,r.stats.chunkCount,i.byteLength,v,g,r.duration);d.push(i,f,c,"",r,n,u.totalduration,!1,p,h)}else{this.log("Unknown video PTS for cc ".concat(r.cc,", waiting for video PTS before demuxing audio frag ").concat(r.sn," of [").concat(u.startSN," ,").concat(u.endSN,"],track ").concat(s)),(this.waitingData=this.waitingData||{frag:r,part:n,cache:new ea,complete:!1}).cache.push(new Uint8Array(i)),this.state!==Bi&&(this.state=Xi)}}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"_handleFragmentLoadComplete",value:function(e){this.waitingData?this.waitingData.complete=!0:R(t,"_handleFragmentLoadComplete",this)([e])}},{key:"onBufferReset",value:function(){this.mediaBuffer=null}},{key:"onBufferCreated",value:function(e,t){this.bufferFlushed=this.flushing=!1;var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}},{key:"onFragLoading",value:function(e,t){!this.audioOnly&&t.frag.type===W.MAIN&&$(t.frag)&&(this.mainFragLoading=t,this.state===Gi&&this.tick())}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,n=t.part;if(r.type===W.AUDIO)if(this.fragContextChanged(r))this.warn("Fragment ".concat(r.sn).concat(n?" p: "+n.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));else{if($(r)){var i=this.switchingTrack;i&&(this.bufferedTrack=i)}this.fragBufferedComplete(r,n),this.media&&this.tick()}else this.audioOnly||r.type!==W.MAIN||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}},{key:"getFwdBufferInfo",value:function(){var e=this.getBufferOutput();return R(t,"getFwdBufferInfo",this)([e,W.AUDIO])}},{key:"getBufferOutput",value:function(){return this.mediaBuffer?this.mediaBuffer:this.media}},{key:"checkFragmentChanged",value:function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying,r=null==e?void 0:e.level;return t&&t.level===r||(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}},{key:"onError",value:function(e,r){var n;if(r.fatal)this.state=zi;else switch(r.details){case U.FRAG_GAP:case U.FRAG_PARSING_ERROR:case U.FRAG_DECRYPT_ERROR:case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.AUDIO,r);break;case U.AUDIO_TRACK_LOAD_ERROR:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==Vi||(null==(n=r.context)?void 0:n.type)!==q.AUDIO_TRACK||(this.state=Gi);break;case U.BUFFER_APPEND_NO_PROGRESS:if("audio"!==r.parent)return;r.frag&&(r.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment ".concat(r.frag.sn," of track ").concat(r.frag.level," as a gap after ").concat(r.appendsWithoutProgress," appends without buffered range growth, to prevent loop loading")),this.fragmentTracker.addAsGap(r.frag));break;case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case U.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,R(t,"flushMainBuffer",this)([0,Number.POSITIVE_INFINITY,"audio"]));break;case U.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}}},{key:"onBufferFlushing",value:function(e,t){t.type!==z&&(this.flushing=!0)}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==z){this.flushing=!1,this.bufferFlushed=!0,this.state===Yi&&(this.state=Gi);var n=this.getBufferOutput();n&&(this.afterBufferFlushed(n,r),this.tick())}}},{key:"_handleTransmuxComplete",value:function(e){var r,n="audio",i=this.hls,a=e.remuxResult,s=e.chunkMeta,o=this.getCurrentContext(s);if(o){var l=o.frag,u=o.part,c=o.level,d=c.details,h=a.audio,f=a.text,v=a.id3,g=a.initSegment;if(this.fragContextChanged(l)||!d)return this.fragmentTracker.removeFragment(l),void(null!=g&&g.tracks&&this.resetTransmuxer());if(this.state=qi,h&&this.switchingTrack&&!this.switchingTrack.flushImmediate){var p=this.config.nextAudioTrackBufferFlushForwardOffset,y=Math.max(this.getLoadPosition()+p,l.start);R(t,"flushMainBuffer",this)([y,Number.POSITIVE_INFINITY,W.AUDIO])}if(null!=g&&g.tracks){var m=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(c,g.tracks,m,s),i.trigger(B.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:n,tracks:g.tracks})}if(h){var E=h.startPTS,k=h.endPTS,S=h.startDTS,T=h.endDTS;u&&(u.elementaryStreams[Y]={startPTS:E,endPTS:k,startDTS:S,endDTS:T}),l.setElementaryStreamInfo(Y,E,k,S,T),this.bufferFragmentData(h,l,u,s)}if(null!=v&&null!=(r=v.samples)&&r.length){var b=ie({id:n,frag:l,details:d},v);i.trigger(B.FRAG_PARSING_METADATA,b)}if(f){var A=ie({id:n,frag:l,details:d},f);i.trigger(B.FRAG_PARSING_USERDATA,A)}}else this.resetWhenMissingContext(s)}},{key:"_bufferInitSegment",value:function(e,t,r,n){if(this.state===qi&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var i=t.audio;i.id=W.AUDIO;var a=e.audioCodec;this.log("Init audio buffer, container:".concat(i.container,", codecs[level/parsed]=[").concat(a,"/").concat(i.codec,"]")),1===(null==a?void 0:a.split(",").length)&&(i.levelCodec=a),this.hls.trigger(B.BUFFER_CODECS,t);var s=i.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:n,parent:r.type,data:s};this.hls.trigger(B.BUFFER_APPENDING,o)}this.tickImmediate()}}},{key:"loadFragment",value:function(e,r,n){var i,a=this.fragmentTracker.getState(e);if(this.switchingTrack||a===Qr||a===Jr)if(null!=(i=r.details)&&i.live&&!this.initPTS[e.cc]){this.log("Waiting for video PTS in continuity counter ".concat(e.cc," of live stream before loading audio fragment ").concat(e.sn," of level ").concat(this.trackId)),this.state=Xi;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&Mi(s,r.details,this)}else R(t,"loadFragment",this)([e,r,n]);else this.clearTrackerIfNeeded(e)}},{key:"flushAudioIfNeeded",value:function(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){var r=this.bufferedTrack;br({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},e,Ar)||(Rr(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),R(t,"flushMainBuffer",this)([0,Number.POSITIVE_INFINITY,"audio"]),this.bufferedTrack=null):this.bufferedTrack=e)}}},{key:"completeAudioSwitch",value:function(e){var t=this.hls;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(B.AUDIO_TRACK_SWITCHED,se({},e))}},{key:"nextAudioTrack",get:function(){return this.nextTrackId}}])}($i),Ps=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,[r,e.logger])).hls=void 0,n.canLoad=!1,n.timer=-1,n.loadingSync=!1,n.hls=e,n}return y(t,e),h(t,[{key:"destroy",value:function(){this.clearTimer(),this.hls=null}},{key:"clearTimer",value:function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}},{key:"startLoad",value:function(){this.canLoad=!0,this.loadPlaylist()}},{key:"stopLoad",value:function(){this.canLoad=!1,this.clearTimer()}},{key:"switchParams",value:function(e,t,r){var n=null==t?void 0:t.renditionReports;if(n){for(var i=-1,a=0;a<n.length;a++){var s=n[a],o=void 0;try{o=new self.URL(s.URI,t.url).href}catch(f){this.warn("Could not construct new URL for Rendition Report: ".concat(f)),o=s.URI||""}if(o===e){i=a;break}o===e.substring(0,o.length)&&(i=a)}if(-1!==i){var l=n[i],u=parseInt(l["LAST-MSN"])||t.lastPartSn,c=parseInt(l["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){var d=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&d>t.partTarget&&(c+=1)}var h=r&&fr(r);return new vr(u,c>=0?c:void 0,h)}}}},{key:"loadPlaylist",value:function(e){this.clearTimer()}},{key:"loadingPlaylist",value:function(e,t){this.clearTimer()}},{key:"shouldLoadPlaylist",value:function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}},{key:"getUrlWithDirectives",value:function(e,t){if(t)try{return t.addDirectives(e)}catch(r){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(r))}return e}},{key:"playlistLoaded",value:function(e,t,r){var n=t.details,i=t.stats,a=n.fragments,s=self.performance.now(),o=i.loading.first?Math.max(0,Math.floor(s-i.loading.first)):0;n.advancedDateTime=Date.now()-o;var l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){var u=Math.max(l||0,0);n.appliedTimelineOffset=u,a.forEach(function(e){null==e||e.setStart(e.playlistOffset+u)})}if(n.live||null!=r&&r.live){var c,d="levelInfo"in t?t.levelInfo:t.track;n.reloaded(r);var h=null==(c=a[a.length-1])?void 0:c.type;if(n.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){var f=new Error("".concat(h," playlist ").concat(d.id," hit max allowed unchanged reloads."));this.warn(f);var v=t.networkDetails,g=t.context;return void this.hls.trigger(B.ERROR,{type:N.NETWORK_ERROR,details:U.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:n.url,error:f,reason:f.message,level:t.level,parent:h,context:g,networkDetails:v,stats:i})}if(r){Ti(r,n,this);var p=n.playlistParsingError;if(p){this.warn(p);var y=this.hls;if(!y.config.ignorePlaylistParsingErrors){var m=t.networkDetails;return void y.trigger(B.ERROR,{type:N.NETWORK_ERROR,details:U.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:p,reason:p.message,level:t.level,parent:h,networkDetails:m,stats:i})}n.playlistParsingError=null}}-1===n.requestScheduled&&(n.requestScheduled=i.loading.start);var E=this.hls.mainForwardBufferInfo,k=E?E.end-E.len:0,S=Li(n,1e3*(n.edge-k));n.requestScheduled+S<s?n.requestScheduled=s:n.requestScheduled<=s&&(n.requestScheduled+=S);var T,b=t.deliveryDirectives;if(this.log("live playlist ".concat(e," ").concat(n.advanced?"REFRESHED ".concat(n.lastPartSn," - ").concat(n.lastPartIndex):n.updated?"UPDATED":"MISSED (received ".concat(n.lastPartSn," - ").concat(n.lastPartIndex).concat(b?" | requested ".concat(b.msn," - ").concat(b.part):"",")"))),!this.canLoad||!n.live)return;var A=void 0,L=void 0;if(n.canBlockReload&&n.advanced){var R=this.hls.config.lowLatencyMode,I=n.lastPartSn,w=n.endSN,_=n.lastPartIndex,P=I===w;-1!==_?P?(A=w+1,L=R?0:_):(A=I,L=R?_+1:n.maxPartIndex):A=w+1;var D=n.age,C=D+n.ageHeader,O=Math.min(C-n.partTarget,1.5*n.targetduration);if(O>0){if(C>3*n.targetduration)this.log("Playlist last advanced ".concat(D.toFixed(2),"s ago. Omitting segment and part directives.")),A=void 0,L=void 0;else if(null!=r&&r.tuneInGoal&&C-n.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(r.tuneInGoal," to: ").concat(O," with playlist age: ").concat(n.age)),O=0;else{var x=Math.floor(O/n.targetduration);if(A+=x,void 0!==L)L+=Math.round(O%n.targetduration/n.partTarget);this.log("CDN Tune-in age: ".concat(n.ageHeader,"s last advanced ").concat(D.toFixed(2),"s goal: ").concat(O," skip sn ").concat(x," to part ").concat(L))}n.tuneInGoal=O}if(T=this.getDeliveryDirectives(n,t.deliveryDirectives,A,L),R||!P)return n.requestScheduled=s,void this.loadingPlaylist(d,T)}else(n.canBlockReload||n.canSkipUntil)&&(T=this.getDeliveryDirectives(n,t.deliveryDirectives,A,L));T&&void 0!==A&&n.canBlockReload&&(n.requestScheduled=i.loading.first+Math.max(S-2*o,S/2)),this.scheduleLoading(d,T,n)}else this.clearTimer()}},{key:"scheduleLoading",value:function(e,t,r){var n=this,i=r||e.details;if(i){var a=self.performance.now(),s=i.requestScheduled;if(a>=s&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(e,t),void(this.loadingSync=!1);var o=Math.max(s-a,0);this.log("reload live playlist ".concat(e.name||e.bitrate+"bps"," in ").concat(Math.round(o)," ms")),this.clearTimer(),this.timer=self.setTimeout(function(){return n.loadingPlaylist(e,t)},o)}else this.loadingPlaylist(e,t)}},{key:"getDeliveryDirectives",value:function(e,t,r,n){var i=fr(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,i=cr),new vr(r,n,i)}},{key:"checkRetry",value:function(e){var t=this,r=e.details,n=le(e),i=e.errorAction,a=i||{},s=a.action,o=a.retryCount,l=void 0===o?0:o,u=a.retryConfig,c=!!i&&!!u&&(s===Br||!i.resolved&&s===Nr);if(c){var d;if(l>=u.maxNumRetry)return!1;if(n&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" without delivery-directives')),this.loadPlaylist();else{var h,f=ge(null==(h=e.response)?void 0:h.code);if(this.clearTimer(),f)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(function(){return t.checkOfflineStatus()},1e3);else{var v=he(u,l);this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" in ').concat(v,"ms")),this.timer=self.setTimeout(function(){return t.loadPlaylist()},v)}}e.levelRetry=!0,i.resolved=!0}return c}},{key:"checkOfflineStatus",value:function(){var e=this;this.clearTimer(),ge(0)?this.timer=self.setTimeout(function(){return e.checkOfflineStatus()},1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}])}(Ee);function Ds(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!Cs(e[r].attrs,t[r].attrs))return!1;return!0}function Cs(e,t,r){var n=e["STABLE-RENDITION-ID"];return n&&!r?n===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(function(r){return e[r]!==t[r]})}var Os=function(e){function t(e){var r;return c(this,t),(r=u(this,t,[e,"audio-track-controller"])).tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.registerListeners(),r}return y(t,e),h(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(B.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVEL_LOADING,this.onLevelLoading,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(B.ERROR,this.onError,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,R(t,"destroy",this)([])}},{key:"onManifestLoading",value:function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.audioTracks||[]}},{key:"onAudioTrackLoaded",value:function(e,t){var r=t.id,n=t.groupId,i=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===n){var s=a.details;a.details=t.details,this.log("Audio track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(n," loaded [").concat(i.startSN,"-").concat(i.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Audio track with id:".concat(r," and group:").concat(n," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this.hls.levels[e];if(t){var r=t.audioGroups||null,n=this.groupIds,i=this.currentTrack;if(!r||(null==n?void 0:n.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==n?void 0:n.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return Ir(e.groupId,r)});if(a.length)this.selectDefaultTrack&&!a.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),a.forEach(function(e,t){e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.audioPreference;if(!i&&s){var o=Tr(s,a,Ar);if(o>-1)i=a[o];else{var l=Tr(s,this.tracks);i=this.tracks[l]}}var u=this.findTrackId(i);-1===u&&i&&(u=this.findTrackId(null));var c={audioTracks:a};this.log("Updating audio tracks, ".concat(a.length," track(s) found in group(s): ").concat(null==r?void 0:r.join(","))),this.hls.trigger(B.AUDIO_TRACKS_UPDATED,c);var d=this.trackId;if(-1!==u&&-1===d)this.setAudioTrack(u);else if(a.length&&-1===d){var h,f=new Error("No audio track selected for current audio group-ID(s): ".concat(null==(h=this.groupIds)?void 0:h.join(",")," track count: ").concat(a.length));this.warn(f.message),this.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===q.AUDIO_TRACK&&t.context.id===this.trackId&&Ir(t.context.groupId,this.groupIds)&&this.checkRetry(t)}},{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}},{key:"nextAudioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}},{key:"setAudioOption",value:function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var n=this.currentTrack;if(n&&br(e,n,Ar))return n;var i=Tr(e,this.tracksInGroup,Ar);if(i>-1){var a=this.tracksInGroup[i];return this.setAudioTrack(i,"flushImmediate"in e&&e.flushImmediate),a}if(n){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,r,n,i){var a=t[n],s=t.reduce(function(e,t,r){var n=t.uri;return(e[n]||(e[n]=[])).push(r),e},{}),o=s[a.uri];o.length>1&&(n=Math.max.apply(Math,o));var l=a.videoRange,u=a.frameRate,c=a.codecSet.substring(0,4),d=Lr(t,n,function(t){if(t.videoRange!==l||t.frameRate!==u||t.codecSet.substring(0,4)!==c)return!1;var n=t.audioGroups,a=r.filter(function(e){return Ir(e.groupId,n)});return Tr(e,a,i)>-1});return d>-1?d:Lr(t,n,function(t){var n=t.audioGroups,a=r.filter(function(e){return Ir(e.groupId,n)});return Tr(e,a,i)>-1})}(e,t.levels,r,s,Ar);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=Tr(e,r);if(l>-1)return r[l]}}}return null}},{key:"setAudioTrack",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this.tracksInGroup;if(e<0||e>=r.length)this.warn("Invalid audio track id: ".concat(e));else{this.selectDefaultTrack=!1;var n=this.currentTrack,i=r[e],a=i.details&&!i.details.live;if(!(e===this.trackId&&i===n&&a||(this.log("Switching to audio-track ".concat(e,' "').concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId," channels:").concat(i.channels)),this.trackId=e,this.currentTrack=i,this.hls.trigger(B.AUDIO_TRACK_SWITCHING,se(se({},i),{},{flushImmediate:t})),a))){var s=this.switchParams(i.url,null==n?void 0:n.details,i.details);this.loadPlaylist(s)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var n=t[r];if((!this.selectDefaultTrack||n.default)&&(!e||br(e,n,Ar)))return r}if(e){for(var i=e.name,a=e.lang,s=e.assocLang,o=e.characteristics,l=e.audioCodec,u=e.channels,c=0;c<t.length;c++){if(br({name:i,lang:a,assocLang:s,characteristics:o,audioCodec:l,channels:u},t[c],Ar))return c}for(var d=0;d<t.length;d++){var h=t[d];if(Cs(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var v=t[f];if(Cs(e.attrs,v.attrs,["LANGUAGE"]))return f}}return-1}},{key:"loadPlaylist",value:function(e){R(t,"loadPlaylist",this)([]);var r=this.currentTrack;this.shouldLoadPlaylist(r)&&Rr(r.url,this.hls)&&this.scheduleLoading(r,e)}},{key:"loadingPlaylist",value:function(e,r){R(t,"loadingPlaylist",this)([e,r]);var n=e.id,i=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading audio-track ".concat(n,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(i).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(B.AUDIO_TRACK_LOADING,{url:a,id:n,groupId:i,deliveryDirectives:r||null,track:e})}}])}(Ps),xs=function(){return h(function e(t){c(this,e),this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t},[{key:"destroy",value:function(){this.tracks=this.queues=null}},{key:"append",value:function(e,t,r){if(null!==this.queues&&null!==this.tracks){var n=this.queues[t];n.push(e),1!==n.length||r||this.executeNext(t)}}},{key:"appendBlocker",value:function(e){var t=this;return new Promise(function(r){var n={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(n,e)})}},{key:"prependBlocker",value:function(e){var t=this;return new Promise(function(r){if(t.queues){var n={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(n)}})}},{key:"removeBlockers",value:function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"===r||"async-blocker-prepend"===r?(e[0].execute(),e.splice(0,1)):"block-audio"===r&&e.splice(0,1)})}},{key:"insertNext",value:function(e,t){var r;null!==this.queues&&(r=this.queues[t]).splice.apply(r,[1,0].concat(I(e)))}},{key:"unblockAudio",value:function(){var e;null!==this.queues&&"block-audio"===(null==(e=this.current("audio"))?void 0:e.label)&&this.shiftAndExecuteNext("audio")}},{key:"audioBlocking",value:function(){return null!==this.queues&&this.queues.audio.some(function(e){return"block-audio"===e.label})}},{key:"executeNext",value:function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(a){var n;if(r.onError(a),null===this.queues||null===this.tracks)return;var i=null==(n=this.tracks[e])?void 0:n.buffer;null!=i&&i.updating||this.shiftAndExecuteNext(e)}}}}},{key:"shiftAndExecuteNext",value:function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}},{key:"current",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}},{key:"toString",value:function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n".concat(this.list("video"),"\n").concat(this.list("audio"),"\n").concat(this.list("audiovideo"),"}")}},{key:"list",value:function(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?"".concat(e,": (").concat(this.listSbInfo(e),") ").concat(this.listOps(e)):""}},{key:"listSbInfo",value:function(e){var t,r=null==(t=this.tracks)?void 0:t[e],n=null==r?void 0:r.buffer;return n?"SourceBuffer".concat(n.updating?" updating":"").concat(r.ended?" ended":"").concat(r.ending?" ending":""):"none"}},{key:"listOps",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e].map(function(e){return e.label}).join(", "))||""}}])}(),Ms=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Fs="HlsJsTrackRemovedError",Ns=function(e){function t(e){var r;return c(this,t),(r=u(this,t,[e])).name=Fs,r}return y(t,e),h(t)}(O(Error)),Us=function(e){function t(e,r){var n,i;return c(this,t),(n=u(this,t,["buffer-controller",e.logger])).hls=void 0,n.fragmentTracker=void 0,n.fragmentAppendProgress=Object.create(null),n.appendsWithoutProgress=Object.create(null),n.details=null,n._objectUrl=null,n.operationQueue=null,n.bufferCodecEventsTotal=0,n.media=null,n.mediaSource=null,n.lastMpegAudioChunk=null,n.lastVideoAppendEnd=0,n.appendSource=void 0,n.transferData=void 0,n.overrides=void 0,n.appendErrors={audio:0,video:0,audiovideo:0},n.appendError=void 0,n._quotaEvictionPending={},n.tracks={},n.sourceBuffers=[[null,null],[null,null]],n._onEndStreaming=function(e){var t;n.hls&&"open"===(null==(t=n.mediaSource)?void 0:t.readyState)&&n.media&&!n.media.seeking&&n.hls.pauseBuffering()},n._onStartStreaming=function(e){n.hls&&n.hls.resumeBuffering()},n._onMediaSourceOpen=function(e){var t=n,r=t.media,i=t.mediaSource;e&&n.log("Media source opened"),r&&i&&(Ni(i,"sourceopen",n._onMediaSourceOpen),Ni(r,"emptied",n._onMediaEmptied),n.updateDuration(),n.hls.trigger(B.MEDIA_ATTACHED,{media:r,mediaSource:i}),null!==n.mediaSource&&n.checkPendingTracks())},n._onMediaSourceClose=function(){if(n.log("Media source closed"),n.media){var e=n.media.error,t=n,r=t.appendError,i=t.appendErrors,a=!1;if(!r&&e)a=Math.max(++i.audio,++i.video,++i.audiovideo)>=n.hls.config.appendErrorMaxRetry;var s=new Error("MediaSource closed while media attached".concat(js(a,e)));n.warn(s),n.hls.trigger(B.ERROR,ie({fatal:a},r,{type:N.MEDIA_ERROR,details:U.MEDIA_SOURCE_REQUIRES_RESET,error:s}))}},n._onMediaSourceEnded=function(){n.log("Media source ended")},n._onMediaEmptied=function(){var e=n,t=e.mediaSrc,r=e._objectUrl;t!==r&&n.error("Media element src was set while attaching MediaSource (".concat(r," > ").concat(t,")"))},n._onMediaError=function(){var e,t,r=n.media;r&&n.log("Media error (code: ".concat(null==(e=r.error)?void 0:e.code,"): ").concat(null==(t=r.error)?void 0:t.message))},n.hls=e,n.fragmentTracker=r,n.appendSource=(i=Re(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),n.initTracks(),n.registerListeners(),n}return y(t,e),h(t,[{key:"hasSourceTypes",value:function(){return Object.keys(this.tracks).length>0}},{key:"destroy",value:function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}},{key:"registerListeners",value:function(){var e=this.hls;e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.BUFFER_RESET,this.onBufferReset,this),e.on(B.BUFFER_APPENDING,this.onBufferAppending,this),e.on(B.BUFFER_CODECS,this.onBufferCodecs,this),e.on(B.BUFFER_EOS,this.onBufferEos,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.FRAG_PARSED,this.onFragParsed,this),e.on(B.FRAG_CHANGED,this.onFragChanged,this),e.on(B.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.BUFFER_RESET,this.onBufferReset,this),e.off(B.BUFFER_APPENDING,this.onBufferAppending,this),e.off(B.BUFFER_CODECS,this.onBufferCodecs,this),e.off(B.BUFFER_EOS,this.onBufferEos,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.FRAG_PARSED,this.onFragParsed,this),e.off(B.FRAG_CHANGED,this.onFragChanged,this),e.off(B.ERROR,this.onError,this)}},{key:"transferMedia",value:function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var n={};if(this.operationQueue){var i=this.isUpdating();i||this.operationQueue.removeBlockers();var a=this.isQueued();(i||a)&&this.warn("Transfering MediaSource with".concat(a?" operations in queue":"").concat(i?" updating SourceBuffer(s)":""," ").concat(this.operationQueue)),this.operationQueue.destroy()}var s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===r?ie(n,s.tracks):this.sourceBuffers.forEach(function(t){var r=L(t,1)[0];r&&(n[r]=ie({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null}),{media:t,mediaSource:r,tracks:n}}},{key:"initTracks",value:function(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}},{key:"onManifestLoading",value:function(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}},{key:"onManifestParsed",value:function(e,t){var r,n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log("".concat(n," bufferCodec event(s) expected.")),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var n=Re(this.appendSource);if(n){var i=!!t.mediaSource;(i||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(a),i)this._objectUrl=r.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,Bs(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(l){r.src=s}else r.src=s}Fi(r,"emptied",this._onMediaEmptied),Fi(r,"error",this._onMediaError),this.appendSource&&Fi(r,"seeking",this._onStartStreaming)}}},{key:"assignMediaSource",value:function(e){var t,r;this.log("".concat((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat(null==(r=e.constructor)?void 0:r.name)),Fi(e,"sourceopen",this._onMediaSourceOpen),Fi(e,"sourceended",this._onMediaSourceEnded),Fi(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Fi(e,"startstreaming",this._onStartStreaming),Fi(e,"endstreaming",this._onEndStreaming))}},{key:"attachTransferred",value:function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var n=this.tracks,i=r.tracks,a=i?Object.keys(i):null,s=a?a.length:0,o=function(){Promise.resolve().then(function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()})};if(i&&a&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal ".concat(this.bufferCodecEventsTotal,")\nrequired tracks: ").concat(mr(n,function(e,t){return"initSegment"===e?void 0:t}),";\ntransfer tracks: ").concat(mr(i,function(e,t){return"initSegment"===e?void 0:t}),"}")),!Ie(i,n)){r.mediaSource=null,r.tracks=void 0;var l=t.currentTime,u=this.details,c=Math.max(l,(null==u?void 0:u.fragments[0].start)||0);return c-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time ".concat(l," -> ").concat(c)):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'.concat(Object.keys(i),'"->"').concat(Object.keys(n),'") start time: ').concat(c," currentTime: ").concat(l)),this.onMediaDetaching(B.MEDIA_DETACHING,{}),this.onMediaAttaching(B.MEDIA_ATTACHING,r),void(t.currentTime=c))}this.transferData=void 0,a.forEach(function(t){var r=t,n=i[r];if(n){var a=n.buffer;if(a){var s=e.fragmentTracker,o=n.id;if(s.hasFragments(o)||s.hasParts(o)){var l=kn.getBuffered(a);s.detectEvictedFragments(r,l,o,null,null,!0)}var u=Gs(r),c=[r,a];e.sourceBuffers[u]=c,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,n)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}}},{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"onMediaDetaching",value:function(e,t){var r=this,n=!!t.transferMedia;this.transferData=this.overrides=void 0;var i=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source ".concat(n?"transferring":"detaching")),n)this.sourceBuffers.forEach(function(e){var t=L(e,1)[0];t&&r.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===a.readyState;try{for(var l=a.sourceBuffers,u=l.length;u--;)o&&l[u].abort(),a.removeSourceBuffer(l[u]);o&&a.endOfStream()}catch(Ry){this.warn("onMediaDetaching: ".concat(Ry.message," while calling endOfStream"))}}this.sourceBufferCount&&this.onBufferReset()}Ni(a,"sourceopen",this._onMediaSourceOpen),Ni(a,"sourceended",this._onMediaSourceEnded),Ni(a,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Ni(a,"startstreaming",this._onStartStreaming),Ni(a,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(Ni(i,"emptied",this._onMediaEmptied),Ni(i,"error",this._onMediaError),Ni(i,"seeking",this._onStartStreaming),n||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(i.removeAttribute("src"),this.appendSource&&Bs(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}},{key:"onBufferReset",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=L(t,1)[0];r&&e.resetBuffer(r)}),this.initTracks()}},{key:"resetBuffer",value:function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var n;null!=(n=this.mediaSource)&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(Ry){this.warn("onBufferReset ".concat(e),Ry)}delete this.tracks[e]}},{key:"removeBuffer",value:function(e){this.removeBufferListeners(e),this.sourceBuffers[Gs(e)]=[null,null];var t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}},{key:"resetQueue",value:function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new xs(this.tracks)}},{key:"onBufferCodecs",value:function(e,t){var r,n=this,i=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'.concat(a,'" (current SB count ').concat(this.sourceBufferCount,")"));var s="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some(function(e){return!i[e]});s||o?this.warn('Unsupported transition between "'.concat(Object.keys(i),'" and "').concat(a,'" SourceBuffers')):(a.forEach(function(e){var r,a,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,c=s.container,d=s.metadata,h=s.supplemental,f=i[e],v=null==(r=n.transferData)||null==(r=r.tracks)?void 0:r[e],g=null!=v&&v.buffer?v:f,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),y=null==g?void 0:g.levelCodec;f||(f=i[e]={buffer:void 0,listeners:[],codec:l,supplemental:h,container:c,levelCodec:u,metadata:d,id:o});var m=Qt(p,y),E=null==m?void 0:m.replace(Ms,"$1"),k=Qt(l,u),S=null==(a=k)?void 0:a.replace(Ms,"$1");k&&m&&E!==S&&("audio"===e.slice(0,5)&&(k=Xt(k,n.appendSource)),n.log("switching codec ".concat(p," to ").concat(k)),k!==(f.pendingCodec||f.codec)&&(f.pendingCodec=k),f.container=c,n.appendChangeType(e,c,k))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){var n=e.tracks[r];return t[r]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},t},{})}},{key:"appendChangeType",value:function(e,t,r){var n=this,i="".concat(t,";codecs=").concat(r),a={label:"change-type=".concat(i),execute:function(){var a=n.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(n.log("changing ".concat(e," sourceBuffer type to ").concat(i)),s.changeType(i),a.codec=r,a.container=t)}n.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){n.warn("Failed to change ".concat(e," SourceBuffer type"),t)}};this.append(a,e,this.isPending(this.tracks[e]))}},{key:"blockAudio",value:function(e){var t,r=this,n=e.start,i=n+.05*e.duration;if(!(!0===(null==(t=this.fragmentTracker.getAppendedFrag(n,W.MAIN))?void 0:t.gap))){var a={label:"block-audio",execute:function(){var e,t;(r.lastVideoAppendEnd>i||kn.isBuffered(null==(e=r.tracks.video)?void 0:e.buffer,i)||!0===(null==(t=r.fragmentTracker.getAppendedFrag(i,W.MAIN))?void 0:t.gap))&&r.unblockAudio()},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.append(a,"audio",!0)}}},{key:"unblockAudio",value:function(){this.operationQueue&&this.operationQueue.unblockAudio()}},{key:"onBufferAppending",value:function(e,t){var r=this,n=this.tracks,i=t.data,a=t.type,s=t.parent,o=t.frag,l=t.part,u=t.chunkMeta,c=t.offset,d=u.buffering[a],h=$(o)&&!l&&!o.gap&&!u.partial&&!u.iframe,f=null,v=!1,g=o.sn,p=o.cc,y=self.performance.now();d.start=y;var m=o.stats.buffering,E=l?l.stats.buffering:null;0===m.start&&(m.start=y),0===(null==E?void 0:E.start)&&(E.start=y);var k=n.audio,S=!1;"audio"===a&&"audio/mpeg"===(null==k?void 0:k.container)&&(S=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var T=n.video,b=null==T?void 0:T.buffer;if(b&&"initSegment"!==g&&void 0!==c){var A=null==k?void 0:k.buffer,R=l||o;if("audio"===a&&"main"!==s&&!T.ending&&!T.ended&&A&&kn.getBuffered(A).length){var I=R.start+.05*R.duration,w=kn.getBuffered(b),_=this.currentOp("video");w.length||_?!kn.isBuffered(b,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(R):this.blockAudio(R)}else if("video"===a){var P=R.end,D=this.lastVideoAppendEnd-P;this.lastVideoAppendEnd=P,D<0||D>R.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}var C=(l||o).start,O={label:"append-".concat(a),execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=r.tracks[a])?void 0:e.buffer;t&&(h&&(f=kn.timeRangesToArray(kn.getBuffered(t)),v=Vs(Hs(f,o),o)),S?r.updateTimestampOffset(t,C,.1,a,g,p):void 0!==c&&x(c)&&r.updateTimestampOffset(t,c,1e-6,a,g,p)),r.appendExecutor(i,a)},onStart:function(){},onComplete:function(){r.clearBufferAppendTimeoutId(r.tracks[a]);var e=self.performance.now();d.executeEnd=d.end=e,0===m.first&&(m.first=e),0===(null==E?void 0:E.first)&&(E.first=e);var t={};if(r.sourceBuffers.forEach(function(e){var r=L(e,2),n=r[0],i=r[1];n&&(t[n]=kn.getBuffered(i))}),h){var n=r.getFragmentAppendProgress(o),i=t[a];if(i&&f){var c=Hs(kn.timeRangesToArray(i),o);n.progressed||(n.progressed=c-Hs(f,o)>.001);var g=v&&Vs(c,o);n.fullyBuffered[a]=(void 0===n.fullyBuffered[a]||n.fullyBuffered[a])&&g}}r.hls.trigger(B.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:s,timeRanges:t})},onError:function(e){var t;r.clearBufferAppendTimeoutId(r.tracks[a]);var n=e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e;if(n&&!r._quotaEvictionPending[a]){var c=r.getBackBufferEvictionTarget(a,i.byteLength,o.type);if(c>0){r._quotaEvictionPending[a]=!0,r.log('QuotaExceededError on "'.concat(a,'" append sn: ').concat(g," - evicting back buffer to ").concat(c.toFixed(3),"s and retrying"));var d=r.getFlushOp(a,0,c),f=r.getClearEvictionPendingOp(a);return void r.insertNext([d,O,f],a)}r.warn('QuotaExceededError on "'.concat(a,'" sn: ').concat(g," - no back buffer available to evict"))}h&&(r.getFragmentAppendProgress(o).errored=!0);var v={type:N.MEDIA_ERROR,parent:s,details:U.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:u,error:e,err:e,fatal:!1},p=null==(t=r.media)?void 0:t.error;if(e.name!==Fs||0!==r.sourceBufferCount||r.media&&0!==r.pendingTrackCount){var y;n&&(v.details=U.BUFFER_FULL_ERROR);var m=++r.appendErrors[a],E=r.hls.config.appendErrorMaxRetry;r.warn("Failed ".concat(m,"/").concat(E+1,' times to append segment in "').concat(a,'" sourceBuffer with error: ').concat(e.message)),m>=E&&(v.fatal=!n);var k=null==(y=r.mediaSource)?void 0:y.readyState;("ended"===k||"closed"===k||p)&&(r.warn('MediaSource readyState "'.concat(k,'" during SourceBuffer').concat(js(v.fatal,p))),v.details=U.MEDIA_SOURCE_REQUIRES_RESET)}else v.errorAction=Xr(!0);r.appendError=v,r.hls.trigger(B.ERROR,v),n&&r.hls&&r.trimBuffers(o.start,1)}};this.log('queuing "'.concat(a,'" append sn: ').concat(g).concat(l?" p: "+l.index:""," of ").concat(s," playlist ").concat(o.level," cc: ").concat(p," offset: ").concat(c," bytes: ").concat(i.byteLength)),this.append(O,a,this.isPending(this.tracks[a]))}},{key:"getClearEvictionPendingOp",value:function(e){var t=this;return{label:"clear",execute:function(){t._quotaEvictionPending[e]=!1,t.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(){}}}},{key:"getFlushOp",value:function(e,t,r){var n=this;return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(r)),{label:"remove",execute:function(){n.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){var i,a=null==(i=n.tracks[e])?void 0:i.buffer;n.log("Remove request ".concat(t,"-").concat(r," from ").concat(e," Source Buffer complete > buffer: ").concat(a?Ui(kn.getBuffered(a)):"(detached)")),n.hls.trigger(B.BUFFER_FLUSHED,{type:e,start:t,end:r})},onError:function(i){n.warn("Failed to remove ".concat(t,"-").concat(r,' from "').concat(e,'" SourceBuffer'),i),n.hls.trigger(B.BUFFER_FLUSHED,{type:e,start:0,end:0,error:i})}}}},{key:"onBufferFlushing",value:function(e,t){var r=this,n=t.type,i=t.startOffset,a=t.endOffset;n&&"audio"!==n||this.unblockAudio(),n?this.append(this.getFlushOp(n,i,a),n):this.sourceBuffers.forEach(function(e){var t=L(e,1)[0];t&&r.append(r.getFlushOp(t,i,a),t)})}},{key:"onFragParsed",value:function(e,t){var r=this,n=t.frag,i=t.part,a=t.chunkMeta,s=[],o=i?i.elementaryStreams:n.elementaryStreams;o[X]?s.push("audiovideo"):(o[Y]&&s.push("audio"),o[z]&&s.push("video"));0===s.length&&this.log("Fragments must have at least one ElementaryStreamType set. ".concat(n.type," ").concat(n.level," ").concat(i?"part: ".concat(i.index," of "):"","sn: ").concat(n.sn)),this.blockBuffers(function(){var e=self.performance.now();n.stats.buffering.end=e,i&&(i.stats.buffering.end=e);var t=i?i.stats:n.stats;r.checkAppendProgress(n,i,a,s),r.hls&&(r.hls.trigger(B.FRAG_BUFFERED,{frag:n,part:i,stats:t,id:n.type,chunkMeta:a}),!i&&n.gap&&t.retry&&r.log("Nothing buffered for ".concat(n.type," level: ").concat(n.level," sn: ").concat(n.sn," retries ").concat(t.retry)))},s).catch(function(e){r.warn("Fragment buffered callback ".concat(e.message)),r.stepOperationQueue(r.sourceBufferTypes)})}},{key:"onFragChanged",value:function(e,t){var r,n,i=this,a=null==(r=this.hls)?void 0:r.config;if(a){var s=a.backBufferLength,o=a.frontBufferFlushThreshold;this.trimBuffers(o,s,t.frag,t.previousFrag);var l=t.frag.elementaryStreams,u=this.appendErrors,c=null==(n=this.appendError)?void 0:n.sourceBufferName;Object.keys(l).forEach(function(e){l[e]&&(u[e]=0,e===c&&(i.appendError=void 0),"audio"===e||"video"===e?(u.audiovideo=0,"audiovideo"===c&&(i.appendError=void 0)):(u.audio=0,u.video=0,"audiovideo"!==c&&(i.appendError=void 0)))})}}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some(function(t){var r=L(t,1)[0];if(r){var n=e.tracks[r];if(n)return!n.ended||n.ending}return!1})}},{key:"onBufferEos",value:function(e,t){var r,n=this;this.sourceBuffers.forEach(function(e){var r=L(e,1)[0];if(r){var i=n.tracks[r];t.type&&t.type!==r||(i.ending=!0,i.ended||(i.ended=!0,n.log("".concat(r," buffer reached EOS"))))}});var i=!1!==(null==(r=this.overrides)?void 0:r.endOfStream),a=this.sourceBufferCount>0&&!this.sourceBuffers.some(function(e){var t,r=L(e,1)[0];return r&&!(null!=(t=n.tracks[r])&&t.ended)});a?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(function(){n.tracksEnded();var e=n.mediaSource;"open"===(null==e?void 0:e.readyState)?(n.log("Calling mediaSource.endOfStream()"),e.endOfStream(),n.hls.trigger(B.BUFFERED_TO_END,void 0)):e&&n.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(e.readyState))})):(this.tracksEnded(),this.hls.trigger(B.BUFFERED_TO_END,void 0))):"video"===t.type&&this.unblockAudio()}},{key:"tracksEnded",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=L(t,1)[0];if(null!==r){var n=e.tracks[r];n&&(n.ending=!1)}})}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())}},{key:"updateDuration",value:function(){var e=this;this.blockUntilOpen(function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)})}},{key:"onError",value:function(e,t){if(t.details===U.BUFFER_APPEND_ERROR&&t.frag){var r,n=null==(r=t.errorAction)?void 0:r.nextAutoLevel;x(n)&&n!==t.frag.level&&this.resetAppendErrors()}}},{key:"getBackBufferEvictionTarget",value:function(e,t,r){var n=this.media;return n?this.fragmentTracker.getBackBufferEvictionEnd(n.currentTime,r,t):0}},{key:"getFragmentAppendProgress",value:function(e){var t,r=Ks(e),n=this.fragmentAppendProgress[r];return(null==(t=n)?void 0:t.stats)!==e.stats&&(n={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[r]=n),n}},{key:"checkAppendProgress",value:function(e,t,r,n){if(!(t||!$(e)||e.gap||r.iframe||r.partial)){var i=Ks(e),a=this.fragmentAppendProgress[i];delete this.fragmentAppendProgress[i];var s=e.stats.buffering;if(!s.start||s.first){var o=(null==a?void 0:a.stats)===e.stats?a:void 0;if(null==o||!o.errored){var l=n.length>0&&n.every(function(e){return!0===(null==o?void 0:o.fullyBuffered[e])});if(null!=o&&o.progressed||l)delete this.appendsWithoutProgress[i];else if(o||0!==n.length){var u=(this.appendsWithoutProgress[i]||0)+1,c=this.hls;u>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[i]:this.appendsWithoutProgress[i]=u,this.warn("Fragment ".concat(e.sn," of ").concat(e.type," playlist ").concat(e.level," appended ").concat(u," time").concat(u>1?"s":""," without buffered range growth")),c.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:r,parent:e.type,appendsWithoutProgress:u,error:new Error("Fragment append did not increase buffered coverage (".concat(u,")"))})}}}}}},{key:"resetAppendProgress",value:function(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}},{key:"resetAppendErrors",value:function(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}},{key:"trimBuffers",value:function(e,t,r,n){var i=this.hls,a=this.details,s=this.media;if(s&&null!==a&&this.sourceBufferCount){var o=i.config,l=s.currentTime,u=a.levelTargetDuration;t=a.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:t;var c=-1/0;if(x(t)&&t>=0){var d=Math.max(t,u);c=Math.floor(l/u)*u-d}if(r){var h=this.getLoopBackBufferFlushEnd(r,null!=n?n:null);h>0&&(c=Math.max(c,h))}if(c>0&&this.flushBackBuffer(l,u,c),x(e)&&e>0){var f=Math.max(o.maxBufferLength,e),v=Math.max(f,u),g=Math.floor(l/u)*u+v;this.flushFrontBuffer(l,u,g)}}}},{key:"getLoopBackBufferFlushEnd",value:function(e,t){var r,n=this.media;if(!1===(null==(r=this.hls)?void 0:r.config.loopBackBufferFlush)||null==n||!n.loop||!t||e.level<=t.level)return 0;var i=e.elementaryStreams,a=i.video,s=i.audiovideo;if(null!=a&&a.partial||null!=s&&s.partial)return 0;var o=this.getEarliestElementaryStreamStart(e)-.25;return o<=0?0:(this.log("Flushing lower quality back buffer for loop: level ".concat(e.level,", range [0-").concat(o.toFixed(3),"]")),o)}},{key:"getEarliestElementaryStreamStart",value:function(e){var t=e.elementaryStreams,r=t.audio,n=t.video,i=t.audiovideo,a=e.start;return i?a=Math.min(a,i.startDTS):(r&&(a=Math.min(a,r.startDTS)),n&&(a=Math.min(a,n.startDTS))),a}},{key:"flushBackBuffer",value:function(e,t,r){var n=this;this.sourceBuffers.forEach(function(e){var t=L(e,2),i=t[0],a=t[1];if(a){var s=kn.getBuffered(a);if(s.length>0&&r>s.start(0)){var o,l,u;n.hls.trigger(B.BACK_BUFFER_REACHED,{bufferEnd:r});var c=n.tracks[i];if(null!=(o=n.details)&&o.live)n.hls.trigger(B.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=c&&c.ended&&(null==(l=n.media)||!l.loop||!1===(null==(u=n.hls)?void 0:u.config.loopBackBufferFlush)))return void n.log("Cannot flush ".concat(i," back buffer while SourceBuffer is in ended state"));n.hls.trigger(B.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:i})}}})}},{key:"flushFrontBuffer",value:function(e,t,r){var n=this;this.sourceBuffers.forEach(function(t){var i=L(t,2),a=i[0],s=i[1];if(s){var o=kn.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),c=o.end(l-1);if(r>u||e>=u&&e<=c)return;n.hls.trigger(B.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}},{key:"getDurationAndRange",value:function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var i=Math.max(0,t.fragmentStart);return{duration:1/0,start:i,end:Math.max(i,n)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return x(a)?{duration:a}:null;var s=this.media.duration;return n>(x(r.duration)?r.duration:0)&&n>s||!x(s)?{duration:n}:null}},{key:"updateMediaSource",value:function(e){var t=e.duration,r=e.start,n=e.end,i=this.mediaSource;i&&this.media&&"open"===i.readyState&&(i.duration!==t&&(x(t)&&this.log("Updating MediaSource duration to ".concat(t.toFixed(3))),i.duration=t),void 0!==r&&void 0!==n&&(this.log("MediaSource duration is set to ".concat(i.duration,". Setting seekable range to ").concat(r,"-").concat(n,".")),i.setLiveSeekableRange(r,n)))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"checkPendingTracks",value:function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: ".concat(t," codec events expected: ").concat(e,") ").concat(mr(r))),this.tracksReady){var n,i=null==(n=this.transferData)?void 0:n.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}},{key:"bufferCreated",value:function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach(function(r){var n=L(r,2),i=n[0],a=n[1];if(i){var s=e.tracks[i];t[i]={buffer:a,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(B.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: ".concat(this.operationQueue)),this.sourceBuffers.forEach(function(t){var r=L(t,1)[0];e.executeNext(r)})}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}}},{key:"createSourceBuffers",value:function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var n in e){var i=n,a=e[i];if(this.isPending(a)){var s=this.getTrackCodec(a,i),o="".concat(a.container,";codecs=").concat(s);a.codec=s,this.log("creating sourceBuffer(".concat(o,")").concat(this.currentOp(i)?" Queued":""," ").concat(mr(a)));try{var l=r.addSourceBuffer(o),u=Gs(i),c=[i,l];t[u]=c,a.buffer=l}catch(h){var d;return this.error("error while trying to add sourceBuffer: ".concat(h.message)),this.shiftAndExecuteNext(i),null==(d=this.operationQueue)||d.removeBlockers(),delete this.tracks[i],void this.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:i,mimeType:o,parent:a.id})}this.trackSourceBuffer(i,a)}}this.bufferCreated()}},{key:"clearBufferAppendTimeoutId",value:function(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}},{key:"getTrackCodec",value:function(e,t){var r=e.supplemental,n=e.codec;r&&("video"===t||"audiovideo"===t)&&Kt(r,"video")&&(n=function(e,t){var r=[];if(e)for(var n=e.split(","),i=0;i<n.length;i++)jt(n[i],"video")||r.push(n[i]);return t&&r.push(t),r.join(",")}(n,r));var i=Qt(n,e.levelCodec);return i?"audio"===t.slice(0,5)?Xt(i,this.appendSource):i:""}},{key:"trackSourceBuffer",value:function(e,t){var r=this,n=t.buffer;if(n){var i=this.getTrackCodec(t,e);this.tracks[e]={buffer:n,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",function(e,t){var n=t.removedRanges;null!=n&&n.length&&(r.log("".concat(e," buffer removed ").concat(Ui(n))),r.hls.trigger(B.BUFFER_FLUSHED,{type:e,start:n.start(0),end:n.end(n.length-1)}))})}}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"onSBUpdateStart",value:function(e){var t=this.currentOp(e);t&&t.onStart()}},{key:"onSBUpdateEnd",value:function(e){var t,r,n=this;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var i=this.currentOp(e);if(i){if(i.onComplete(),null==(r=this.tracks[e])||null==(r=r.buffer)?void 0:r.updating)return this.log("".concat(e,' SourceBuffer updating on "updateend"')),void this.blockUntilOpen(function(){n.shiftAndExecuteNext(e)});this.shiftAndExecuteNext(e)}}else this.resetBuffer(e)}},{key:"onSBUpdateError",value:function(e,t){var r,n=null==(r=this.mediaSource)?void 0:r.readyState,i=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat(n));this.error("".concat(i.message),t),this.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});var a=this.currentOp(e);a&&a.onError(i)}},{key:"updateTimestampOffset",value:function(e,t,r,n,i,a){var s=t-e.timestampOffset;Math.abs(s)>=r&&(this.log("Updating ".concat(n," SourceBuffer timestampOffset to ").concat(t," (sn: ").concat(i," cc: ").concat(a,")")),e.timestampOffset=t)}},{key:"removeExecutor",value:function(e,t,r){var n=this.media,i=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!n||!i||!s)throw new Error("Attempting to remove from the ".concat(e," SourceBuffer, but it does not exist"));var o,l=x(n.duration)?n.duration:1/0,u=x(i.duration)?i.duration:1/0,c=Math.max(0,t);if(c>=u)return null==(o=this.currentOp(e))||o.onComplete(),void this.shiftAndExecuteNext(e);var d=Math.min(r,l,u);if(!(d>c)||a.ending&&!a.ended)throw new Error("Cannot remove ".concat(d<=c?"invalid range (".concat(c," >= ").concat(d,") "):"","from the ").concat(e," SourceBuffer").concat(a.ending?" while track ending":""));a.ended=!1,this.log("Removing [".concat(c,",").concat(d,"] from the ").concat(e," SourceBuffer")),s.remove(c,d)}},{key:"appendExecutor",value:function(e,t){var r=this,n=this.tracks[t],i=null==n?void 0:n.buffer;if(!i)throw new Ns("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));if(n.ending=!1,n.ended=!1,this.hls.config.appendTimeout!==1/0){var a=this.calculateAppendTimeoutTime(i);n.bufferAppendTimeoutId=self.setTimeout(function(){return r.appendTimeoutHandler(t,i,a)},a)}i.appendBuffer(e)}},{key:"appendTimeoutHandler",value:function(e,t,r){this.log("Received timeout after ".concat(r,"ms for append on ").concat(e," source buffer. Aborting and triggering error."));try{t.abort()}catch(i){this.log("Failed to abort append on ".concat(e," source buffer after timeout."))}var n=this.currentOp(e);n&&n.onError(new Error("".concat(e,"-append-timeout")))}},{key:"calculateAppendTimeoutTime",value:function(e){var t=10;this.details&&(t=this.details.levelTargetDuration);var r=2*t*1e3;if(null===this.media)return r;var n=kn.bufferInfo(e,this.media.currentTime,0);return n.len?(r=Math.max(1e3*n.len,r),Math.max(this.hls.config.appendTimeout,r)):r}},{key:"blockUntilOpen",value:function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(function(e){t.warn("SourceBuffer blocked callback ".concat(e)),t.stepOperationQueue(t.sourceBufferTypes)});else try{e()}catch(r){this.warn("Callback run without blocking ".concat(this.operationQueue," ").concat(r))}}},{key:"isUpdating",value:function(){return this.sourceBuffers.some(function(e){var t=L(e,2),r=t[0],n=t[1];return r&&n.updating})}},{key:"isQueued",value:function(){var e=this;return this.sourceBuffers.some(function(t){var r=L(t,1)[0];return r&&!!e.currentOp(r)})}},{key:"isPending",value:function(e){return!!e&&!e.buffer}},{key:"isAudioBlocked",value:function(){var e;return"block-audio"===(null==(e=this.currentOp("audio"))?void 0:e.label)}},{key:"isAudioBlocking",value:function(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}},{key:"blockBuffers",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var n=this.operationQueue,i=2===r.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:r.map(function(e){return t.appendBlocker(e)});return Promise.all(i).then(function(r){n===t.operationQueue&&(e(),t.stepOperationQueue(t.sourceBufferTypes))})}},{key:"stepOperationQueue",value:function(e){var t=this;e.forEach(function(e){var r,n=null==(r=t.tracks[e])?void 0:r.buffer;!n||n.updating||"audio"===e&&t.isAudioBlocked()||t.shiftAndExecuteNext(e)})}},{key:"append",value:function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}},{key:"insertNext",value:function(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}},{key:"appendBlocker",value:function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}},{key:"currentOp",value:function(e){return this.operationQueue?this.operationQueue.current(e):null}},{key:"executeNext",value:function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}},{key:"shiftAndExecuteNext",value:function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){return t+(e.isPending(e.tracks[r])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(e,t){return e+(L(t,1)[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(e){return L(e,1)[0]}).filter(function(e){return!!e})}},{key:"addBufferListener",value:function(e,t,r){var n=this.tracks[e];if(n){var i=n.buffer;if(i){var a=r.bind(this,e);n.listeners.push({event:t,listener:a}),Fi(i,t,a)}}}},{key:"removeBufferListeners",value:function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach(function(e){Ni(r,e.event,e.listener)}),t.listeners.length=0)}}}])}(Ee);function Bs(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach(function(t){e.removeChild(t)})}function Gs(e){return"audio"===e?1:0}function js(e,t){return"".concat(e?"":" - triggering recovery").concat(t?" with HTMLMediaElement Error: "+t.message:"")}function Ks(e){return"".concat(e.type,"_").concat(e.sn,"_").concat(e.level)}function Hs(e,t){for(var r=t.start,n=t.end,i=0,a=0;a<e.length;a++){var s=e[a];if(s.start>=n)break;var o=Math.max(r,s.start),l=Math.min(n,s.end);l>o&&(i+=l-o)}return i}function Vs(e,t){return t.duration-e<=.05}var qs=function(){function e(t){c(this,e),this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}return h(e,[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"destroy",value:function(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(B.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.BUFFER_CODECS,this.onBufferCodecs,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this))}},{key:"unregisterListener",value:function(){var e=this.hls;e&&(e.off(B.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.BUFFER_CODECS,this.onBufferCodecs,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this))}},{key:"onFpsDropLevelCapping",value:function(e,t){if(this.hls){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}}},{key:"onMediaAttaching",value:function(e,t){var r=t.media;this.clientRect=null,this.hls&&(r instanceof HTMLVideoElement?(this.media=r,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}},{key:"onManifestParsed",value:function(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}},{key:"onLevelsUpdated",value:function(){if(this.hls)if((this.timer||this.observer)&&(x(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){var e=this.hls.levels;e.length>1&&e.some(function(e){return!!e.videoCodec})&&this.startCapping()}}},{key:"onBufferCodecs",value:function(e,t){t.video&&this.startCapping()}},{key:"onMediaDetaching",value:function(){this.stopCapping(),this.media=null}},{key:"detectPlayerSize",value:function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);var e=this.hls.levels;if(e.length>1){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(r,": ").concat(e[r].height,"p@").concat(e[r].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else 1===e.length&&this.stopCapping()}}},{key:"getMaxLevel",value:function(t){var r=this;if(!this.hls)return-1;var n=this.hls.levels;if(!n.length)return-1;var i=n.filter(function(e,n){return r.isLevelAllowed(e)&&n<=t});return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}},{key:"observe",value:function(){var e=this,t=self.ResizeObserver;t&&(this.observer=new t(function(t){var r,n=null==(r=t[0])?void 0:r.contentRect;n&&(e.clientRect=n,e.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}},{key:"startCapping",value:function(){var e;this.timer||this.observer||null==(e=this.hls)||!e.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}},{key:"stopCapping",value:function(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}},{key:"getDimensions",value:function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}},{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls)return e;var t=this.hls.config,r=t.ignoreDevicePixelRatio,n=t.maxDevicePixelRatio;if(!r)try{e=self.devicePixelRatio}catch(i){}return Math.min(e,n)}},{key:"isLevelAllowed",value:function(e){return!this.restrictedLevels.some(function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height})}}],[{key:"getMaxLevelByMediaSize",value:function(e,t,r){if(null==e||!e.length)return-1;for(var n=function(e,t){return!t||(e.width!==t.width||e.height!==t.height)},i=e.length-1,a=Math.max(t,r),s=0;s<e.length;s+=1){var o=e[s];if((o.width>=a||o.height>=a)&&n(o,e[s+1])){i=s;break}}return i}}])}(),Ws=h(function e(t,r){c(this,e),Array.isArray(t)&&(t=t.map(function(t){return t instanceof e?t:new e(t)})),this.value=t,this.params=r});function Ys(e,t,r,n){return new Error("failed to ".concat(e,' "').concat((i=t,Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":"object"===_(i)?JSON.stringify(i):String(i)),'" as ').concat(r),{cause:n});var i}var zs="Bare Item";var Xs=/[\x00-\x1f\x7f]+/,Qs=h(function e(t){c(this,e),this.description=t});function $s(e,t,r){return Ys("serialize",e,t,r)}function Js(e){if(!1===ArrayBuffer.isView(e))throw $s(e,"Byte Sequence");return":".concat((t=e,btoa(String.fromCharCode.apply(String,I(t)))),":");var t}function Zs(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw $s(e,"Integer");return e.toString()}function eo(e){var t=Ce(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw $s(e,"Decimal");var r=t.toString();return r.includes(".")?r:"".concat(r,".0")}function to(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw $s(r,"Token");return r}function ro(e){switch(_(e)){case"number":if(!x(e))throw $s(e,zs);return Number.isInteger(e)?Zs(e):eo(e);case"string":return function(e){if(Xs.test(e))throw $s(e,"String");return'"'.concat(e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}(e);case"symbol":return to(e);case"boolean":return function(e){if("boolean"!=typeof e)throw $s(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@".concat(Zs(e.getTime()/1e3))}(e);if(e instanceof Uint8Array)return Js(e);if(e instanceof Qs)return to(e);default:throw $s(e,zs)}}function no(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw $s(e,"Key");return e}function io(e){return null==e?"":Object.entries(e).map(function(e){var t=L(e,2),r=t[0],n=t[1];return!0===n?";".concat(no(r)):";".concat(no(r),"=").concat(ro(n))}).join("")}function ao(e){return e instanceof Ws?"".concat(ro(e.value)).concat(io(e.params)):ro(e)}function so(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!==_(e)||null==e)throw $s(e,"Dict");var r=e instanceof Map?e.entries():Object.entries(e),n=null!=t&&t.whitespace?" ":"";return Array.from(r).map(function(e){var t=L(e,2),r=t[0],n=t[1];n instanceof Ws==!1&&(n=new Ws(n));var i,a=no(r);return!0===n.value?a+=io(n.params):(a+="=",Array.isArray(n.value)?a+="(".concat((i=n).value.map(ao).join(" "),")").concat(io(i.params)):a+=ao(n)),a}).join(",".concat(n))}function oo(e,t){return so(e,t)}var lo=["url"],uo=["version","eventTargets","sid","transmissionMode"],co=["customData","headers"],ho=function(e){return e instanceof Ws?new Ws(Math.round(e.value),e.params):Math.round(e)},fo=function(e){return Array.isArray(e)?e.map(ho):ho(e)},vo=function(e,t){return Array.isArray(e)?e.map(function(e){return vo(e,t)}):e instanceof Ws&&"string"==typeof e.value?new Ws(vo(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var r;try{r=new URL(e)}catch(l){return e}var n=new URL(t);if(r.origin!==n.origin)return e;for(var i=r.pathname.split("/").slice(1),a=n.pathname.split("/").slice(1,-1),s=Math.min(i.length,a.length),o=0;o<s&&i[o]===a[o];o++)i.shift(),a.shift();for(;a.length;)a.shift(),i.unshift("..");return i.join("/")+r.search+r.hash}(e,(r=t.baseUrl,(n="string"==typeof r?new URL(r):r).origin+n.pathname.substring(0,n.pathname.lastIndexOf("/")+1)))),1===t.version?encodeURIComponent(e):e);var r,n},go=function(e){return e instanceof Ws?new Ws(100*Math.round(e.value/100),e.params):100*Math.round(e/100)},po=function(e){return Array.isArray(e)?e.map(go):go(e)},yo={br:fo,d:fo,bl:po,dl:po,mtp:po,nor:function(e,t){var r=e;return t.version>=2&&(e instanceof Ws&&"string"==typeof e.value?r=new Ws([e]):"string"==typeof e&&(r=[e])),vo(r,t)},rtp:po,tb:fo},mo="rr",Eo="bc",ko="e",So=mo,To="ce",bo=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Ao="event",Lo="request",Ro=["cen","e","h","ts"],Io=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],wo=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function _o(e){return wo.test(e)}var Po=new Set(Io);function Do(e){return Po.has(e)||_o(e)}var Co=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Oo=new Set(Co);function xo(e){return Oo.has(e)}var Mo=new Set(Ro);var Fo=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),No=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Uo=new Set(No);function Bo(e){return Uo.has(e)||_o(e)}var Go=new Set(["ot","sf","st","e","sta"]);function jo(e){return Go.has(e)}function Ko(e){return"number"==typeof e?x(e):null!=e&&""!==e&&!1!==e}var Ho=v(v({},Ao,function(e){return Do(e)||xo(e)||Mo.has(e)}),Lo,Do);function Vo(e,t){var r;return Array.isArray(e)?(t&&(r=e.find(function(e){var r;return(null==(r=e.params)?void 0:r.ot)===t})),r||(r=e[0]),Vo(r)):e instanceof Ws?e.value:e}function qo(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(null==e||"object"!==_(e))return r;var n=t.version||e.v||2,i=t.reportingMode||Lo,a=1===n?function(e){for(var t={},r=0,n=Object.entries(e);r<n.length;r++){var i=L(n[r],2),a=i[0],s=i[1];if(null!=s)if("nor"===a){var o,l=(Array.isArray(s)?s:[s])[0];l instanceof Ws?(t.nor=l.value,null!=(o=l.params)&&o.r&&(t.nrr=l.params.r)):t.nor=l}else Fo.has(a)?t[a]=Vo(s,e.ot):t[a]=s;else t[a]=s}return t}(e):e,s=1===n?Bo:Ho[i],o=Object.keys(a).filter(s);a.e&&a.e!==mo&&(o=o.filter(function(e){return!xo(e)}));var l=t.filter;"function"==typeof l&&(o=o.filter(l));var u=i===Ao;if(u){var c=a.e;o.includes("e")||null==c||o.push("e"),o.includes("ts")||o.push("ts"),o.includes("cen")||null==a.cen||"ce"!==c||o.push("cen");var d=c?bo.get(c):void 0;d&&null!=a[d]&&!o.includes(d)&&o.push(d)}if(0===o.length)return r;n>1&&!o.includes("v")&&o.push("v");var h={version:n,reportingMode:i,baseUrl:t.baseUrl};o.sort();var v,g=f(o);try{for(g.s();!(v=g.n()).done;){var p,y,m=v.value,E=a[m],k=null!=(p=null==(y=t.formatters)?void 0:y[m])?p:yo[m];if("function"==typeof k&&(E=k(E,h)),"v"===m){if(1===n)continue;E=n}if("pr"!==m||1!==E||u&&"pr"===a.e){u&&"ts"===m&&!x(E)&&(E=Date.now());var S=u&&!1===E&&"bg"===m&&"b"===a.e;(Ko(E)||S)&&(jo(m)&&"string"==typeof E&&(E=new Qs(E)),r[m]=E)}}}catch(Ry){g.e(Ry)}finally{g.f()}return r}var Wo="CMCD-Object",Yo="CMCD-Request",zo="CMCD-Session",Xo="CMCD-Status",Qo=Yo,$o={ab:Wo,br:Wo,d:Wo,lab:Wo,lb:Wo,ot:Wo,tab:Wo,tb:Wo,tpb:Wo,bl:Yo,cs:Yo,dfa:Yo,dl:Yo,ltc:Yo,mtp:Yo,nor:Yo,nrr:Yo,pb:Yo,sn:Yo,sta:Yo,su:Yo,tbl:Yo,cid:zo,msd:zo,sf:zo,sid:zo,st:zo,v:zo,bg:Xo,bs:Xo,bsa:Xo,bsd:Xo,bsda:Xo,cdn:Xo,ec:Xo,nr:Xo,pr:Xo,pt:Xo,rtp:Xo};function Jo(e,t){var r={};if(!e)return r;for(var n,i=Object.keys(e),a=t?(n=t,Object.keys(n).reduce(function(e,t){var r;return null==(r=n[t])||r.forEach(function(r){return e[r]=t}),e},{})):{},s=0,o=i;s<o.length;s++){var l,u=o[s],c=$o[u]||a[u]||Qo;(null!=(l=r[c])?l:r[c]={})[u]=e[u]}return r}var Zo="CMCD";function el(e){return oo(e,{whitespace:!1})}function tl(e){return e?el(qo(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})):""}var rl=[].concat(No,Io,Co,Ro).filter(function(e,t,r){return r.indexOf(e)===t}),nl="m",il="a",al="v",sl="av",ol="i",ll="tt",ul="s",cl="p",dl="k",hl="r",fl="a",vl="e",gl="f",pl="d",yl="query",ml="headers";function El(e,t,r){var n,i=new Set(null!=(n=t.enabledKeys)?n:[]);return{version:t.version||2,reportingMode:e,filter:function(e){return i.has(e)},baseUrl:r}}var kl=Object.is,Sl=function(e){return e},Tl=Array.from(bo,function(e){var t=L(e,2),r=t[0],n=t[1];return"br"===n?{event:r,field:n,equal:function(e,t){return void 0===e||void 0===t?e===t:function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++){var n=e[r],i=t[r];if(n!==i){if("number"==typeof n||"number"==typeof i)return!1;if(n.value!==i.value)return!1;var a=n.params,s=i.params,o=a&&Object.keys(a)[0],l=s&&Object.keys(s)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&a&&s&&a[o]!==s[l])return!1}}return!0}(e,t)},snapshot:function(e){return e.slice()}}:{event:r,field:n,equal:kl,snapshot:Sl}}),bl=new Map(Tl.map(function(e){return[e.event,e]}));function Al(e){var t=e.url,r=oe(e,lo);return fetch(t,r)}var Ll=function(){return h(function e(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Al;c(this,e),this.timeOrigin=performance.timeOrigin||(null==(r=performance.timing)?void 0:r.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(e){var t=e.version,r=void 0===t?2:t,n=e.eventTargets,i=void 0===n?[]:n,a=e.sid,s=void 0===a?Oe():a,o=e.transmissionMode,l=void 0===o?yl:o;return se(se({},oe(e,uo)),{},{version:r,transmissionMode:l,sid:s,eventTargets:i.reduce(function(e,t){var r,n,i;return null!=t&&t.url&&null!=(r=t.events)&&r.length&&e.push({version:t.version||2,enabledKeys:(null==(n=t.enabledKeys)?void 0:n.slice())||[],url:t.url,events:t.events.slice(),interval:null!=(i=t.interval)?i:30,batchSize:t.batchSize||1}),e},[])})}(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=n;var i,a=f(this.config.eventTargets);try{for(a.s();!(i=a.n()).done;){var s=i.value;this.eventTargets.set(s,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}}catch(Ry){a.e(Ry)}finally{a.f()}},[{key:"start",value:function(){var e=this;this.eventTargets.forEach(function(t,r){if(e.disarmInterval(t),0!==r.interval&&r.events.includes("t")){var n=function(){e.recordTargetEvent(t,r,"t"),e.processEventTargets()};t.intervalId=setInterval(n,1e3*r.interval),n()}})}},{key:"stop",value:function(){var e=this;arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.flush(),this.eventTargets.forEach(function(t){e.disarmInterval(t)})}},{key:"flush",value:function(){this.processEventTargets(!0)}},{key:"update",value:function(e){e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=se(se(se({},this.data),e),{},{msd:void 0});for(var t=0,r=Tl;t<r.length;t++){var n=r[t];n.field in e&&!n.equal(this.data[n.field],this.lastEmitted[n.field])&&this.recordEvent(n.event)}}},{key:"recordEvent",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=bl.get(e);if(n){var i=n.field,a=r[i];void 0!==a&&ie(this.data,v({},i,a));var s=this.data[i];if(void 0===s)return;if(n.equal(s,this.lastEmitted[i]))return;ie(this.lastEmitted,v({},i,n.snapshot(s)))}this.eventTargets.forEach(function(n,i){t.recordTargetEvent(n,i,e,r)}),this.processEventTargets()}},{key:"recordTargetEvent",value:function(e,t,r){var n,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(t.events.includes(r)){var a=se(se(se({},this.data),i),{},{e:r,ts:null!=(n=i.ts)?n:Date.now(),sn:e.sn++});isNaN(this.msd)||e.msdSent||(a.msd=this.msd,e.msdSent=!0),e.queue.push(a)}}},{key:"recordResponseReceived",value:function(e){var t,r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=e.request,s=null!=(t=i.url)?t:null==a?void 0:a.url;if(s){var o=new URL(s);o.searchParams.delete(Zo);var l={url:o.toString(),rc:e.status},u=e.resourceTiming;u&&(null!=u.startTime&&(l.ts=Math.round(this.timeOrigin+u.startTime),null!=u.responseStart&&(l.ttfb=Math.round(u.responseStart-u.startTime))),null!=u.duration&&(l.ttlb=Math.round(u.duration)));var c=null!=(r=null==(n=a.customData)?void 0:n.cmcd)?r:{};this.recordEvent(mo,se(se(se({},c),l),i))}}},{key:"applyRequestReport",value:function(e){var t;return null!=(t=this.createRequestReport(e))?t:e}},{key:"isRequestReportingEnabled",value:function(){var e;return!(null==(e=this.config.enabledKeys)||!e.length)}},{key:"createRequestReport",value:function(e,t){var r,n=e.customData,i=void 0===n?{}:n,a=e.headers,s=void 0===a?{}:a,o=se(se({},oe(e,co)),{},{headers:se({},s),customData:se(se({},i),{},{cmcd:{}})});if(null==(r=this.config.enabledKeys)||!r.length||!o.url)return o;var l=new URL(o.url),u=se(se(se({},this.data),t),{},{sn:this.requestTarget.sn++}),c=El(Lo,this.config,o.url);isNaN(this.msd)||this.requestTarget.msdSent||(u.msd=this.msd,this.requestTarget.msdSent=!0);var d=o.customData.cmcd=qo(u,c);switch(this.config.transmissionMode){case yl:var h=el(d);h&&(l.searchParams.set(Zo,h),o.url=l.toString());break;case ml:ie(o.headers,function(e,t){for(var r={},n=Jo(e,t),i=0,a=Object.entries(n);i<a.length;i++){var s=L(a[i],2),o=s[0],l=oo(s[1],{whitespace:!1});l&&(r[o]=l)}return r}(d,c.customHeaderMap))}return o}},{key:"processEventTargets",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=!1;this.eventTargets.forEach(function(n,i){var a=n.queue;if(a.length&&(!(a.length<i.batchSize)||t)){var s=t?a.length:i.batchSize,o=a.splice(0,s);e.sendEventReport(i,o).catch(function(){var e;(e=n.queue).unshift.apply(e,I(o))}),r||(r=a.length>0)}}),r&&this.processEventTargets()}},{key:"sendEventReport",value:(e=o(S().m(function e(t,r){var n,i,a;return S().w(function(e){for(;;)switch(e.n){case 0:return n=El(Ao,t),e.n=1,this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:r.map(function(e){return tl(e,n)}).join("\n")+"\n"});case 1:if(i=e.v,410!==(a=i.status)){e.n=2;break}this.disposeEventTarget(t),e.n=3;break;case 2:if(!(429===a||a>499&&a<600)){e.n=3;break}throw new Error("Event report failed with status ".concat(a));case 3:return e.a(2)}},e,this)})),function(t,r){return e.apply(this,arguments)})},{key:"disarmInterval",value:function(e){clearInterval(e.intervalId),e.intervalId=void 0}},{key:"disposeEventTarget",value:function(e){var t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))}},{key:"resetSession",value:function(){this.eventTargets.forEach(function(e){return e.sn=0}),this.requestTarget.sn=0,this.lastEmitted={}}}]);var e}(),Rl="h",Il="v",wl="l",_l="ll";new Set(No),new Set(rl);var Pl=["includeKeys"];function Dl(e){return Object.keys(e).every(_o)}var Cl=function(){return h(function e(t){var r=this;c(this,e),this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0,r.setPlayerState(hl)),r.buffering=!0},this.onPlay=function(){r.initialized||r.setPlayerState(ul)},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1,r.setPlayerState(cl)},this.onPause=function(){r.media&&!r.media.ended&&r.setPlayerState(fl)},this.onSeeking=function(){r.initialized&&r.setPlayerState(dl)},this.onSeeked=function(){var e;r.initialized&&null!=(e=r.media)&&e.paused&&r.setPlayerState(fl)},this.onRateChange=function(){r.reporter&&r.media&&r.reporter.update({pr:r.media.playbackRate})},this.applyPlaylistData=function(e){try{r.apply(e,{ot:nl,su:!r.initialized})}catch(t){r.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=function(e){try{var t=e.frag,n=e.part,i=r.hls.levels[t.level],a=r.getObjectType(t,i),s={d:1e3*(n||t).duration,ot:a};if(a===al||a===il||a===sl||null==a&&("main"===t.type||"audio"===t.type)){var o,l=i.bitrate/1e3;s.br=[l];var u=r.config.cmcd,c=null!=(o=null==u?void 0:u.rtpSafetyFactor)?o:5;if(s.rtp=100*Math.round(l*c/100),a===sl||null==a&&"main"===t.type){var d=r.getTopBandwidth()/1e3;x(d)&&(s.tb=[d]);var h=r.getLowestBandwidth()/1e3;x(h)&&(s.lb=[h])}var f=r.getBufferLength(t);if(x(f)){var v;s.bl=[f];var g=(null==(v=r.media)?void 0:v.playbackRate)||1;s.dl=100*Math.round(f/g/100)}r.playheadLevel&&(s.pb=[r.playheadLevel.bitrate/1e3]);var p=r.hls.maxAutoLevel;if(p>=0){var y=r.hls.levels[p];y&&(s.tpb=[y.bitrate/1e3])}}var m=n?r.getNextPart(n):r.getNextFrag(t);null!=m&&m.url&&m.url!==t.url&&(m.byteRange.length>0?s.nor=[(E=m.url,k={r:"".concat(m.byteRange[0],"-").concat(m.byteRange[1])},new Ws(E,k))]:s.nor=[m.url]),r.apply(e,s)}catch(S){r.hls.logger.warn("Could not generate segment CMCD data.",S)}var E,k},this.recordFragmentResponse=function(e,t,n){var i,a=r.config.cmcd,s=null==a||null==(i=a.eventTargets)?void 0:i.some(function(e){var t;return null==(t=e.events)?void 0:t.includes(So)});if(r.reporter&&n.loading.first>0&&s)try{r.reporter.recordResponseReceived({request:{url:e},status:t.code,resourceTiming:{startTime:n.loading.start,responseStart:n.loading.first,duration:n.loading.end-n.loading.start,encodedBodySize:n.total}})}catch(o){r.hls.logger.warn("Could not record fragment response CMCD data.",o)}},this.hls=t;var n=this.config=t.config;null!=n.cmcd&&(n.pLoader=this.createPlaylistLoader(),n.fLoader=this.createFragmentLoader(),this.registerListeners())},[{key:"createReporter",value:function(){var e,t,r=this.config.cmcd;if(null!=r){var n=r.version||1;if(this.reporter=new Ll({sid:r.sessionId||this.hls.sessionId,cid:r.contentId,version:n,transmissionMode:!0===r.useHeaders?ml:yl,enabledKeys:null!=(e=r.includeKeys)?e:I(n>=2?rl:No),eventTargets:(null!=(t=r.eventTargets)?t:[]).map(function(e){var t=e.includeKeys;return se(se({},oe(e,Pl)),{},{enabledKeys:null!=t?t:rl})})},r.loader),this.reporter.update({sf:Rl,sta:this.playerState}),r.reporterCallback){var i=this.reporter,a={updateCustomData:function(e){Dl(e)&&i.update(e)},recordCustomEvent:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Dl(t)&&i.recordEvent(To,se({cen:e},t))}};r.reporterCallback(a)}this.reporter.start()}}},{key:"registerListeners",value:function(){var e=this.hls;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_DETACHED,this.onMediaDetached,this),e.on(B.MEDIA_ENDED,this.onMediaEnded,this),e.on(B.ERROR,this.onError,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(B.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(B.BUFFER_FLUSHED,this.onBufferInfoChange,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_DETACHED,this.onMediaDetached,this),e.off(B.MEDIA_ENDED,this.onMediaEnded,this),e.off(B.ERROR,this.onError,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(B.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(B.BUFFER_FLUSHED,this.onBufferInfoChange,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.setPlayerState(this.media.autoplay?ul:pl),Fi(r,"waiting",this.onWaiting),Fi(r,"play",this.onPlay),Fi(r,"playing",this.onPlaying),Fi(r,"pause",this.onPause),Fi(r,"seeking",this.onSeeking),Fi(r,"seeked",this.onSeeked),Fi(r,"ratechange",this.onRateChange)}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(Ni(e,"waiting",this.onWaiting),Ni(e,"play",this.onPlay),Ni(e,"playing",this.onPlaying),Ni(e,"pause",this.onPause),Ni(e,"seeking",this.onSeeking),Ni(e,"seeked",this.onSeeked),Ni(e,"ratechange",this.onRateChange),this.media=null)}},{key:"onMediaEnded",value:function(e,t){this.setPlayerState(vl)}},{key:"onManifestLoading",value:function(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(pl)}},{key:"onError",value:function(e,t){t.fatal&&(this.setPlayerState(gl),this.reporter&&this.reporter.recordEvent(ko,{ec:[t.details]}))}},{key:"onLevelSwitching",value:function(e,t){var r;if(this.reporter){var n={br:[t.bitrate/1e3]},i=null==(r=t.details)?void 0:r.fragments[0];i&&(n.ot=this.getObjectType(i,t)),this.reporter.recordEvent(Eo,n)}}},{key:"onLevelSwitched",value:function(e,t){var r=this.hls.levels[t.level];r&&(this.playheadLevel=r)}},{key:"setPlayerState",value:function(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}},{key:"getStreamType",value:function(){var e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?_l:wl:Il}},{key:"apply",value:function(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.reporter){this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(t=this.media)?void 0:t.playbackRate,st:this.getStreamType()});var n=r.ot===ol||r.ot===al||r.ot===sl;this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),null==r.su&&(r.su=this.buffering);var i=this.reporter.createRequestReport({url:e.url,headers:e.headers},r);e.url=i.url,e.headers=i.headers}}},{key:"getNextFrag",value:function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var n=e.sn-r.startSN;return r.fragments[n+1]}}},{key:"getNextPart",value:function(e){var t,r=e.index,n=e.fragment,i=null==(t=this.hls.levels[n.level])||null==(t=t.details)?void 0:t.partList;if(i)for(var a=n.sn,s=i.length-1;s>=0;s--){var o=i[s];if(o.index===r&&o.fragment.sn===a)return i[s+1]}}},{key:"getObjectType",value:function(e,t){var r=e.type;if("subtitle"===r)return ll;if("initSegment"===e.sn)return ol;if("audio"===r)return il;if("main"===r){if(e.hasStreams){var n=e.elementaryStreams;if(n.audiovideo)return sl;if(n.video)return al;if(n.audio)return il}if(t){var i=t.audioCodec,a=t.videoCodec;if(!this.hls.audioTracks.length){if(i&&a)return sl;if(i)return il}if(a)return al}}}},{key:"getTopBandwidth",value:function(){var e=0,t=this.hls,r=t.maxAutoLevel,n=r>-1?r+1:t.levels.length;return t.levels.slice(0,n).forEach(function(t){t.bitrate>e&&(e=t.bitrate)}),e>0?e:NaN}},{key:"getLowestBandwidth",value:function(){var e=1/0,t=this.hls,r=t.maxAutoLevel,n=r>-1?r+1:t.levels.length;return t.levels.slice(0,n).forEach(function(t){t.bitrate<e&&(e=t.bitrate)}),x(e)?e:NaN}},{key:"getBufferLength",value:function(e){if(!this.media)return NaN;var t="audio"===e.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?1e3*t.len:NaN}},{key:"getEventBufferLength",value:function(){if(!this.media)return NaN;var e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return 1e3*Math.min(e.len,t.len);var r=e||t;return r?1e3*r.len:NaN}},{key:"onBufferInfoChange",value:function(e,t){if(this.reporter){var r=this.getEventBufferLength();x(r)&&this.reporter.update({bl:[r]})}}},{key:"createPlaylistLoader",value:function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){return h(function e(t){c(this,e),this.loader=void 0,this.loader=new r(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,r,n){t(e),this.loader.load(e,r,n)}}])}()}},{key:"createFragmentLoader",value:function(){var e=this.config.fLoader,t=this.applyFragmentData,r=this.recordFragmentResponse,n=e||this.config.loader;return function(){return h(function e(t){c(this,e),this.loader=void 0,this.loader=new n(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,n,i){t(e);var a=i.onSuccess;this.loader.load(e,n,se(se({},i),{},{onSuccess:function(t,n,i,s){a(t,n,i,s),r(e.url,t,n)}}))}}])}()}}])}(),Ol=function(e){function t(e){var r;return c(this,t),(r=u(this,t,["content-steering",e.logger])).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=e,r.registerListeners(),r}return y(t,e),h(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.ERROR,this.onError,this))}},{key:"pathways",value:function(){return(this.levels||[]).reduce(function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e},[])}},{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}},{key:"startLoad",value:function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}},{key:"stopLoad",value:function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}},{key:"clearTimeout",value:function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"removeLevel",value:function(e){var t=this.levels;t&&(this.levels=t.filter(function(t){return t!==e}))}},{key:"onManifestLoading",value:function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}},{key:"onManifestParsed",value:function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}},{key:"onError",value:function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===Nr&&r.flags&jr){var n=this.levels,i=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&n?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!i&&n&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==a,r.resolved||t.details===U.BUFFER_APPEND_ERROR&&!t.fatal||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(a," levels: ").concat(n?n.length:n," priorities: ").concat(mr(i)," penalized: ").concat(mr(this.penalizedPathways))))}}},{key:"filterParsedLevels",value:function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(r,'"')),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found ".concat(t.length,"/").concat(e.length,' levels in Pathway "').concat(this.pathwayId,'"')),t}},{key:"getLevelsForPathway",value:function(e){return null===this.levels?[]:this.levels.filter(function(t){return e===t.pathwayId})}},{key:"updatePathwayPriority",value:function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach(function(e){n-r[e]>3e5&&delete r[e]});for(var i=0;i<e.length;i++){var a=e[i];if(!(a in r)){if(a===this.pathwayId)return;var s=this.hls.nextLoadLevel,o=this.hls.levels[s];if((t=this.getLevelsForPathway(a)).length>0){this.log('Setting Pathway to "'.concat(a,'"')),this.pathwayId=a,_i(t),this.hls.trigger(B.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate ".concat(o.bitrate," to ").concat(l.bitrate)),this.hls.nextLoadLevel=s);break}}}}},{key:"getPathwayForGroupId",value:function(e,t,r){for(var n=this.getLevelsForPathway(r).concat(this.levels||[]),i=0;i<n.length;i++)if(t===q.AUDIO_TRACK&&n[i].hasAudioGroup(e)||t===q.SUBTITLE_TRACK&&n[i].hasSubtitleGroup(e))return n[i].pathwayId;return r}},{key:"clonePathways",value:function(e){var t=this,r=this.levels;if(r){var n={},i={};e.forEach(function(e){var a=e.ID,s=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!r.some(function(e){return e.pathwayId===a})){var l=t.getLevelsForPathway(s).map(function(e){var t=new wn(e.attrs);t["PATHWAY-ID"]=a;var r=t.AUDIO&&"".concat(t.AUDIO,"_clone_").concat(a),s=t.SUBTITLES&&"".concat(t.SUBTITLES,"_clone_").concat(a);r&&(n[t.AUDIO]=r,t.AUDIO=r),s&&(i[t.SUBTITLES]=s,t.SUBTITLES=s);var l=Ml(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),u=new gr({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(var c=1;c<e.audioGroups.length;c++)u.addGroupId("audio","".concat(e.audioGroups[c],"_clone_").concat(a));if(e.subtitleGroups)for(var d=1;d<e.subtitleGroups.length;d++)u.addGroupId("text","".concat(e.subtitleGroups[d],"_clone_").concat(a));return u});r.push.apply(r,I(l)),xl(t.audioTracks,n,o,a),xl(t.subtitleTracks,i,o,a)}})}}},{key:"loadSteeringManifest",value:function(e){var t,r=this,n=this.hls.config,i=n.loader;this.loader&&this.loader.destroy(),this.loader=new i(n);try{t=new self.URL(e)}catch(d){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: ".concat(e))}if("data:"!==t.protocol){var a=0|(this.hls.bandwidthEstimate||n.abrEwmaDefaultEstimate);or(t,"_HLS_pathway",this.pathwayId),or(t,"_HLS_throughput",""+a)}var s={type:q.STEERING_MANIFEST,responseType:"json",url:t.href},o=n.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},u={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:function(e,n,i,a){r.log('Loaded steering manifest: "'.concat(t,'"'));var s=e.data;if(1===(null==s?void 0:s.VERSION)){r.updated=performance.now(),r.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,t).href}catch(d){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(o))}r.scheduleRefresh(r.uri||i.url),l&&r.clonePathways(l);var c={steeringManifest:s,url:t.toString()};r.hls.trigger(B.STEERING_MANIFEST_LOADED,c),u&&r.updatePathwayPriority(u)}else r.log("Steering VERSION ".concat(s.VERSION," not supported!"))},onError:function(e,t,n,i){if(r.log("Error loading steering manifest: ".concat(e.code," ").concat(e.text," (").concat(t.url,")")),r.stopLoad(),410===e.code)return r.enabled=!1,void r.log("Steering manifest ".concat(t.url," no longer available"));var a=1e3*r.timeToLoad;if(429!==e.code)r.scheduleRefresh(r.uri||t.url,a);else{var s=r.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}r.log("Steering manifest ".concat(t.url," rate limited"))}},onTimeout:function(e,t,n){r.log("Timeout loading steering manifest (".concat(t.url,")")),r.scheduleRefresh(r.uri||t.url)}};this.log("Requesting steering manifest: ".concat(t)),this.loader.load(s,u,c)}},{key:"scheduleRefresh",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var r,n=null==(r=t.hls)?void 0:r.media;!n||n.ended?t.scheduleRefresh(e,1e3*t.timeToLoad):t.loadSteeringManifest(e)},r)}}])}(Ee);function xl(e,t,r,n){e&&Object.keys(t).forEach(function(i){var a=e.filter(function(e){return e.groupId===i}).map(function(e){var a=ie({},e);return a.details=void 0,a.attrs=new wn(a.attrs),a.url=a.attrs.URI=Ml(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[i],a.attrs["PATHWAY-ID"]=n,a});e.push.apply(e,I(a))})}function Ml(e,t,r,n){if(t){var i=n[r];if(i){var a=i[t];if(a)return a}}var s=n.HOST,o=n.PARAMS,l=new self.URL(e);return s&&(l.hostname=s),o&&Object.keys(o).sort().forEach(function(e){e&&or(l,e,o[e])}),l.href}var Fl=function(){return h(function e(){c(this,e),this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new ia,this.error=void 0,this.ok=void 0},[{key:"errored",get:function(){return this.error},set:function(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}},{key:"hasListeners",get:function(){return this.emitter.eventNames().length>0}},{key:"resolved",get:function(){return this.ok}},{key:"resolve",value:function(){this.ok=!0,this.emitter.emit("resolved")}},{key:"useable",get:function(){var e=this;return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise(function(t,r){e.emitter.on("error",r),e.emitter.on("resolved",t)})}},{key:"reset",value:function(){this.emitter.removeAllListeners();var e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}])}(),Nl=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,[r])).data=void 0,e.error||(e.error=new Error(r)),n.data=e,e.err=e.error,n}return y(t,e),h(t)}(O(Error)),Ul=function(e){function t(e){var r;return c(this,t),(r=u(this,t,["eme",e.logger])).hls=void 0,r.config=void 0,r.media=null,r.mediaResolved=void 0,r.keyFormatPromise=null,r.keySystemAccessPromises={},r.sessionSetupByUri={},r.mediaKeySessions=[],r.activeKeys={},r.mediaKeys=null,r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.onMediaEncrypted=function(e){var t=e.initDataType,n=e.initData,i='"'.concat(e.type,'" event: init data type: "').concat(t,'"');if(r.log(i),null!==n){if(!r.keyFormatPromise){var a=Object.keys(r.keySystemAccessPromises);a.length||(a=Xn(r.config));var s=a.map(zn).filter(function(e){return!!e});r.keyFormatPromise=r.getKeyFormatPromise(s)}r.keyFormatPromise.then(function(a){var s,o,l=Wn(a),u=r.activeLevelKeys();if(l===jn.FAIRPLAY&&"sinf"===t)try{var c=$e(new Uint8Array(n)),d=St(Qe(JSON.parse(c).sinf));if(!d)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");s=new Uint8Array(d.subarray(8,24))}catch(k){return void r.warn("".concat(i," Failed to parse sinf: ").concat(k))}else if(l===jn.PLAYREADY)s=Jn(new Uint8Array(n));else if(l===jn.WIDEVINE){var h=Pt(n).filter(function(e){return e.systemId===Yn});if(h.length){var f,v=h[0];s=null!=(f=v.kids)&&f.length?v.kids[0]:null}}if(s)for(var g=ze(s),p=0;p<u.length;p++){var y=u[p];if(y.keyId&&(On(s,y.keyId)||-1!==y.uri.replace(/-/g,"").indexOf(g))){y.pssh||(y.scheme=t,y.pssh=new Uint8Array(n),y.keyId=s,ei.setKeyIdForUri(y.uri,s)),o=r.getSessionForKey(y,"encrypted-event-key-match");break}}if(!o){var m,E;if(u.length)return(m=u[0]).scheme||(m.scheme=t),(E=u[0]).pssh||(E.pssh=new Uint8Array(n)),r.getSessionForKey(u[0],"encrypted-event-no-match");if(s)throw new Error("Key ID ".concat(ze(s)," not encountered in playlist"));r.log('Ignoring "'.concat(e.type,'" event - could not determine keyId'))}return o}).catch(function(e){return r.handleError(e)})}},r.onWaitingForKey=function(e){r.log('"'.concat(e.type,'" event'))},r.hls=e,r.config=e.config,r.registerListeners(),r}return y(t,e),h(t,[{key:"destroy",value:function(){this.onDestroying(),this.onMediaDetached();var e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHED,this.onMediaDetached,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHED,this.onMediaDetached,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.DESTROYING,this.onDestroying,this))}},{key:"attemptKeySystemAccess",value:function(e){var t=this;if(!this.hls)return Promise.reject(new Error("destroyed"));var r=this.hls.levels,n=function(e,t,r){return!!e&&r.indexOf(e)===t},i=r.map(function(e){return e.audioCodec}).filter(n),a=r.map(function(e){return e.videoCodec}).filter(n);return i.length+a.length===0&&a.push("avc1.42e01e"),new Promise(function(r,n){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,i,a).then(function(e){return r({keySystem:o,mediaKeys:e})}).catch(function(t){e.length?s(e):n(t instanceof Nl?t:new Nl({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};s(e)})}},{key:"requestMediaKeySystemAccess",value:function(e,t){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var n="Configured requestMediaKeySystemAccess is not a function ".concat(r);return null===$n&&"http:"===self.location.protocol&&(n="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(n))}return r(e,t)}},{key:"getMediaKeysPromise",value:function(e,t,r){var n,i=this,a=function(e,t,r,n){var i;switch(e){case jn.FAIRPLAY:i=["cenc","sinf"];break;case jn.WIDEVINE:case jn.PLAYREADY:i=["cenc"];break;case jn.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(e))}return function(e,t,r,n){return[{initDataTypes:e,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map(function(e){return{contentType:"audio/mp4; codecs=".concat(e),robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null}}),videoCapabilities:r.map(function(e){return{contentType:"video/mp4; codecs=".concat(e),robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}})}]}(i,t,r,n)}(e,t,r,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(n=s)?void 0:n.keySystemAccess;if(!o){this.log('Requesting encrypted media "'.concat(e,'" key-system access with config: ').concat(mr(a))),o=this.requestMediaKeySystemAccess(e,a);var l=s=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(function(t){i.log('Failed to obtain access to key-system "'.concat(e,'": ').concat(t))}),o.then(function(t){i.throwIfDestroyed(),i.log('Access for key-system "'.concat(t.keySystem,'" obtained'));var r=i.fetchServerCertificate(e);i.log('Create media-keys for "'.concat(e,'"'));var n=l.mediaKeys=t.createMediaKeys().then(function(t){return i.log('Media-keys created for "'.concat(e,'"')),l.hasMediaKeys=!0,r.then(function(r){return r?i.setMediaKeysServerCertificate(t,e,r):t})});return n.catch(function(t){i.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(t))}),n})}return o.then(function(){return s.mediaKeys})}},{key:"getMediaKeySessionContext",value:function(e,t,r,n){for(var i=this.mediaKeySessions,a=' key-session "'.concat(e,'" keyId: ').concat(ze(r.keyId||[])," keyUri: ").concat(r.uri,' for "').concat(n,'"'),s=0;s<i.length;s++){var o=i[s];if(!o.initialized&&o.createdFor.levelKey.uri===r.uri)return this.log("Reusing".concat(a)),o}this.log("Creating".concat(a));var l=t.createSession(),u={keySystem:e,mediaKeys:t,mediaKeysSession:l,keyRequests:{},keyStatuses:{},createdFor:{levelKey:r,reason:n},initialized:!1};return i.push(u),u}},{key:"resetMediaKeys",value:function(){var e,t=null==(e=this.mediaKeySessions[0])?void 0:e.keySystem,r=this.keySystemAccessPromises[t];r&&(this.log("reset mediaKeys"),this.mediaKeys=null,r.hasMediaKeys=!1,delete r.mediaKeys,delete this.keySystemAccessPromises[t])}},{key:"updateKeySession",value:function(e,t,r){var n=e.mediaKeysSession;return this.log('Updating key-session "'.concat(n.sessionId,'" for keyId ').concat(ze(t.keyId||[]),"\n } (data length: ").concat(r.byteLength,")")),n.update(r)}},{key:"getSelectedKeySystemFormats",value:function(){var e=this;return Object.keys(this.keySystemAccessPromises).map(function(t){return{keySystem:t,hasMediaKeys:e.keySystemAccessPromises[t].hasMediaKeys}}).filter(function(e){return!!e.hasMediaKeys}).map(function(e){return zn(e.keySystem)}).filter(function(e){return!!e})}},{key:"getKeySystemAccess",value:function(e){var t=this;return this.getKeySystemSelectionPromise(e).then(function(e){var r=e.keySystem,n=e.mediaKeys;return t.attemptSetMediaKeys(r,n)})}},{key:"selectKeySystem",value:function(e){return this.getKeySystemSelectionPromise(e).then(function(e){var t=e.keySystem,r=zn(t);if(!r)throw new Error('Unable to find format for key-system "'.concat(t,'"'));return r})}},{key:"selectKeySystemFormat",value:function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: ".concat(e.sn," ").concat(e.type,": ").concat(e.level,") key formats ").concat(t.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}},{key:"getKeyFormatPromise",value:function(e){var t=Xn(this.config),r=e.map(Wn).filter(function(e){return!!e&&-1!==t.indexOf(e)});return this.selectKeySystem(r)}},{key:"loadClear",value:function(e,t,r){var n=this;if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(var i,a=function(){var i=t[s];if(e.cc<=i.cc&&(!$(e)||!$(i)||e.sn<i.sn)||!r&&s==o-1)return{v:n.selectKeySystemFormat(i).then(function(e){if(n.hls){i.setKeyFormat(e);var t=Wn(e);return t?n.getKeySystemAccess([t]):void 0}})}},s=0,o=t.length;s<o;s++)if(i=a())return i.v;if(this.config.requireKeySystemAccessOnStart){var l=Xn(this.config);if(l.length)return this.getKeySystemAccess(l)}}return null}},{key:"getKeyStatus",value:function(e){for(var t=this.mediaKeySessions,r=0;r<t.length;r++){var n=Bl(e,t[r]);if(n)return n}}},{key:"loadKey",value:function(e){var t=e.decryptdata,r=this.getKeyStatus(t);if("internal-error"===r){var n=Gl(r,t);return n.data.frag=e,this.error("".concat(n.message," (").concat(ze(t.keyId||[]),")")),Promise.reject(n)}var i=e.type,a=this.activeKeys,s=a[i];s&&!t.matches(s.decryptdata)&&(a.previous||(a.previous=[]),a.previous.push(s),delete a[i]),a[i]||(a[i]=e);for(var o=this.mediaKeySessions.length;o--;){var l=this.mediaKeySessions[o];if(t.keyId&&"expired"===l.keyStatuses[ze(t.keyId)])return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}},{key:"renewKeySession",value:function(e,t){var r=this;return this.resetMediaKeys(),this.removeSession(t).then(function(){return r.throwIfDestroyed(),r.updateUsablePromise(e,"expired")})}},{key:"updateUsablePromise",value:function(e,t,r){var n=this,i=this.getSessionForKey(e,t);return i.catch(function(e){return n.handleError(e,r)}),i.then(function(t){return e})}},{key:"getSessionForKey",value:function(e,t){var r=this,n=this.findContextForKey(e);if(void 0!==n)return Promise.resolve(n);var i,a=e.uri,s=this.sessionSetupByUri[a];i=void 0===s?this.resolveSessionForKey(e,t):s.catch(function(){}).then(function(){return r.throwIfDestroyed(),r.resolveSessionForKey(e,t)}),this.sessionSetupByUri[a]=i;var o=function(){r.sessionSetupByUri[a]===i&&delete r.sessionSetupByUri[a]};return i.then(o,o),i}},{key:"findContextForKey",value:function(e){for(var t=this.mediaKeySessions,r=t.length;r--;){var n=t[r];if(Bl(e,n))return n}}},{key:"resolveSessionForKey",value:function(e,t){var r=this;return this.getKeySystemForKeyPromise(e).then(function(n){var i=n.keySystem,a=n.mediaKeys;r.throwIfDestroyed();for(var s=r.mediaKeySessions.length;s--;){var o=r.mediaKeySessions[s];if(Bl(e,o))return o;var l=r.getUsableKeyPromise(o,e,t);if(l)return l}return r.attemptSetMediaKeys(i,a).then(function(){return r.throwIfDestroyed(),r.getMediaKeySessionContext(i,a,e,t)}).then(function(n){r.throwIfDestroyed();var i=e.scheme||"cenc",a=e.pssh?e.pssh.buffer:null;return r.generateRequestWithPreferredKeySession(n,e,i,a,t)})})}},{key:"getUsableKeyPromise",value:function(e,t,r){var n=e.keyRequests[t.uri];if(n)return this.log("Waiting for usable key (".concat(r," keyId: ").concat(function(e){if(e.keyFormat===Hn)return e.uri;if(null===e.keyId)throw new Error("keyId is null");return ze(e.keyId)}(t),' format: "').concat(t.keyFormat,'" URI: ').concat(t.uri,")")),n.useable.then(function(){return e})}},{key:"throwIfDestroyed",value:function(){if(!this.hls)throw new Error("invalid state")}},{key:"handleError",value:function(e,t){if(this.hls)if(e instanceof Nl){t&&(e.data.frag=t);var r=e.data.decryptdata;this.error("".concat(e.message).concat(r?" (".concat(ze(r.keyId||[]),")"):"")),this.hls.trigger(B.ERROR,e.data)}else this.error(e.message),this.hls.trigger(B.ERROR,{type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}},{key:"getKeySystemForKeyPromise",value:function(e){var t=Wn(e.keyFormat),r=t?[t]:Xn(this.config);return this.attemptKeySystemAccess(r)}},{key:"getKeySystemSelectionPromise",value:function(e){if(e.length||(e=Xn(this.config)),0===e.length)throw new Nl({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options ".concat(mr({drmSystems:this.config.drmSystems})));return this.attemptKeySystemAccess(e)}},{key:"activeLevelKeys",value:function(){var e=this.activeKeys,t=(e.previous||[]).map(function(e){return e.decryptdata});return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}},{key:"attemptSetMediaKeys",value:function(e,t){var r=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var n=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));var i=Promise.all(n).then(function(){return r.media?r.media.setMediaKeys(t):new Promise(function(e,n){r.mediaResolved=function(){if(r.mediaResolved=void 0,!r.media)return n(new Error("Attempted to set mediaKeys without media element attached"));r.mediaKeys=t,r.media.setMediaKeys(t).then(e).catch(n)}})});return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(function(){r.log('Media-keys set for "'.concat(e,'"')),n.push(i),r.setMediaKeysQueue=r.setMediaKeysQueue.filter(function(e){return-1===n.indexOf(e)})})}},{key:"filterInitData",value:function(e,t,r,n,i){var a,s=null==(a=this.config.drmSystems)||null==(a=a[e.keySystem])?void 0:a.generateRequest;if(s)try{var o=s.call(this.hls,r,n,ie({},e,{decryptdata:t,reason:i}),i);if(!o)throw new Error("Invalid response from configured generateRequest filter");t.scheme=o.initDataType?o.initDataType:"cenc";var l=o.initData?o.initData:null;return t.pssh=l?new Uint8Array(l):null,o}catch(c){var u;if(this.warn(c.message),null!=(u=this.hls)&&u.config.debug)throw c}return{initDataType:r,initData:n}}},{key:"generateRequestWithPreferredKeySession",value:function(e,t,r,n,i){var a=this,s=this.getUsableKeyPromise(e,t,i);if(s)return s;var o=this.filterInitData(e,t,r,n,i);if(o&&(n=o.initData?o.initData:null,r=o.initDataType),null===n)return i.startsWith("encrypted-event")?Promise.reject(new Error('missing initialization data for "'.concat(i,'"'))):(this.log('Skipping key-session request for "'.concat(i,'" (no initData)')),Promise.resolve(e));var l=t.uri,u=new Fl;e.keyRequests[l]=u;var c=function(r){var n=e.mediaKeysSession;if(n){var i=r.messageType,s=r.message;u.status=i,a.log('"'.concat(i,'" message event for session "').concat(n.sessionId,'" message size: ').concat(s.byteLength)),"license-request"===i||"license-renewal"===i?a.renewLicense(e,t,s).catch(function(t){u.errored=t,u.hasListeners||a.handleError(t),a.removeSession(e)}):"license-release"===i?e.keySystem===jn.FAIRPLAY&&a.updateKeySession(e,t,Nn("acknowledged")).then(function(){return a.removeSession(e)}).catch(function(e){return a.handleError(e)}):a.warn('unhandled media key message type "'.concat(i,'"'))}else{var o=new Error("invalid state");u.errored=o}};u.onmessage=c,Fi(e.mediaKeysSession,"message",c);return this.generateRequest(e,t,r,n,i,!1)}},{key:"generateRequest",value:function(e,t,r,n,i,a){var s=this;if(a){var o=this.filterInitData(e,t,r,n,i);o&&(n=o.initData?o.initData:n,r=o.initDataType)}var l=t.uri,u=e.keyRequests[l],c=ze(t.keyId||[]),d=function(e){var r;e.startsWith("usable")?u.resolve():"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=Gl(e,t):"expired"===e?r=new Error("key expired (keyId: ".concat(c,")")):"released"===e?r=new Error("key released"):"status-pending"===e||s.warn('unhandled key status change "'.concat(e,'" (keyId: ').concat(c,")")),r&&(u.errored=r,u.hasListeners||s.handleError(r))},h=function(r){if(e.mediaKeysSession){var n=e.keyStatuses=s.getKeyStatuses(e);if(Object.keys(n).some(function(e){return"status-pending"!==n[e]})){for(var i=s.activeLevelKeys(),a=0;a<i.length;a++){var o=ze(i[a].keyId||[]);if("expired"===n[o]){var l;s.log("Expired key ".concat(mr(n),' in key-session "').concat(null==(l=e.mediaKeysSession)?void 0:l.sessionId,'"')),s.renewKeySession(t,e).catch(function(e){return s.handleError(e)});break}}var h=n[c];if(h)d(h);else{var f;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(f=e.keyStatusTimeouts)[c]||(f[c]=self.setTimeout(function(){var r;if(e.mediaKeysSession){var n,i=s.getKeyStatus(t);if(i&&"status-pending"!==i)return s.log("No status for keyId ".concat(c,' in key-session "').concat(null==(n=e.mediaKeysSession)?void 0:n.sessionId,'". Using session key-status ').concat(i," from other session.")),d(i);s.log("key status for ".concat(c,' in key-session "').concat(null==(r=e.mediaKeysSession)?void 0:r.sessionId,'" timed out after ').concat(1e3,"ms")),d(h="internal-error")}},1e3)),s.log("No status for keyId ".concat(c," (").concat(mr(n),")."))}}}else{var v=new Error("invalid state");u.errored=v}};u.onkeystatuseschange=h,Fi(e.mediaKeysSession,"keystatuseschange",h);var f=u.useable;return this.log('Generating key-session request for "'.concat(i,'" keyId: ').concat(c," URI: ").concat(l," (init data type: ").concat(r," length: ").concat(n.byteLength,")")),u.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(r,n).then(function(){var t;u.status="generated",s.log('Request generated for key-session "'.concat(null==(t=e.mediaKeysSession)?void 0:t.sessionId,'" keyId: ').concat(c," URI: ").concat(l))}).catch(function(e){throw s.log("mediaKeysSession.generateRequest failed: ".concat(e)),new Nl({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},"Error generating key-session request: ".concat(e))}).then(function(){return f}).catch(function(t){var r;s.log("mediaKeysSession.generateRequest failed: ".concat(t));var n=null==(r=t.data)?void 0:r.details;return n!==U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&n!==U.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(e.keyStatuses).some(function(t){return"usable"===e.keyStatuses[t]})?s.removeSession(e).then(function(){throw t}):(s.handleError(t),e)}).then(function(){return e})}},{key:"getKeyStatuses",value:function(e){var t=this,r={},n=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach(function(i,a){if("string"==typeof a&&"object"===_(i)){var s=a;a=i,i=s}var o="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(e.keySystem===jn.PLAYREADY&&16===o.length){var l=ze(o);r[l]=i,Un(o)}var u=ze(o);t.log('key status change "'.concat(i,'" for keyStatuses keyId: ').concat(u,' key-session "').concat(n,'"')),r[u]=i}),r}},{key:"fetchServerCertificate",value:function(e){var t=this.config,r=new(0,t.loader)(t),n=function(e,t){var r=t.drmSystems,n=null==r?void 0:r[e];if(n)return n.serverCertificateUrl}(e,t);return n?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise(function(i,a){var s={type:q.SERVER_CERTIFICATE,responseType:"arraybuffer",url:n},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,n){i(e.data)},onError:function(t,r,i,o){a(new Nl({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:se({url:s.url,data:void 0},t)},'"'.concat(e,'" certificate request failed (').concat(n,"). Status: ").concat(t.code," (").concat(t.text,")")))},onTimeout:function(t,r,i){a(new Nl({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:{url:s.url,data:void 0}},'"'.concat(e,'" certificate request timed out (').concat(n,")")))},onAbort:function(e,t,r){a(new Error("aborted"))}};r.load(s,l,u)})):(this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]')),Promise.resolve())}},{key:"setMediaKeysServerCertificate",value:function(e,t,r){var n=this;return new Promise(function(i,a){e.setServerCertificate(r).then(function(a){n.log("setServerCertificate ".concat(a?"success":"not supported by CDM"," (").concat(r.byteLength,') on "').concat(t,'"')),i(e)}).catch(function(e){a(new Nl({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}},{key:"renewLicense",value:function(e,t,r){var n=this;return this.requestLicense(e,t,new Uint8Array(r)).then(function(r){return n.updateKeySession(e,t,new Uint8Array(r)).catch(function(e){throw new Nl({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)})})}},{key:"unpackPlayReadyKeyMessage",value:function(e,t){var r=$e(new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var n=(new DOMParser).parseFromString(r,"application/xml"),i=n.querySelectorAll("HttpHeader");if(i.length>0)for(var a,s=0,o=i.length;s<o;s++){var l,u,c=null==(l=(a=i[s]).querySelector("name"))?void 0:l.textContent,d=null==(u=a.querySelector("value"))?void 0:u.textContent;c&&d&&e.setRequestHeader(c,d)}var h=n.querySelector("Challenge"),f=null==h?void 0:h.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return Nn(atob(f))}},{key:"setupLicenseXHR",value:function(e,t,r,n,i){var a=this,s=this.config.licenseXhrSetup;return s?Promise.resolve().then(function(){return a.throwIfDestroyed(),s.call(a.hls,e,t,se(se({},r),{},{decryptdata:n}),i)}).catch(function(o){if(!r.mediaKeysSession)throw o;return e.open("POST",t,!0),s.call(a.hls,e,t,se(se({},r),{},{decryptdata:n}),i)}).then(function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||i}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}},{key:"requestLicense",value:function(e,t,r){var n=this;return new Promise(function(i,a){var s=function(e,t){var r=t.drmSystems,n=t.widevineLicenseUrl,i=null==r?void 0:r[e];if(i)return i.licenseUrl;if(e===jn.WIDEVINE&&n)return n}(e.keySystem,n.config);if(!s)return a(new Error('no license server URL configured for key-system "'.concat(e.keySystem,'"')));var o=e.keyRequests[t.uri];if(!o)return a(new Error("License emitter removed"));n.log("Sending license request to URL: ".concat(s));var l=n.config.keyLoadPolicy.default,u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=function(){if(!n.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===u.readyState)if(200===u.status){o.requestErrors=[];var c=u.response;n.log("License received ".concat(c instanceof ArrayBuffer?c.byteLength:c));var d=n.config.licenseResponseCallback;if(d)try{c=d.call(n.hls,u,s,se(se({},e),{},{decryptdata:t}))}catch(g){n.error(g)}i(c)}else{var h=l.errorRetry,f=h?h.maxNumRetry:0;if(o.requestErrors.push({status:u.status,message:u.statusText}),o.requestErrors.length>f||u.status>=400&&u.status<500)a(new Nl({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:u,response:{url:s,data:void 0,code:u.status,text:u.statusText}},"License Request XHR failed (".concat(s,"). Status: ").concat(u.status," (").concat(u.statusText,")")));else{var v=f-o.requestErrors.length;n.warn("Retrying license request, ".concat(v," attempts left")),n.requestLicense(e,t,r).then(i,a)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=u,n.setupLicenseXHR(u,s,e,t,r).then(function(t){var r=t.xhr,i=t.licenseChallenge;e.keySystem==jn.PLAYREADY&&(i=n.unpackPlayReadyKeyMessage(r,i)),r.send(i)}).catch(a)})}},{key:"onDestroying",value:function(){this.unregisterListeners(),this._clear()}},{key:"onMediaAttached",value:function(e,t){if(this.config.emeEnabled){var r=t.media;this.media=r,Fi(r,"encrypted",this.onMediaEncrypted),Fi(r,"waitingforkey",this.onWaitingForKey);var n=this.mediaResolved;n?n():this.mediaKeys=r.mediaKeys}}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(Ni(e,"encrypted",this.onMediaEncrypted),Ni(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}},{key:"_clear",value:function(){var e,r=this;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};var n=this.mediaResolved;if(n&&n(),this.mediaKeys||this.mediaKeySessions.length){var i=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,ei.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map(function(e){return r.removeSession(e)}).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch(function(e){r.log("Could not clear media keys: ".concat(e)),r.hls&&r.hls.trigger(B.ERROR,{type:N.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: ".concat(e))})}))||Promise.resolve())).catch(function(e){r.log("Could not close sessions and clear media keys: ".concat(e)),r.hls&&r.hls.trigger(B.ERROR,{type:N.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: ".concat(e))})}).then(function(){s&&r.log("finished closing key sessions and clearing media keys")})}}},{key:"onManifestLoading",value:function(){this._clear(),this.keyFormatPromise=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var n=r.reduce(function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e},[]);this.log("Selecting key-system from session-keys ".concat(n.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(n),this.keyFormatPromise.catch(function(){})}}},{key:"removeSession",value:function(e){var t=this,r=e.mediaKeysSession;if(r){this.log('Remove licenses and keys and close session "'.concat(r.sessionId,'"')),Object.keys(e.keyRequests).forEach(function(t){var n=e.keyRequests[t];n.onmessage&&r.removeEventListener("message",n.onmessage),n.onkeystatuseschange&&r.removeEventListener("keystatuseschange",n.onkeystatuseschange),n.reset(),e.keyRequests[t]=void 0}),e.mediaKeysSession=void 0;var n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);var i=e.keyStatusTimeouts;i&&Object.keys(i).forEach(function(e){return self.clearTimeout(i[e])});var a=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(function(e){return"persistent-license"===e})))}(this.config.drmSystemOptions)?new Promise(function(e,t){self.setTimeout(function(){return t(new Error("MediaKeySession.remove() timeout"))},8e3),r.remove().then(e).catch(t)}):Promise.resolve();return a.catch(function(e){t.log("Could not remove session: ".concat(e)),t.hls&&t.hls.trigger(B.ERROR,{type:N.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: ".concat(e))})}).then(function(){return r.close()}).then(function(){return r.closed}).catch(function(e){t.log("Could not close session: ".concat(e)),t.hls&&t.hls.trigger(B.ERROR,{type:N.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: ".concat(e))})})}return Promise.resolve()}}])}(Ee);function Bl(e,t){var r=e.keyId,n=t.mediaKeysSession;if(r&&n){var i=t.mediaKeysSession.keyStatuses;if(i.size)return i.has(r)?i.get(r):t.keyStatuses[ze(r)]}}function Gl(e,t){var r="output-restricted"===e,n=r?U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:U.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Nl({type:N.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'.concat(e,'"'))}Ul.CDMCleanupPromise=void 0;var jl=function(){return h(function e(t){c(this,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=t,this.registerListeners()},[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"registerListeners",value:function(){this.hls.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(B.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListeners",value:function(){this.hls.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(B.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"destroy",value:function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&"function"==typeof n.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}},{key:"onMediaDetaching",value:function(){this.media=null}},{key:"checkFPS",value:function(e,t,r){var n=performance.now();if(t){if(this.lastTime){var i=n-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/i,l=this.hls;if(l.trigger(B.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(B.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}},{key:"checkFPSInterval",value:function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}])}(),Kl=function(){if(null!=Gn&&Gn.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function n(e){return r(t,e)}function i(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];for(var i=1;i<arguments.length;i++){var a=arguments[i];for(var s in a)e[s]=a[s]}return e}function a(t,a,s){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var u="",c=!1,d=t,h=a,f=s,v=null,g="",p=!0,y="auto",m="start",E=50,k="middle",S=50,T="middle";Object.defineProperty(o,"id",i({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",i({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",i({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",i({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",i({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",i({},l,{get:function(){return v},set:function(e){v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",i({},l,{get:function(){return g},set:function(t){var n=function(t){return r(e,t)}(t);if(!1===n)throw new SyntaxError("An invalid or illegal string was specified.");g=n,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",i({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",i({},l,{get:function(){return y},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",i({},l,{get:function(){return m},set:function(e){var t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",i({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return k},set:function(e){var t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");k=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",i({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",i({},l,{get:function(){return T},set:function(e){var t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),Hl=function(){return h(function e(){c(this,e)},[{key:"decode",value:function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}])}();function Vl(e){function t(e,t,r,n){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(n||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var ql=function(){return h(function e(){c(this,e),this.values=Object.create(null)},[{key:"set",value:function(e,t){this.get(e)||""===t||(this.values[e]=t)}},{key:"get",value:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}},{key:"has",value:function(e){return e in this.values}},{key:"alt",value:function(e,t,r){for(var n=0;n<r.length;++n)if(t===r[n]){this.set(e,t);break}}},{key:"integer",value:function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}},{key:"percent",value:function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}])}();function Wl(e,t,r,n){var i=n?e.split(n):[e];for(var a in i)if("string"==typeof i[a]){var s=i[a].split(r);if(2===s.length)t(s[0],s[1])}}var Yl=new Kl(0,0,""),zl="middle"===Yl.align?"middle":"center";function Xl(e,t,r){var n=e;function i(){var t=Vl(e);if(null===t)throw new Error("Malformed timestamp: "+n);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=i(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+n);e=e.slice(3),a(),t.endTime=i(),a(),function(e,t){var n=new ql;Wl(e,function(e,t){var i;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){n.set(e,r[a].region);break}break;case"vertical":n.alt(e,t,["rl","lr"]);break;case"line":i=t.split(","),n.integer(e,i[0]),n.percent(e,i[0])&&n.set("snapToLines",!1),n.alt(e,i[0],["auto"]),2===i.length&&n.alt("lineAlign",i[1],["start",zl,"end"]);break;case"position":i=t.split(","),n.percent(e,i[0]),2===i.length&&n.alt("positionAlign",i[1],["start",zl,"end","line-left","line-right","auto"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start",zl,"end","left","right"])}},/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");var i=n.get("line","auto");"auto"===i&&-1===Yl.line&&(i=-1),t.line=i,t.lineAlign=n.get("lineAlign","start"),t.snapToLines=n.get("snapToLines",!0),t.size=n.get("size",100),t.align=n.get("align",zl);var a=n.get("position","auto");"auto"===a&&50===Yl.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function Ql(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var $l=function(){return h(function e(){c(this,e),this.state="INITIAL",this.buffer="",this.decoder=new Hl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0},[{key:"parse",value:function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=Ql(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var n=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),n}function n(e){Wl(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var i="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var a=(i=r()).match(/^()?WEBVTT([ \t].*)?$/);if(null==a||!a[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var s=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:i=r(),t.state){case"HEADER":/:/.test(i)?n(i):i||(t.state="ID");continue;case"NOTE":i||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){t.state="NOTE";break}if(!i)continue;if(t.cue=new Kl(0,0,""),t.state="CUE",-1===i.indexOf("--\x3e")){t.cue.id=i;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Xl(i,t.cue,t.regionList)}catch(l){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var o=-1!==i.indexOf("--\x3e");if(!i||o&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=i;continue;case"BADCUE":i||(t.state="ID")}}}catch(l){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}},{key:"flush",value:function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}])}();function Jl(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var Zl=/\r\n|\n\r|\n|\r/g,eu="Missing initPTS for VTT ";function tu(e,t,r){return Jl(e.toString())+Jl(t.toString())+Jl(r)}function ru(e,t,r,n,i,a,s){var o,l=new $l,u=Ge(new Uint8Array(e)).trim().replace(Zl,"\n").split("\n"),c=[],d=t?function(e){return ls(e,9e4,1/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1))}(t.baseTime,t.timescale):0,h="00:00.000",f=0,v=0,g=!1,p=!0;l.oncue=function(e){var a=r[n],s=r.ccOffset,l=(f-d)/9e4;if(g){if(null!=a&&a.new&&(s=r.ccOffset=a.start),l){if(!t)return void(o=new Error(eu+"MPEGTS"));s=l-r.presentationOffset}}else{if(!t)return void(o=new Error(eu+"without X-TIMESTAMP-MAP"));s=-t.baseTime/t.timescale}var u=e.endTime-e.startTime,h=vs(9e4*(e.startTime+s-v),9e4*i)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+u,0);var p=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(p)),e.id?n&&(e.id="hlsjscc".concat(n,"_").concat(e.id)):e.id=tu(e.startTime,e.endTime,p),e.endTime>0&&c.push(e)},l.onparsingerror=function(e){o=e},l.onflush=function(){o?s(o):a(c)},u.forEach(function(e){if(p){if(e.startsWith("X-TIMESTAMP-MAP=")){p=!1,g=!0,e.slice(16).split(",").forEach(function(e){e.startsWith("LOCAL:")?h=e.slice(6):e.startsWith("MPEGTS:")&&(f=parseInt(e.slice(7)))});try{v=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(x(t)&&x(r)&&x(n)&&x(i)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*r,t+=6e4*n,t+36e5*i}(h)/1e3}catch(t){o=t}return}""===e&&(p=!1)}l.parse(e+"\n")}),l.flush()}var nu="stpp.ttml.im1t",iu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,au=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,su={left:"start",center:"center",right:"end",start:"start",end:"end"};function ou(e,t,r,n){var i=dt(new Uint8Array(e),["mdat"]);if(0!==i.length){var a=i.map(function(e){return Ge(e)}),s=function(e,t){return ls(e,t,1/(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1),arguments.length>3&&void 0!==arguments[3]&&arguments[3])}(t.baseTime,1,t.timescale);try{a.forEach(function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml"),n=r.getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");var i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(i).reduce(function(e,t){return e[t]=n.getAttribute("ttp:".concat(t))||i[t],e},{});!n.getAttribute("ttp:tickRate")&&n.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));var s="preserve"!==n.getAttribute("xml:space"),o=uu(lu(n,"styling","style")),l=uu(lu(n,"layout","region")),u=lu(n,"body","[begin]");return[].map.call(u,function(e){var r=cu(e,s);if(!r||!e.hasAttribute("begin"))return null;var n=fu(e.getAttribute("begin"),a),i=fu(e.getAttribute("dur"),a),u=fu(e.getAttribute("end"),a);if(null===n)throw hu(e);if(null===u){if(null===i)throw hu(e);u=n+i}var c=new Kl(n-t,u-t,r);c.id=tu(c.startTime,c.endTime,c.text);var d=function(e,t,r){var n="http://www.w3.org/ns/ttml#styling",i=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;s&&r.hasOwnProperty(s)&&(i=r[s]);return a.reduce(function(r,a){var s=du(t,n,a)||du(e,n,a)||du(i,n,a);return s&&(r[a]=s),r},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),h=d.textAlign;if(h){var f=su[h];f&&(c.lineAlign=f),c.align=h}return ie(c,d),c}).filter(function(e){return null!==e})}(e,s))})}catch(o){n(o)}}else n(new Error("Could not parse IMSC1 mdat"))}function lu(e,t,r){var n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function uu(e){return e.reduce(function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function cu(e,t){return[].slice.call(e.childNodes).reduce(function(e,r,n){var i;return"br"===r.nodeName&&n?e+"\n":null!=(i=r.childNodes)&&i.length?cu(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}function du(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function hu(e){return new Error("Could not parse ttml timestamp ".concat(e))}function fu(e,t){if(!e)return null;var r=Vl(e);return null===r&&(iu.test(e)?r=function(e,t){var r=iu.exec(e),n=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+n/t.frameRate}(e,t):au.test(e)&&(r=function(e,t){var r=au.exec(e),n=Number(r[1]);switch(r[2]){case"h":return 3600*n;case"m":return 60*n;case"ms":return n/1e3;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}(e,t))),r}function vu(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"disabled",a=e.ownerDocument.createElement("track");return a.kind=t,a.label=r,n&&(a.srclang=n),a.src="data:,WEBVTT",a.track.mode=i,e.appendChild(a),a}function gu(e){return e.forced&&(Ft.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Mt))?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function pu(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: ".concat(t))}catch(Ry){Le.debug("[texttrack-utils]: ".concat(Ry));try{var n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(i){Le.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(i))}}"disabled"===r&&(e.mode=r)}function yu(e,t,r,n){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,r){var n=[],i=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;var n,i=0,a=r;for(;i<=a;)if(t<e[n=Math.floor((a+i)/2)].startTime)a=n-1;else{if(!(t>e[n].startTime&&i<r))return n;i=n+1}return e[i].startTime-t<t-e[a].startTime?i:a}(e,t);if(i>-1)for(var a=i,s=e.length;a<s;a++){var o=e[a];if(o.startTime>=t&&o.endTime<=r)n.push(o);else if(o.startTime>r)return n}return n}(e.cues,t,r),s=0;s<a.length;s++)n&&!n(a[s])||e.removeCue(a[s]);"disabled"===i&&(e.mode=i)}var mu=function(e){function t(e){var r;return c(this,t),(r=u(this,t,[e,"subtitle-track-controller"])).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){var e,t=-1,n=!1;if(r.currentTrack){var i,a=null==(i=r.currentTrack.trackNode)?void 0:i.track.mode;"showing"===a?(t=r.trackId,n=!0):"hidden"===a&&(t=r.trackId)}if(!n)for(var s=0;s<r.tracksInGroup.length;s++){var o,l=null==(o=r.tracksInGroup[s].trackNode)?void 0:o.track.mode;if("showing"===l){t=s;break}t<0&&"hidden"===l&&(t=s)}if(t>-1)r._subtitleDisplay="showing"===(null==(e=r.tracksInGroup[t].trackNode)?void 0:e.track.mode);r.setSubtitleTrack(t,!0)}},r.registerListeners(),r}return y(t,e),h(t,[{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,R(t,"destroy",this)([])}},{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"registerListeners",value:function(){var e=this.hls;e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(B.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVEL_LOADING,this.onLevelLoading,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(B.ERROR,this.onError,this)}},{key:"createTracksInGroup",value:function(){var e,t=this;if(this.media&&this.hls.config.renderTextTracksNatively){this.tracksInGroup.forEach(function(e){e.trackNode||(e.trackNode=vu(t.media,gu(e),e.name,e.lang))});var r=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;"disabled"===(null==r?void 0:r.mode)&&(r.mode=this._subtitleDisplay?"showing":"hidden")}}},{key:"onMediaAttached",value:function(e,t){var r=t.media;this.media=r;var n=this.trackId;this.queuedDefaultTrack>-1&&(n=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(n),this.createTracksInGroup(),this.useTextTrackPolling=!(r.textTracks&&"onchange"in r.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):r.textTracks.addEventListener("change",this.asyncPollTrackChange)}},{key:"pollTrackChange",value:function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}},{key:"onMediaDetaching",value:function(e,t){var r=this.media;if(r){var n=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,n||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(function(e){var t=e.trackNode;t&&(t.track.mode="hidden",t.remove(),e.trackNode=void 0)})}}},{key:"onManifestLoading",value:function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.subtitleTracks}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r=t.id,n=t.groupId,i=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===n){var s=a.details;a.details=t.details,this.log("Subtitle track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(n," loaded [").concat(i.startSN,"-").concat(i.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:".concat(r," and group:").concat(n," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this,r=this.hls.levels[e];if(r){var n=r.subtitleGroups||null,i=this.groupIds,a=this.currentTrack;if(!n||(null==i?void 0:i.length)!==(null==n?void 0:n.length)||null!=n&&n.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=n;var s=[];if(this.tracks.forEach(function(e){(e.textCodec===nu?t.hls.config.enableIMSC1:t.hls.config.enableWebVTT)&&(!n||n.indexOf(e.groupId)>-1?(e.id=s.length,s.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))}),s.length===this.tracksInGroup.length){for(var o=!1,l=0;l<s.length;l++)if(s[l]!==this.tracksInGroup[l]){o=!0;break}if(!o)return}s.length&&this.selectDefaultTrack&&!s.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),this.tracksInGroup=s,this.trackId=-1,this.currentTrack=null;var u=this.hls.config.subtitlePreference;if(!a&&u){this.selectDefaultTrack=!1;var c=Tr(u,s);if(c>-1)a=s[c];else{var d=Tr(u,this.tracks);a=this.tracks[d]}}var h=this.findTrackId(a);-1===h&&a&&(h=this.findTrackId(null));var f={subtitleTracks:s};this.log("Updating subtitle tracks, ".concat(s.length,' track(s) found in "').concat(null==n?void 0:n.join(","),'" group-id')),this.hls.trigger(B.SUBTITLE_TRACKS_UPDATED,f),this.setSubtitleTrack(h),this.createTracksInGroup()}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,n=0;n<t.length;n++){var i=t[n];if((!r||i.default)&&(r||e)&&(!e||br(i,e)))return n}if(e){for(var a=0;a<t.length;a++){var s=t[a];if(Cs(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return a}for(var o=0;o<t.length;o++){var l=t[o];if(Cs(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===q.SUBTITLE_TRACK&&t.context.id===this.trackId&&Ir(t.context.groupId,this.groupIds)&&this.checkRetry(t)}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}},{key:"setSubtitleOption",value:function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1,!0),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var r=this.currentTrack;if(r&&br(e,r))return r;var n=Tr(e,this.tracksInGroup);if(n>-1){var i=this.tracksInGroup[n];return this.setSubtitleTrack(n,!0),i}if(r)return null;var a=Tr(e,t);if(a>-1)return t[a]}}return null}},{key:"loadPlaylist",value:function(e){R(t,"loadPlaylist",this)([]),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}},{key:"loadingPlaylist",value:function(e,r){R(t,"loadingPlaylist",this)([e,r]);var n=e.id,i=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading subtitle ".concat(n,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(i).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(B.SUBTITLE_TRACK_LOADING,{url:a,id:n,groupId:i,deliveryDirectives:r||null,track:e})}},{key:"toggleTrackModes",value:function(){var e=this;if(this.media&&this.hls.config.renderTextTracksNatively){var t=this.currentTrack;this.tracksInGroup.forEach(function(r){if(r.trackNode){var n=r===t?e._subtitleDisplay?"showing":"hidden":"disabled",i=r.trackNode.track;i.mode!==n&&(i.mode=n)}})}}},{key:"setSubtitleTrack",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=r.length||!x(e))this.warn("Invalid subtitle track id: ".concat(e));else{var n=this.currentTrack,i=r[e]||null;if(this.trackId=e,this.currentTrack=i,t&&this.toggleTrackModes(),i){var a=!!i.details&&!i.details.live;if(i!==n||!a){this.log("Switching to subtitle-track ".concat(e)+(i?' "'.concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId):""));var s=i.id,o=i.groupId,l=void 0===o?"":o,u=i.name,c=i.type,d=i.url;this.hls.trigger(B.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:c,url:d});var h=this.switchParams(i.url,null==n?void 0:n.details,i.details);this.loadPlaylist(h)}}else n&&this.hls.trigger(B.SUBTITLE_TRACK_SWITCH,{id:e})}}}])}(Ps),Eu=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,["gap-controller",e.logger])).hls=void 0,n.fragmentTracker=void 0,n.media=null,n.mediaSource=void 0,n.nudgeRetry=0,n.skipRetry=0,n.stallReported=!1,n.stalled=null,n.moved=!1,n.seeking=!1,n.buffered={},n.lastCurrentTime=void 0,n.ended=0,n.waiting=0,n.onMediaPlaying=function(){n.ended=0,n.waiting=0},n.onMediaWaiting=function(){var e;null!=(e=n.media)&&e.seeking||(n.waiting=self.performance.now(),n.tick())},n.onMediaEnded=function(){var e;n.hls&&(n.ended=(null==(e=n.media)?void 0:e.currentTime)||1,n.hls.trigger(B.MEDIA_ENDED,{stalled:!1}))},n.hls=e,n.fragmentTracker=r,n.lastCurrentTime=n.getCurrentTime(),n.registerListeners(),n}return y(t,e),h(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"destroy",value:function(){R(t,"destroy",this)([]),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}},{key:"onMediaAttached",value:function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;Fi(r,"playing",this.onMediaPlaying),Fi(r,"waiting",this.onMediaWaiting),Fi(r,"ended",this.onMediaEnded)}},{key:"onMediaDetaching",value:function(e,t){this.clearInterval();var r=this.media;r&&(Ni(r,"playing",this.onMediaPlaying),Ni(r,"waiting",this.onMediaWaiting),Ni(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}},{key:"onBufferAppended",value:function(e,t){this.buffered=t.timeRanges}},{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}},{key:"getCurrentTime",value:function(){var e,t=(null==(e=this.hls)?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}},{key:"tick",value:function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}}},{key:"poll",value:function(e,t){var r,n,i=null==(r=this.hls)?void 0:r.config;if(i){var a=this.media;if(a){var s=a.seeking,o=this.seeking&&!s,l=!this.seeking&&s,u=a.paused&&!s||a.ended||0===a.playbackRate;if(this.seeking=s,e!==t)return t&&(this.ended=0),this.moved=!0,s||(this.skipRetry=this.nudgeRetry=0,i.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(u)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(B.MEDIA_ENDED,{stalled:!1})));if(kn.getBuffered(a).length){var c=kn.bufferInfo(a,e,0),d=this.fragmentTracker;d&&this.hls&&bu(c,e,d,this.hls);var h=c.nextStart||0;if(s&&d&&this.hls){var f=ku(this.hls.inFlightFragments,e),v=c.len>2,g=!h||f||h-e>2&&!d.getPartialFragment(e);if(v||g)return;this.moved=!1}var p=null==(n=this.hls)?void 0:n.latestLevelDetails;if(!this.moved&&null!==this.stalled&&d){if(!(c.len>0)&&!h)return;var y=Math.max(h,c.start||0)-e,m=!(null==p||!p.live)?2*p.targetduration:2,E=Tu(e,d);if(y>0&&(y<=m||E))return void(a.paused||this._trySkipBufferHole(E))}var k=i.detectStallWithCurrentTimeMs,S=self.performance.now(),T=this.waiting,b=this.stalled;if(null===b){if(!(T>0&&S-T<k))return void(this.stalled=S);b=this.stalled=T}var A=S-b;if(!s&&(A>=k||T&&this.moved)&&this.hls){var L;if("ended"===(null==(L=this.mediaSource)?void 0:L.readyState)&&(null==p||!p.live)&&Math.abs(e-((null==p?void 0:p.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(B.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return;if(a.currentTime!==e){var R=e;return e=a.currentTime,this.moved=!0,void this.log("currentTime changed ".concat(R," > ").concat(e))}}var I=kn.bufferInfo(a,e,i.maxBufferHole);this._tryFixBufferStall(I,A,e)}else this.skipRetry=this.nudgeRetry=0}}}}},{key:"stallResolved",value:function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(r),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(B.STALL_RESOLVED,{})}}},{key:"nudgeOnVideoHole",value:function(e,t){var r,n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&n&&n.length>1&&e>n.end(0)){var i=kn.bufferedInfo(kn.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){var a=kn.timeRangesToArray(n),s=kn.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=kn.bufferedInfo(a,e,0).bufferedIndex,l=a[s].end,u=a[s+1].start;if((-1===o||o>s)&&u-l<1&&e-l<2){var c=new Error("nudging playhead to flush pipeline after video hole. currentTime: ".concat(e," hole: ").concat(l," -> ").concat(u," buffered index: ").concat(o));this.warn(c.message),this.media.currentTime+=1e-6;var d=Tu(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);var h=kn.bufferInfo(this.media,e,0);this.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:d,buffer:h.len,bufferInfo:h})}}}}}},{key:"_tryFixBufferStall",value:function(e,t,r){var n,i,a=this.fragmentTracker,s=this.media,o=null==(n=this.hls)?void 0:n.config;if(s&&a&&o){var l=null==(i=this.hls)?void 0:i.latestLevelDetails,u=Tu(r,a);if(u||null!=l&&l.live&&r<l.fragmentStart)if(this._trySkipBufferHole(u)||!this.media)return;var c=e.buffered,d=this.adjacentTraversal(e,r);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}}},{key:"adjacentTraversal",value:function(e,t){var r=this.fragmentTracker,n=e.nextStart;if(r&&n){var i=r.getFragAtPos(t,W.MAIN),a=r.getFragAtPos(n,W.MAIN);if(i&&a)return a.sn-i.sn<2}return!1}},{key:"_reportStall",value:function(e){var t=this.hls,r=this.media,n=this.stallReported,i=this.stalled;if(!n&&null!==i&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @".concat(r.currentTime," due to low buffer (").concat(mr(e),")"));this.warn(a.message),t.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}},{key:"_trySkipBufferHole",value:function(e){var t=this.fragmentTracker,r=this.media,n=this.hls,i=null==n?void 0:n.config;if(!r||!t||!i)return 0;var a=r.currentTime,s=kn.bufferInfo(r,a,0);bu(s,a,t,n);var o=a<s.start?s.start:s.nextStart;if(o){var l=s.len<=i.maxBufferHole,u=s.len>0&&s.len<1&&r.readyState<3,c=o-a;if(c>0&&(l||u)){if(c>i.maxBufferHole){var d=!1;if(0===a){var h=t.getAppendedFrag(0,W.MAIN);h&&o<h.end&&(d=!0)}if(!d&&e){var f;if(null==(f=n.loadLevelObj)||!f.details)return 0;if(ku(n.inFlightFragments,o))return 0;for(var v=!1,g=e.end;g<o;){var p=Tu(g,t),y=p?p.duration:0;if(!(y>0)){v=!0;break}g+=y}if(v)return 0}}var m=i.nudgeMaxRetry,E=i.skipBufferHolePadding,k=++this.skipRetry>m,S=Math.max(o,a)+E;if(k||(this.warn("skipping hole, adjusting currentTime from ".concat(a," to ").concat(S)),this.moved=!0,r.currentTime=S),null==e||!e.gap||k){var T=new Error(k?"Playhead still not moving after seeking over buffer hole from ".concat(a," to ").concat(S," after ").concat(i.nudgeMaxRetry," attempts."):"fragment loaded with buffer holes, seeking from ".concat(a," to ").concat(S)),b={type:N.MEDIA_ERROR,details:U.BUFFER_SEEK_OVER_HOLE,fatal:k,error:T,reason:T.message,buffer:s.len,bufferInfo:s};e&&("fragment"in e?b.part=e:b.frag=e),n.trigger(B.ERROR,b)}return S}}return 0}},{key:"_tryNudgeBuffer",value:function(e){var t=this.hls,r=this.media,n=this.nudgeRetry,i=null==t?void 0:t.config;if(!r||!i)return 0;var a=r.currentTime;if(this.nudgeRetry++,n<i.nudgeMaxRetry){var s=a+(n+1)*i.nudgeOffset,o=new Error("Nudging 'currentTime' from ".concat(a," to ").concat(s));this.warn(o.message),r.currentTime=s,t.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{var l=new Error("Playhead still not moving while enough data buffered @".concat(a," after ").concat(i.nudgeMaxRetry," nudges"));this.error(l.message),t.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}])}(yn);function ku(e,t){var r=Su(e.main);if(r&&r.start<=t)return r;var n=Su(e.audio);return n&&n.start<=t?n:null}function Su(e){if(!e)return null;switch(e.state){case Gi:case Bi:case Yi:case zi:return null}return e.frag}function Tu(e,t){return t.getAppendedFrag(e,W.MAIN)||t.getPartialFragment(e)}function bu(e,t,r,n){var i=n.latestLevelDetails,a=Tu(t,r);if(Zi(n.config)&&!e.nextStart&&i&&a&&n.interstitialsManager){var s="type"in a?a:a.fragment,o=Mr(i,s.sn);(null==o?void 0:o.level)===s.level&&Ji(o,n.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}function Au(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Lu(e,t,r,n,i){var a=new e(t,r,"");try{a.value=n,i&&(a.type=i)}catch(s){a=new e(t,r,mr(i?se({type:i},n):n))}return a}var Ru=function(){var e=Au();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),Iu=function(){return h(function e(t){var r=this;c(this,e),this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){r.hls&&r.hls.trigger(B.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()},[{key:"destroy",value:function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}},{key:"_registerListeners",value:function(){var e=this.hls;e&&(e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media}},{key:"onMediaAttached",value:function(){var e,t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}},{key:"onMediaDetaching",value:function(e,t){this.media=null,!!t.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}},{key:"onManifestLoading",value:function(){this.dateRangeCuesAppended={}}},{key:"createTrack",value:function(e){return vu(e,"metadata","id3","","hidden")}},{key:"onFragParsingMetadata",value:function(e,t){if(this.media&&this.hls){var r=this.hls.config,n=r.enableEmsgMetadataCues,i=r.enableID3MetadataCues;if(n||i){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=Au();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==ga.emsg||n)&&i){var u=Ve(a[o].data),c=a[o].pts,d=c+a[o].duration;d>Ru&&(d=Ru),d-c<=0&&(d=c+.25);for(var h=0;h<u.length;h++){var f=u[h];if(!qe(f)){this.updateId3CueEnds(c,l);var v=Lu(s,c,d,f,l);v&&this.id3Track.track.addCue(v)}}}}}}}},{key:"updateId3CueEnds",value:function(e,t){var r,n=null==(r=this.id3Track)?void 0:r.track.cues;if(n)for(var i=n.length;i--;){var a=n[i];a.type===t&&a.startTime<e&&a.endTime===Ru&&(a.endTime=e)}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,n=t.endOffset,i=t.type,a=this.id3Track,s=this.hls;if(s){var o,l=s.config,u=l.enableEmsgMetadataCues,c=l.enableID3MetadataCues;if(a&&(u||c))o="audio"===i?function(e){return e.type===ga.audioId3&&c}:"video"===i?function(e){return e.type===ga.emsg&&u}:function(e){return e.type===ga.audioId3&&c||e.type===ga.emsg&&u},yu(a.track,r,n,o)}}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)}},{key:"onLevelPtsUpdated",value:function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}},{key:"updateDateRangeCues",value:function(e,t){var r=this;if(this.hls&&this.media){var n=this.hls.config,i=n.assetPlayerId,a=n.timelineOffset,s=n.enableDateRangeMetadataCues,o=n.interstitialsController;if(s){var l=Au();if(i&&a&&!o){var u=e.fragmentStart,c=e.fragmentEnd,d=this.assetCue;d?(d.startTime=u,d.endTime=c):l&&(d=this.assetCue=Lu(l,u,c,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(d.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(d),d.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var h,f=this.id3Track,v=e.dateRanges,g=Object.keys(v),p=this.dateRangeCuesAppended;if(f&&t)if(null!=(h=f.track.cues)&&h.length)for(var y,m=Object.keys(p).filter(function(e){return-1===g.indexOf(e)}),E=function(){var e=m[k],t=null==(y=p[e])?void 0:y.cues;delete p[e],t&&Object.keys(t).forEach(function(e){var n=t[e];if(n){n.removeEventListener("enter",r.onEventCueEnter);try{f.track.removeCue(n)}catch(i){}}})},k=m.length;k--;)E();else p=this.dateRangeCuesAppended={};var S=e.fragments[e.fragments.length-1];if(0!==g.length&&x(null==S?void 0:S.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var T=function(){var e=g[b],t=v[e],n=t.startTime,i=p[e],a=(null==i?void 0:i.cues)||{},s=(null==i?void 0:i.durationKnown)||!1,u=Ru,c=t.duration;if(t.endDate&&null!==c)u=n+c,s=!0;else if(t.endOnNext&&!s){var d=g.reduce(function(e,r){if(r!==t.id){var n=v[r];if(n.class===t.class&&n.startDate>t.startDate&&(!e||t.startDate<e.startDate))return n}return e},null);d&&(u=d.startTime,s=!0)}for(var h=Object.keys(t.attr),f=0;f<h.length;f++){var y=h[f];if(_n(y)){var m=a[y];if(m)!s||null!=i&&i.durationKnown?Math.abs(m.startTime-n)>.01&&(m.startTime=n,m.endTime=u):m.endTime=u;else if(l){var E=t.attr[y];Pn(y)&&(E=Xe(E));var k=Lu(l,n,u,{key:y,data:E},ga.dateRange);k&&(k.id=e,r.id3Track.track.addCue(k),a[y]=k,o&&("X-ASSET-LIST"!==y&&"X-ASSET-URL"!==y||k.addEventListener("enter",r.onEventCueEnter)))}}}p[e]={cues:a,dateRange:t,durationKnown:s}},b=0;b<g.length;b++)T()}}}}}}])}();function wu(){return self.SourceBuffer||self.WebKitSourceBuffer}function _u(){if(!Re())return!1;var e=wu();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var Pu,Du,Cu=0,Ou=1,xu=2,Mu=function(e){function t(e,r,n){var i;return c(this,t),(i=u(this,t,[e,r,n,"stream-controller",W.MAIN])).audioCodecSwap=!1,i.level=-1,i._forceStartLoad=!1,i._hasEnoughToStart=!1,i.altAudio=Cu,i.audioOnly=!1,i._couldBacktrack=!1,i._backtrackFragment=void 0,i.audioCodecSwitch=!1,i.videoBuffer=null,i.onMediaPlaying=function(){i.tick()},i.onMediaSeeked=function(){var e=i.media,t=e?e.currentTime:null;if(null!==t&&x(t)&&(i.log("Media seeked to ".concat(t)),i.getBufferedFrag(t))){var r=i.getFwdBufferInfoAtPos(e,t,W.MAIN,0);r&&0!==r.len?i.tick():i.log("Main buffer empty at ".concat(t,' on "seeked" event: ').concat(r?r.len:r))}},i.registerListeners(),i}return y(t,e),h(t,[{key:"registerListeners",value:function(){R(t,"registerListeners",this)([]);var e=this.hls;e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(B.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(B.BUFFER_CREATED,this.onBufferCreated,this),e.on(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){R(t,"unregisterListeners",this)([]);var e=this.hls;e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(B.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(B.BUFFER_CREATED,this.onBufferCreated,this),e.off(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"onHandlerDestroying",value:function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),R(t,"onHandlerDestroying",this)([])}},{key:"startLoad",value:function(e,t){if(this.levels){var r=this.lastCurrentTime,n=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var i=n.startLevel;-1===i&&(n.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=n.firstAutoLevel),n.nextLoadLevel=i,this.level=n.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @".concat(r)),e=r),this.state=Gi,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Bi}},{key:"stopLoad",value:function(){this._forceStartLoad=!1,R(t,"stopLoad",this)([])}},{key:"doTick",value:function(){switch(this.state){case Qi:var e=this.levels,t=this.level,r=null==e?void 0:e[t],n=null==r?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(n))break;this.state=Gi;break}if(this.hls.nextLoadLevel!==this.level){this.state=Gi;break}break;case Hi:this.checkRetryDate()}this.state===Gi&&this.doTickIdle(),this.onTickEnd()}},{key:"onTickEnd",value:function(){var e;R(t,"onTickEnd",this)([]),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}},{key:"doTickIdle",value:function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,n=this.media;if(null!==t&&(n||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var i=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[i]){var a=r[i],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={type:this.targetBufferType()};return this.hls.trigger(B.BUFFER_EOS,l),void(this.state=Yi)}if(this.buffering){e.loadLevel!==i&&-1===e.manualLevel&&this.log("Adapting to level ".concat(i," from level ").concat(this.level)),this.level=e.nextLoadLevel=i;var u=a.details;if(!u||this.state===Qi||this.waitForLive(a))return this.level=i,this.state=Qi,void(this.startFragRequested=!1);var c=s.len,d=this.getMaxBufferLength(a.maxBitrate);if(!(c>=d)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=void 0);var h=this.backtrackFragment?this.backtrackFragment.start:s.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&$(f)&&this.fragmentTracker.getState(f)!==Zr){var v,g=(null!=(v=this.backtrackFragment)?v:f).sn-u.startSN,p=u.fragments[g-1];p&&f.cc===p.cc&&(f=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,h)){if(!f.gap){var y=this.audioOnly&&!this.altAudio?Y:z,m=(y===z?this.videoBuffer:this.mediaBuffer)||this.media;m&&this.afterBufferFlushed(m,y)}f=this.getNextFragmentLoopLoading(f,u,s,W.MAIN,d)}f&&(this.exceedsMaxBuffer(s,d,f)||this.loadFragment(f,a,h))}}}}}}},{key:"loadFragment",value:function(e,r,n){var i=this.fragmentTracker.getState(e);i===Qr||i===Jr?this.bitrateTest?(this.log("Fragment ".concat(e.sn," of level ").concat(e.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(e,r)):R(t,"loadFragment",this)([e,r,n]):this.clearTrackerIfNeeded(e)}},{key:"immediateLevelSwitch",value:function(){var e;(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Cu)&&(((null==(e=this.getLevelDetails())?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&R(t,"flushMainBuffer",this)([0,Number.POSITIVE_INFINITY,"audio"]))}},{key:"getBufferOutput",value:function(){return this.mediaBuffer&&this.altAudio===xu?this.mediaBuffer:this.media}},{key:"checkFragmentChanged",value:function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying;if(t){var r=t.level;this.hls.trigger(B.FRAG_CHANGED,{frag:t,previousFrag:e}),(null==e?void 0:e.level)!==r&&this.hls.trigger(B.LEVEL_SWITCHED,{level:r})}return!0}},{key:"backtrackFragment",get:function(){return this._backtrackFragment},set:function(e){this._backtrackFragment=e}},{key:"couldBacktrack",get:function(){return this._couldBacktrack},set:function(e){this._couldBacktrack=e}},{key:"abortCurrentFrag",value:function(){this.backtrackFragment=void 0,R(t,"abortCurrentFrag",this)([])}},{key:"flushMainBuffer",value:function(e,r){R(t,"flushMainBuffer",this)([e,r,this.targetBufferType()])}},{key:"targetBufferType",value:function(){return this.altAudio!==xu||this.audioOnly?null:"video"}},{key:"onMediaAttached",value:function(e,r){R(t,"onMediaAttached",this)([e,r]);var n=r.media;Fi(n,"playing",this.onMediaPlaying),Fi(n,"seeked",this.onMediaSeeked)}},{key:"onMediaDetaching",value:function(e,r){var n=this.media;n&&(Ni(n,"playing",this.onMediaPlaying),Ni(n,"seeked",this.onMediaSeeked)),this.videoBuffer=null,R(t,"onMediaDetaching",this)([e,r]),!!r.transferMedia||(this._hasEnoughToStart=!1)}},{key:"onManifestLoading",value:function(){R(t,"onManifestLoading",this)([]),this.log("Trigger BUFFER_RESET"),this.hls.trigger(B.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Cu,this.audioOnly=!1}},{key:"onManifestParsed",value:function(e,t){for(var r,n,i=!1,a=!1,s=0;s<t.levels.length;s++){var o=t.levels[s].audioCodec;o&&(i=i||-1!==o.indexOf("mp4a.40.2"),a=a||-1!==o.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&a&&!("function"==typeof(null==(n=wu())||null==(r=n.prototype)?void 0:r.changeType)),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}},{key:"onLevelLoading",value:function(e,t){if(this.levels&&this.state===Gi){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=Qi)}}},{key:"onLevelLoaded",value:function(e,t){var r,n=this,i=this.levels,a=this.startFragRequested,s=t.level,o=t.details,l=o.totalduration;if(i){this.log("Level ".concat(s," loaded [").concat(o.startSN,",").concat(o.endSN,"]").concat(o.lastPartSn?"[part-".concat(o.lastPartSn,"-").concat(o.lastPartIndex,"]"):"",", cc [").concat(o.startCC,", ").concat(o.endCC,"] duration:").concat(l));var u=t.levelInfo,c=this.fragCurrent;!c||this.state!==Ki&&this.state!==Hi||c.level!==t.level&&c.loader&&this.abortCurrentFrag();var d=0;if(o.live||null!=(r=u.details)&&r.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,u.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(u.details=o,this.levelLastLoaded=u,a||this.setStartPosition(o,d),this.hls.trigger(B.LEVEL_UPDATED,{details:o,level:s}),this.state===Qi){if(this.waitForCdnTuneIn(o))return;this.state=Gi}a&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some(function(e,t){if(t>=o.startCC)return!0;delete n.initPTS[t]}),this.tick()}else this.warn("Levels were reset while loading level ".concat(s))}},{key:"synchronizeToLiveEdge",value:function(e){var t=this.config,r=this.media;if(r){var n=this.hls.liveSyncPosition,i=this.playhead,a=e.fragmentStart,s=e.edge,o=i>=a-t.maxFragLookUpTolerance&&i<=s;if(null!==n&&r.duration>n&&(i<n||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||i<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),r.readyState))if(this.warn("Playback: ".concat(i," is located too far from the end of live sliding playlist: ").concat(s,", reset currentTime to : ").concat(n)),"buffered"===this.config.liveSyncMode){var u,c=kn.bufferInfo(r,n,0);if(null==(u=c.buffered)||!u.length)return void(r.currentTime=n);if(c.start<=i)return void(r.currentTime=n);var d=kn.bufferedInfo(c.buffered,i,0).nextStart;d&&(r.currentTime=d)}else r.currentTime=n}}}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,n=e.part,i=e.payload,a=this.levels;if(a){var s=a[r.level];if(s){var o=s.details;if(!o)return this.warn("Dropping fragment ".concat(r.sn," of level ").concat(r.level," after level details were reset")),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(s),h=this.transmuxer=this.transmuxer||new ws(this.hls,W.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,v=-1!==f,g=vn(r,n,this.iframesOnly),p=g.decryptRange,y=g.byteRange,m=new mn(r.level,r.sn,r.stats.chunkCount,y?y.end-y.start:i.byteLength,f,v,r.duration,this.iframesOnly,p),E=this.initPTS[r.cc];h.push(i,c,d,l,r,n,o.totalduration,u,m,E)}else this.warn("Level ".concat(r.level," not found on progress"))}else this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"onAudioTrackSwitching",value:function(e,t){var r=this,n=this.hls,i=this.altAudio!==Cu;if(Rr(t.url,n))this.altAudio=Ou;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=Cu,this.fragmentTracker.removeAllFragments(),n.once(B.BUFFER_FLUSHED,function(){r.hls&&r.hls.trigger(B.AUDIO_TRACK_SWITCHED,t)}),void n.trigger(B.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});n.trigger(B.AUDIO_TRACK_SWITCHED,t)}}},{key:"onAudioTrackSwitched",value:function(e,t){var r=Rr(t.url,this.hls);if(r){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r?xu:Cu,this.tick()}},{key:"onBufferCreated",value:function(e,t){var r,n,i=t.tracks,a=!1;for(var s in i){var o=i[s];if("main"===o.id){if(n=s,r=o,"video"===s){var l=i[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use ".concat(n,".buffered to schedule main fragment loading")),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,n=t.part,i=r.type===W.MAIN;if(i){if(this.fragContextChanged(r))return this.warn("Fragment ".concat(r.sn).concat(n?" p: "+n.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===Wi&&(this.state=Gi));var a=!1;if($(r)&&(a=!!r.gap&&!r.tagList.some(function(e){return"GAP"===e[0]})),this.fragBufferedComplete(r,n),a){var s;r.stats.retry++;var o=null==(s=this.levels)?void 0:s[r.level];o&&o.fragmentError++}}var l=this.media;l&&(!this._hasEnoughToStart&&kn.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}},{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"onError",value:function(e,t){var r;if(t.fatal)this.state=zi;else switch(t.details){case U.FRAG_GAP:case U.FRAG_PARSING_ERROR:case U.FRAG_DECRYPT_ERROR:case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.MAIN,t);break;case U.LEVEL_LOAD_ERROR:case U.LEVEL_LOAD_TIMEOUT:case U.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Qi||(null==(r=t.context)?void 0:r.type)!==q.LEVEL||(this.state=Gi);break;case U.BUFFER_APPEND_NO_PROGRESS:if("main"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment ".concat(t.frag.sn," of level ").concat(t.frag.level," as a gap after ").concat(t.appendsWithoutProgress," appends without buffered range growth, to prevent loop loading")),this.fragmentTracker.addAsGap(t.frag));break;case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case U.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t))!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case U.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}},{key:"onFragLoadEmergencyAborted",value:function(){this.state=Gi,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==Y||!this.altAudio){var n=(r===z?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r),this.tick())}}},{key:"onLevelsUpdated",value:function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}},{key:"swapAudioCodec",value:function(){this.audioCodecSwap=!this.audioCodecSwap}},{key:"seekToStartPos",value:function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to ".concat(r,", already seeking at ").concat(t));var n=this.timelineOffset;n&&r&&(r+=n);var i=this.getLevelDetails(),a=kn.getBuffered(e),s=a.length?a.start(0):0,o=s-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==i?void 0:i.partTarget)||0)))&&(this.log("adjusting start position by ".concat(o," to match buffer start")),r+=o,this.startPosition=r),t<r&&(this.log("seek to target start position ".concat(r," from current time ").concat(t," buffer start ").concat(s)),e.currentTime=r)}}}},{key:"_getAudioCodec",value:function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}},{key:"_loadBitrateTestFrag",value:function(e,t){var r=this;e.bitrateTest=!0,this._doFragLoad(e,t).then(function(e){var n=r.hls,i=null==e?void 0:e.frag;if(i&&!r.fragContextChanged(i)){t.fragmentError=0,r.state=Gi,r.startFragRequested=!1,r.bitrateTest=!1;var a=i.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),n.trigger(B.FRAG_LOADED,e),i.bitrateTest=!1}}).catch(function(t){r.state!==Bi&&r.state!==zi&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"_handleTransmuxComplete",value:function(e){var t=this.playlistType,r=this.hls,n=e.remuxResult,i=e.chunkMeta,a=this.getCurrentContext(i);if(a){var s=a.frag,o=a.part,l=a.level,u=n.video,c=n.text,d=n.id3,h=n.initSegment,f=l.details,v=this.altAudio?void 0:n.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=qi,h){var g=h.tracks;if(g){var p=s.initSegment||s;if(this.unhandledEncryptionError(h,s))return;this._bufferInitSegment(l,g,p,i),r.trigger(B.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:t,tracks:g})}var y=h.initPTS,m=h.timescale,E=this.initPTS[s.cc];if(x(y)&&(!E||E.baseTime!==y||E.timescale!==m)){var k=h.trackId;this.initPTS[s.cc]={baseTime:y,timescale:m,trackId:k};var S=this.initPTS.slice(0);r.trigger(B.INIT_PTS_FOUND,{timestampOffsets:S,frag:s,id:t,initPTS:y,timescale:m,trackId:k})}}if(u&&f){v&&"audiovideo"===u.type&&this.logMuxedErr(s);var T=f.fragments[s.sn-1-f.startSN],b=s.sn===f.startSN,A=!T||s.cc>T.cc;if(!1!==n.independent){var L=u.startPTS,R=u.endPTS,I=u.startDTS,w=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:L,endPTS:R,startDTS:I,endDTS:w};else if(u.firstKeyFrame&&u.independent&&1===i.id&&!A&&(this.couldBacktrack=!0),u.dropped&&u.independent){var _=this.getMainFwdBufferInfo(),P=(_?_.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:L;if(!b&&P<D-this.config.maxBufferHole&&!A)return void this.backtrack(s);A&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,R,s.start,w,!0)}else b&&L-(f.appliedTimelineOffset||0)>2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,L,R,I,w),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,i,b||A)}else{if(!b&&!A)return void this.backtrack(s);s.gap=!0}}if(v){var C=v.startPTS,O=v.endPTS,M=v.startDTS,F=v.endDTS;o&&(o.elementaryStreams[Y]={startPTS:C,endPTS:O,startDTS:M,endDTS:F}),s.setElementaryStreamInfo(Y,C,O,M,F),this.bufferFragmentData(v,s,o,i)}if(f&&null!=d&&d.samples.length){var N={id:t,frag:s,details:f,samples:d.samples};r.trigger(B.FRAG_PARSING_METADATA,N)}if(f&&c){var U={id:t,frag:s,details:f,samples:c.samples};r.trigger(B.FRAG_PARSING_USERDATA,U)}}}else this.resetWhenMissingContext(i)}},{key:"logMuxedErr",value:function(e){this.warn("".concat($(e)?"Media":"Init"," segment with muxed audiovideo where only video expected: ").concat(e.url))}},{key:"_bufferInitSegment",value:function(e,t,r,n){var i=this;if(this.state===qi){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var a=t.audio,s=t.video,o=t.audiovideo;if(a){var l=e.audioCodec,u=Qt(a.codec,l);if("mp4a"===u&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var c=a.metadata;c&&"channelCount"in c&&1!==(c.channelCount||1)&&!function(){if(void 0===Ot){var e=Mt.match(/Firefox\/(\d+)/i);Ot=e?parseInt(e[1]):0}return Ot}()&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&/Android/.test(Mt)&&"audio/mpeg"!==a.container&&(u="mp4a.40.2",this.log("Android: force audio codec to ".concat(u))),l&&l!==u&&this.log('Swapping manifest audio codec "'.concat(l,'" for "').concat(u,'"')),a.levelCodec=u,a.id=W.MAIN,this.log("Init audio buffer, container:".concat(a.container,", codecs[selected/level/parsed]=[").concat(u||"","/").concat(l||"","/").concat(a.codec,"]")),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=W.MAIN;var d=s.codec;if(4===(null==d?void 0:d.length))switch(d){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log("Init video buffer, container:".concat(s.container,", codecs[level/parsed]=[").concat(e.videoCodec||"","/").concat(d,"]").concat(s.codec!==d?" parsed-corrected="+s.codec:"").concat(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(r),this.log("Init audiovideo buffer, container:".concat(o.container,", codecs[level/parsed]=[").concat(e.codecs,"/").concat(o.codec,"]")),delete t.video,delete t.audio);var h=Object.keys(t);if(h.length){if(this.hls.trigger(B.BUFFER_CODECS,t),!this.hls)return;h.forEach(function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&i.hls.trigger(B.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:n,parent:r.type})})}this.tickImmediate()}}},{key:"getMainFwdBufferInfo",value:function(){var e=this.getBufferOutput();return this.getFwdBufferInfo(e,W.MAIN)}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"backtrack",value:function(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=Gi}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return x(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(x(t)){var r=this.getLevelDetails(),n=this.currentFrag||(r?Dr(null,r.fragments,t):null);if(n){var i=n.programDateTime;if(null!==i){var a=i+1e3*(t-n.start);return new Date(a)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}($i),Fu=function(e){function t(){var e;c(this,t);for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return(e=u(this,t,[].concat(n))).currentOp=void 0,e.nextOp=void 0,e.cached=[],e.cachedSize=0,e.cacheFragmentData=!0,e.initDetails=void 0,e.onBufferedToEnd=function(){var t=e.media;null!=t&&t.seeking&&(t.currentTime=t.currentTime)},e.onMediaSeeking=function(){},e}return y(t,e),h(t,[{key:"setInitPts",value:function(e){this.initPTS=e.slice()}},{key:"loadMediaAt",value:function(e,t){if(this.hls){var r=t.seekOnAppend,n=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=n,this.startPosition=e,this.state){case Bi:case Yi:case zi:this.state=Gi}this.state===Gi?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[n,t]):this.nextOp=[n,t],this.hls.off(B.BUFFERED_TO_END,this.onBufferedToEnd);var i=this.media;if(r&&i)this.seekTo(n)&&(this.currentOp=[n,t],this.nextOp=void 0,this.flushPipeline(n,!0))}}},{key:"seekTo",value:function(e){var t=this.media;if(t){var r,n=null==(r=this.getLevelDetails())?void 0:r.edge,i=void 0!==n?n:t.duration;if(e>=i&&(e=i-.01),kn.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}},{key:"getBufferedAt",value:function(e){return this.fragmentTracker.getBufferedFrag(e,W.MAIN)}},{key:"cacheSet",value:function(e,t){if(this.hls){e.data=t;var r=this.cached;r.push(e),this.cachedSize+=t.buffer.byteLength;for(var n=this.hls.config.iframeCacheLimit;this.cachedSize>n&&r.length>1;){var i=r.shift();if(!i.data){this.cached=r.filter(function(e){return!!e.data}),this.cachedSize=r.reduce(function(e,t){var r=t.data;return r?r.buffer.byteLength:0},0);break}this.cachedSize-=i.data.byteLength,i.data=void 0}}}},{key:"onHandlerDestroying",value:function(){this.cached.length=0,this.cachedSize=0,R(t,"onHandlerDestroying",this)([])}},{key:"_handleFragmentLoadProgress",value:function(e){var r=e.frag,n=e.part,i=e.payload;this.cacheFragmentData&&!n&&null!=i&&i.byteLength&&!r.data&&$(r)&&this.cacheSet(r,new Uint8Array(i.slice(0))),R(t,"_handleFragmentLoadProgress",this)([e])}},{key:"loadFragment",value:function(e,r,n){var i=this.fragmentTracker.getState(e);i!==Qr&&i!==Jr||!this.canReplayCached(e)?R(t,"loadFragment",this)([e,r,n]):this.replayCachedFragment(e)}},{key:"canReplayCached",value:function(e){var t;if(!this.cacheFragmentData||null==(t=e.data)||!t.byteLength)return!1;var r=e.decryptdata;return"identity"!==(null==r?void 0:r.keyFormat)||!!r.key}},{key:"replayCachedFragment",value:function(e){var t=e.data.slice().buffer;this.log("Buffering cached ".concat(e.type," sn: ").concat(e.sn," of level ").concat(e.level," (").concat(t.byteLength," bytes)")),this.fragCurrent=e,this.startFragRequested=!0;var r=e.stats=new V;r.loading.start=r.loading.first=r.loading.end=self.performance.now(),r.loaded=r.total=t.byteLength,r.chunkCount=1,this.state=Ki;var n={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(n),this.hls.trigger(B.FRAG_LOADED,n),this._handleFragmentLoadComplete(n)}},{key:"fragBufferedComplete",value:function(e,r){R(t,"fragBufferedComplete",this)([e,r]);var n=this.currentOp,i=this.nextOp;this.currentOp=this.nextOp=void 0,this.state=Bi,null!=n&&n[1].seekOnAppend&&(this.flushPipeline(n[0],!i),this.seekTo(n[0])||this.log("Could not seek to ".concat(n[0]," after fragment buffered (superseded or flushed) buffer: ").concat(this.media?Ui(kn.getBuffered(this.media)):"none"))),i&&this.loadMediaAt.apply(this,i)}},{key:"flushPipeline",value:function(e,t){if(t){var r=this.media;if(r){var n=kn.bufferInfo(r,e,0),i=n.len?n.nextStart:0;i&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,W.MAIN),this.flushMainBuffer(i,1/0))}this.hls.once(B.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(B.BUFFER_EOS,{type:"video"})}},{key:"playhead",get:function(){return this.nextLoadPosition}},{key:"startLoad",value:function(){if(!this.startFragRequested){var e=this.hls;e.nextLoadLevel=-1===e.startLevel?0:e.firstAutoLevel}}},{key:"seekToStartPos",value:function(){}},{key:"setStartPosition",value:function(){}},{key:"alignPlaylists",value:function(e,r,n){var i=this.initDetails;return this.initDetails=null,R(t,"alignPlaylists",this)([e,r,n||i||void 0])}},{key:"getMainFwdBufferInfo",value:function(){var e=this.playhead,t=this.getBufferedAt(e);if(t){var r=t.duration;return{len:r,start:e,end:e+r,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}},{key:"_streamEnded",value:function(){var e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,W.MAIN);return!(null==t||!t.endList)}}])}(Mu),Nu=function(e){function t(){var e;c(this,t);for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return(e=u(this,t,[].concat(n)))._img=void 0,e.queued=void 0,e.cacheFragmentData=!1,e}return y(t,e),h(t,[{key:"image",get:function(){return this._img},set:function(e){var t,r=null==(t=this._img)?void 0:t.src;r&&self.URL.revokeObjectURL(r),this._img=e}},{key:"loadMediaAt",value:function(e){if(this.hls){var t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case Bi:case Yi:case zi:this.state=Gi}if(this.state===Gi){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===Gi){var r=this.getBufferedAt(e);r&&(this.fragCurrent=r,this.updateImage(r,null))}}else{var n=this.fragCurrent;(!n||e>=n.start&&e<n.end)&&(this.queued=[t])}}}},{key:"updateImage",value:function(e,t,r){var n=this,i=e.data;i||this.fragmentTracker.removeFragment(e);var a=this._img;if(a&&i){var s=self.performance.now();(t?t.stats:e.stats).buffering.start=e.stats.buffering.start=s,a.onload=function(){if(n.hls){var i=n.hls.levels[e.level];null!=i&&i.fragmentError&&(i.fragmentError=0,e.stats.retry=0);var a=self.performance.now(),s=t?t.stats:e.stats;s.buffering.end=e.stats.buffering.end=a,n.hls.trigger(B.FRAG_BUFFERED,{frag:e,part:t,stats:s,id:e.type,chunkMeta:r})}},a.onerror=function(){n.handleError("Image decode error",e,t,r)};var o=a.src;o&&self.URL.revokeObjectURL(o);var l=new Blob([i],{type:"image/jpeg"});a.src=self.URL.createObjectURL(l)}else this.state=Bi,this.processQueued()}},{key:"processQueued",value:function(){var e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}},{key:"handleError",value:function(e,t,r,n){if(this.hls){var i=new Error(e);this.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,chunkMeta:n,frag:t,part:r,fatal:!1,error:i,err:i})}}},{key:"_bufferInitSegment",value:function(){}},{key:"bufferFragmentData",value:function(e,r,n,i){R(t,"bufferFragmentData",this)([e,r,n,i,!0]);var a=dt(new Uint8Array(e.data1),["mdat"]);if(0!==a.length){var s=r;this.cacheSet(s,a[0]),this.updateImage(s,n,i)}else this.handleError("Could not find I-Frame mdat",r,n,i)}},{key:"fragBufferedComplete",value:function(e,r){this.fragmentTracker.fragBuffered(e,!0),R(t,"fragBufferedComplete",this)([e,r]),this.processQueued()}},{key:"checkFragPlaying",value:function(){var e,t=null==(e=this.fragPrevious)?void 0:e.start;if(void 0!==t){var r=this.getAppendedFrag(t);if(r&&!J(r,this.fragPlaying))return this.fragPlaying=r,!0}return!1}},{key:"getMainFwdBufferInfo",value:function(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}])}(Fu),Uu="Image I-Frame player does not accept HTMLMediaElements",Bu={seekOnAppend:!0},Gu=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,["iframes",e.logger])).hls=void 0,n.stats=void 0,n.variableList=null,n.initPTS=[],n.iframeInstances=void 0,n.instanceCounter=0,Pu||(Pu=function(e){function t(e,r,n,i){var a;return c(this,t),e.streamController||(e.streamController=Fu),(a=u(this,t,[e]))._url=r,a.streamController.setInitPts(n),a.streamController.initDetails=i,a}return y(t,e),h(t,[{key:"loadSource",value:function(){}},{key:"loadMediaAt",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Bu;if(!(e<0)){var r=se(se({},Bu),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,r)}}}])}(r)),Du||(Du=function(e){return function(e){function t(e,r,n,i){return c(this,t),e.cmcdController=void 0,e.emeController=void 0,e.streamController||(e.streamController=Nu),e.capLevelController=void 0,e.bufferController=void 0,u(this,t,[e,r,n,i])}return y(t,e),h(t,[{key:"attachImage",value:function(e){this.streamController.image=e}},{key:"detachImage",value:function(){this.streamController.image=void 0}},{key:"loadSource",value:function(){}},{key:"attachMedia",value:function(){throw new Error(Uu)}},{key:"detachMedia",value:function(){}},{key:"recoverMediaError",value:function(){}},{key:"transferMedia",value:function(){return null}},{key:"loadMediaAt",value:function(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}])}(e)}(Pu)),n.hls=e,n.iframeInstances=[],n.registerListeners(),n}return y(t,e),h(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(B.MANIFEST_LOADING,this.clearAsset,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.MANIFEST_LOADING,this.clearAsset,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.DESTROYING,this.onDestroying,this))}},{key:"clearAsset",value:function(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(function(e){return e.destroy()}),this.iframeInstances.length=0}},{key:"onDestroying",value:function(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}},{key:"onManifestLoaded",value:function(e,t){this.stats=t.stats,this.variableList=t.variableList}},{key:"onLevelsUpdated",value:function(e,t){var r,n=t.levels,i=null==(r=this.hls)?void 0:r.pathwayPriority;n.length&&i&&this.iframeInstances.forEach(function(e){e.pathwayPriority=i})}},{key:"onInitPtsFound",value:function(e,t){var r=t.id,n=t.timestampOffsets;r===W.MAIN&&(this.initPTS=n)}},{key:"onFragBuffered",value:function(e,t){var r,n=this,i=this.hls;i&&i.hasEnoughToStart&&((null==(r=i.mainForwardBufferInfo)?void 0:r.len)||0)>10&&this.iframeInstances.forEach(function(e){var t;e.loadingEnabled||e.startLoad((null==(t=n.hls)||null==(t=t.media)?void 0:t.currentTime)||0)})}},{key:"createIFramePlayer",value:function(e){var t;return this.createInstance(Pu,null==(t=this.hls)?void 0:t.iframeVariants,e)}},{key:"createImageIFramePlayer",value:function(e){var t,r=null==(t=this.hls)?void 0:t.iframeVariants.filter(function(e){return e.imageCodec});return this.createInstance(Du,r,e,"image-")}},{key:"createInstance",value:function(e,t,r,n){var i=this.hls;if(!i)return null;var a=i.url,s=i.userConfig,o=i.latestLevelDetails,l=i.loadLevelObj,u=i.loadLevel,c=i.bandwidthEstimate,d=i.sessionId,h=this.stats,f=this.variableList;if(null==t||!t.length||!h||!a)return null;var v="".concat(n||"","iframe-player-").concat(this.instanceCounter++),g=i.levels,p=l||g[u],y=wr(p,s.videoPreference),m=(null==p?void 0:p.pathwayId)||".",E=new e(se(se({},s),{},{loggerId:v,primarySessionId:d,videoPreference:y,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},r),a,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter(function(e){return!e.url}),this.iframeInstances.push(E),E.trigger(B.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:m},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:h,networkDetails:null,url:a,variableList:f}),E}}])}(Ee);var ju=.025,Ku=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Hu(e,t,r){return"".concat(e.identifier,"-").concat(r+1,"-").concat(Jl(t))}var Vu=function(){return h(function e(t,r){c(this,e),this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=t,this.setDateRange(t)},[{key:"setDateRange",value:function(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)}},{key:"reset",value:function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}},{key:"isAssetPastPlayoutLimit",value:function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var r=this.playoutLimit;return!(e<=0||isNaN(r))&&(0===r||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>r)}},{key:"findAssetIndex",value:function(e){return this.assetList.indexOf(e)}},{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return Wu(t,e)?qu(e,t):e}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-qu(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=x(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return Wu(t,e)?qu(e,t):e}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<ju))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Ku.Range:Ku.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}},{key:"toString",value:function(){return'["'.concat((e=this).identifier,'" ').concat(e.cue.pre?"<pre>":e.cue.post?"<post>":"").concat(e.timelineStart.toFixed(2),"-").concat(e.resumeTime.toFixed(2),"]");var e}}])}();function qu(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<ju)?t.start:t.start+t.duration}function Wu(e,t){return t>e.start-ju&&t<e.start+e.duration+ju}function Yu(e,t,r){var n=new self.URL(e,r);return"data:"!==n.protocol&&or(n,"_HLS_primary_id",t),n}function zu(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function Xu(e){var t=e.timelineStart,r=e.duration||0;return'["'.concat(e.identifier,'" ').concat(t.toFixed(2),"-").concat((t+r).toFixed(2),"]")}var Qu=function(){return h(function e(t,r,n,i){var a=this;c(this,e),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=function(){a.reachedPlayout(a.currentTime)&&a.hls&&a.hls.trigger(B.PLAYOUT_LIMIT_REACHED,{})};var s=this.hls=new t(r);this.interstitial=n,this.assetItem=i;var o=function(){a.hasDetails=!0};s.once(B.LEVEL_LOADED,o),s.once(B.AUDIO_TRACK_LOADED,o),s.once(B.SUBTITLE_TRACK_LOADED,o),s.on(B.MEDIA_ATTACHING,function(e,t){var r=t.media;a.removeMediaListeners(),a.mediaAttached=r,a.interstitial.playoutLimit&&(r.addEventListener("timeupdate",a.checkPlayout),a.appendInPlace&&s.on(B.BUFFER_APPENDED,function(){var e=a.bufferedEnd;a.reachedPlayout(e)&&(a._bufferedEosTime=e,s.trigger(B.BUFFERED_TO_END,void 0))}))})},[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"loadSource",value:function(){var e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{var t=this.assetItem.uri;try{t=Yu(t,e.config.primarySessionId||"").href}catch(r){}e.loadSource(t)}}},{key:"bufferedInPlaceToEnd",value:function(e,t){var r;if(!this.appendInPlace)return!1;if(null!=(r=this.hls)&&r.bufferedToEnd)return!0;if(!e)return!1;var n=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset+(t||0),a=kn.bufferInfo(e,i,.02);return this.getAssetTime(a.end)>=n-.02}},{key:"reachedPlayout",value:function(e){var t=this.interstitial.playoutLimit;return this.startOffset+e>=t}},{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=kn.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var r=t-this.startOffset;if(r>0&&r<e)return r}return e}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}},{key:"getAssetTime",value:function(e){var t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}},{key:"removeMediaListeners",value:function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}},{key:"bufferSnapShot",value:function(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}},{key:"destroy",value:function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}},{key:"attachMedia",value:function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}},{key:"detachMedia",value:function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.hls)||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.hls)||e.pauseBuffering()}},{key:"transferMedia",value:function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}},{key:"resetDetails",value:function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}},{key:"on",value:function(e,t,r){var n;null==(n=this.hls)||n.on(e,t)}},{key:"once",value:function(e,t,r){var n;null==(n=this.hls)||n.once(e,t)}},{key:"off",value:function(e,t,r){var n;null==(n=this.hls)||n.off(e,t)}},{key:"toString",value:function(){var e;return"HlsAssetPlayer: ".concat(Xu(this.assetItem)," ").concat(null==(e=this.hls)?void 0:e.sessionId," ").concat(this.appendInPlace?"append-in-place":"")}}])}(),$u=.033,Ju=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,["interstitials-sched",r])).onScheduleUpdate=void 0,n.eventMap={},n.events=null,n.items=null,n.durations={primary:0,playout:0,integrated:0},n.onScheduleUpdate=e,n}return y(t,e),h(t,[{key:"destroy",value:function(){this.reset(),this.onScheduleUpdate=null}},{key:"reset",value:function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(function(e){return e.reset()}),this.events=this.items=null}},{key:"resetErrorsInRange",value:function(e,t){return this.events?this.events.reduce(function(r,n){return e<=n.startOffset&&t>n.startOffset?(delete n.error,r+1):r},0):0}},{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"getEvent",value:function(e){return e&&this.eventMap[e]||null}},{key:"hasEvent",value:function(e){return e in this.eventMap}},{key:"findItemIndex",value:function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);var n=this.items;if(n)for(n[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(i=n[r])&&i.event;){var i;r--}return r}},{key:"findItemIndexAtTime",value:function(e,t){var r=this.items;if(r)for(var n=0;n<r.length;n++){var i=r[n];t&&"primary"!==t&&(i=i[t]);var a=i.start,s=r[n].event,o=null!=s&&s.cue.pre?s.duration:i.end;if(e===a||e>a&&e<o)return n}return-1}},{key:"findJumpRestrictedIndex",value:function(e,t){var r=this.items;if(r)for(var n=e;n<=t&&r[n];n++){var i=r[n].event;if(null!=i&&i.restrictions.jump&&!i.appendInPlace)return n}return-1}},{key:"findEventIndex",value:function(e){var t=this.items;if(t)for(var r=t.length;r--;){var n;if((null==(n=t[r].event)?void 0:n.identifier)===e)return r}return-1}},{key:"findAssetIndex",value:function(e,t){var r=e.assetList,n=r.length;if(n>1)for(var i=0;i<n;i++){var a=r[i];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||i===n-1))return i}}return 0}},{key:"assetIdAtEnd",get:function(){var e,t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){var r=t.assetList,n=r[r.length-1];if(n)return n.identifier}return null}},{key:"parseInterstitialDateRanges",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=e.main.details,a=i.dateRanges,s=this.events,o=this.parseDateRanges(a,{url:i.url},t),l=Object.keys(a),u=s?s.filter(function(e){return-1===l.indexOf(e.identifier)}):[];o.length&&o.sort(function(e,t){var r=e.cue.pre,n=e.cue.post,i=t.cue.pre,a=t.cue.post;if(r&&!i)return-1;if(i&&!r)return 1;if(n&&!a)return 1;if(a&&!n)return-1;if(!(r||i||n||a)){var s=e.startTime,o=t.startTime;if(s!==o)return s-o}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=o,u.forEach(function(e){r.removeEvent(e)}),this.updateSchedule(e,u,n)}},{key:"updateSchedule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=this.events||[];if(i.length||t.length||this.length<2){var a=this.items,s=this.parseSchedule(i,e,r);(n||t.length||(null==a?void 0:a.length)!==s.length||s.some(function(e,t){return Math.abs(e.playout.start-a[t].playout.start)>.005||Math.abs(e.playout.end-a[t].playout.end)>.005}))&&(this.items=s,this.onScheduleUpdate(t,a))}}},{key:"parseDateRanges",value:function(e,t,r){for(var n=[],i=Object.keys(e),a=0;a<i.length;a++){var s=i[a],o=e[s];if(o.isInterstitial){var l=this.eventMap[s];l?l.setDateRange(o):(l=new Vu(o,t),this.eventMap[s]=l,!1===r&&(l.appendInPlace=r)),n.push(l)}}return n}},{key:"parseSchedule",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=[],i=t.main.details,a=i.live?1/0:i.edge,s=0;if((e=e.filter(function(e){return!(e.error||e.cue.once&&e.hasPlayed)})).length){this.resolveOffsets(e,t);var o=0,l=0;if(e.forEach(function(t,u){var c=t.cue.pre,d=t.cue.post,h=e[u-1]||null,f=t.appendInPlace,v=d?a:t.startOffset,g=t.duration,p=t.timelineOccupancy===Ku.Range?g:0,y=c&&i.live?r+(t.resumeOffset||0):0,m=y||t.resumptionOffset,E=(null==h?void 0:h.startTime)===v,k=v+t.cumulativeDuration,S=f?k+g:v+m;if(c||!d&&v<=0){var T=l;l+=p,t.timelineStart=k;var b=s;s+=g,n.push({event:t,start:k,end:S,playout:{start:b,end:s},integrated:{start:T,end:l}})}else{if(!(v<=a))return;if(!E){var A=v-o;if(A>$u){var L=o,R=l;l+=A;var I=s;s+=A;var w={previousEvent:e[u-1]||null,nextEvent:t,start:L,end:L+A,playout:{start:I,end:s},integrated:{start:R,end:l}};n.push(w)}else A>0&&h&&(h.cumulativeDuration+=A,n[n.length-1].end=v)}d&&(S=k),t.timelineStart=k;var _=l;l+=p;var P=s;s+=g,n.push({event:t,start:k,end:S,playout:{start:P,end:s},integrated:{start:_,end:l}})}var D=y||t.resumeTime;o=d||D>a?a:!c&&S&&t.appendInPlaceStarted&&D-S>$u?S:D}),o<a){var u,c=o,d=l,h=a-o;l+=h;var f=s;s+=h,n.push({previousEvent:(null==(u=n[n.length-1])?void 0:u.event)||null,nextEvent:null,start:o,end:c+h,playout:{start:f,end:s},integrated:{start:d,end:l}})}this.setDurations(a,s,l)}else{n.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a)}return n}},{key:"setDurations",value:function(e,t,r){this.durations={primary:e,playout:t,integrated:r}}},{key:"resolveOffsets",value:function(e,t){var r=this,n=t.main.details,i=n.live?1/0:n.edge,a=0,s=-1;e.forEach(function(o,l){var u=o.cue.pre,c=o.cue.post,d=u?0:c?i:o.startTime;(r.updateAssetDurations(o),s===d?o.cumulativeDuration=a:(a=0,s=d),!c&&o.snapOptions.in&&(o.resumeAnchor=Dr(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted)&&(r.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1));!o.appendInPlace&&l+1<e.length&&(e[l+1].startTime-e[l].resumeTime<$u&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&r.warn("Could not change append strategy for abutting event ".concat(o))));var h=x(o.resumeOffset)?o.resumeOffset:o.duration;a+=h})}},{key:"primaryCanResumeInPlaceAt",value:function(e,t){var r=this,n=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(n-i)>ju?(this.log('"'.concat(e.identifier,'" resumption ').concat(n," not aligned with estimated timeline end ").concat(i)),!1):!Object.keys(t).some(function(i){var a=t[i].details,s=a.edge;if(n>=s)return r.log('"'.concat(e.identifier,'" resumption ').concat(n," past ").concat(i," playlist end ").concat(s)),!1;var o=Dr(null,a.fragments,n);if(!o)return r.log('"'.concat(e.identifier,'" resumption ').concat(n," does not align with any fragments in ").concat(i," playlist (").concat(a.fragStart,"-").concat(a.fragmentEnd,")")),!0;var l="audio"===i?.175:0;return!(Math.abs(o.start-n)<ju+l||Math.abs(o.end-n)<ju+l)&&(r.log('"'.concat(e.identifier,'" resumption ').concat(n," not aligned with ").concat(i," fragment bounds (").concat(o.start,"-").concat(o.end," sn: ").concat(o.sn," cc: ").concat(o.cc,")")),!0)})}},{key:"updateAssetDurations",value:function(e){if(e.assetListLoaded){for(var t=e.timelineStart,r=0,n=!1,i=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+r;s.startOffset=r,s.timelineStart=o,n||(n=null===s.duration),i||(i=!!s.error),r+=s.error?0:s.duration||0}e.duration=n&&!i?Math.max(r,e.duration):r}}},{key:"removeEvent",value:function(e){e.reset(),delete this.eventMap[e.identifier]}}])}(Ee);function Zu(e){return"[".concat(e.event?'"'+e.event.identifier+'"':"primary",": ").concat(e.start.toFixed(2),"-").concat(e.end.toFixed(2),"]")}var ec=function(){return h(function e(t){c(this,e),this.hls=void 0,this.hls=t},[{key:"destroy",value:function(){this.hls=null}},{key:"loadAssetList",value:function(e,t){var r,n=this,i=e.assetListUrl;try{r=Yu(i,this.hls.sessionId,e.baseUrl)}catch(h){var a=this.assignAssetListError(e,U.ASSET_LIST_LOAD_ERROR,h,i);return void this.hls.trigger(B.ERROR,a)}t&&"data:"!==r.protocol&&or(r,"_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={type:q.INTERSTITIAL_ASSET_LIST,responseType:"json",url:r.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,r,i,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,n.hls.trigger(B.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=n.assignAssetListError(e,U.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,r,a);n.hls.trigger(B.ERROR,l)}},onError:function(t,r,i,a){var s=n.assignAssetListError(e,U.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status ".concat(t.code," ").concat(t.text," (").concat(r.url,")")),r.url,a,i);n.hls.trigger(B.ERROR,s)},onTimeout:function(t,r,i){var a=n.assignAssetListError(e,U.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(r.url,")")),r.url,t,i);n.hls.trigger(B.ERROR,a)}};return o.load(l,c,d),this.hls.trigger(B.ASSET_LIST_LOADING,{event:e}),o}},{key:"assignAssetListError",value:function(e,t,r,n,i,a){return e.error=r,{type:N.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:r,networkDetails:a,stats:i}}}])}();function tc(e){var t;null==e||null==(t=e.play())||t.catch(function(){})}function rc(e,t){return"[".concat(e,"] Advancing timeline position to ").concat(t)}var nc=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,["interstitials",e.logger])).HlsPlayerClass=void 0,n.hls=void 0,n.assetListLoader=void 0,n.mediaSelection=null,n.altSelection=null,n.media=null,n.detachedData=null,n.requiredTracks=null,n.manager=null,n.playerQueue=[],n.bufferedPos=-1,n.timelinePos=-1,n.schedule=void 0,n.playingItem=null,n.bufferingItem=null,n.waitingItem=null,n.endedItem=null,n.playingAsset=null,n.endedAsset=null,n.bufferingAsset=null,n.bufferPastEdge=!1,n.shouldPlay=!1,n.onPlay=function(){n.shouldPlay=!0},n.onPause=function(){n.shouldPlay=!1},n.onSeeking=function(){var e=n.currentTime;if(void 0!==e&&!n.playbackDisabled&&n.schedule){var t=e-n.timelinePos;if(!(Math.abs(t)<1/7056e5)){var r=t<=-.01;-1!==n.timelinePos||n.effectivePlayingItem||n.checkStart(),n.timelinePos=e,n.bufferedPos=e;var i=n.playingItem;if(i){if(r)n.schedule.resetErrorsInRange(e,e-t)&&n.updateSchedule(!0);if(n.checkBuffer(),r&&e<i.start||e>=i.end){var a,s=n.findItemIndex(i),o=n.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),n.log("seeked ".concat(r?"back ":"","to position not covered by schedule ").concat(e," (resolving from ").concat(s," to ").concat(o,")"))),!n.isInterstitial(i)&&null!=(a=n.media)&&a.paused&&(n.shouldPlay=!1),!r&&o>s){var l=n.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void n.setSchedulePosition(l)}n.setSchedulePosition(o)}else{var u=n.playingAsset;if(u){var c,d=u.timelineStart,h=u.duration||0;if(r&&e<d||e>=d+h)null!=(c=i.event)&&c.appendInPlace&&(n.clearAssetPlayers(i.event,i),n.flushFrontBuffer(e)),n.setScheduleToAssetAtTime(e,u)}else if(n.playingLastItem&&n.isInterstitial(i)){var f=i.event.assetList[0];f&&(n.endedItem=n.playingItem,n.playingItem=null,n.setScheduleToAssetAtTime(e,f))}}}else n.checkBuffer()}}},n.onTimeupdate=function(){var e=n.currentTime;if(void 0!==e&&!n.playbackDisabled&&(-1!==n.timelinePos||n.effectivePlayingItem||n.checkStart(),e>n.timelinePos)){n.timelinePos=e,e>n.bufferedPos&&n.checkBuffer();var t=n.playingItem;if(t&&!n.playingLastItem){if(e>=t.end){n.timelinePos=t.end;var r=n.findItemIndex(t);n.setSchedulePosition(r+1)}var i=n.playingAsset;if(i)e>=i.timelineStart+(i.duration||0)&&n.setScheduleToAssetAtTime(e,i)}}},n.onScheduleUpdate=function(e,t){var r=n.schedule;if(r){var i=n.playingItem,a=r.events||[],s=r.items||[],o=r.durations,l=e.map(function(e){return e.identifier}),u=!(!a.length&&!l.length);(u||t)&&n.log("INTERSTITIALS_UPDATED (".concat(a.length,"): ").concat(a,"\nSchedule: ").concat(s.map(function(e){return Zu(e)})," pos: ").concat(n.timelinePos)),l.length&&n.log("Removed events ".concat(l));var c=null,d=null;i&&(c=n.updateItem(i,n.timelinePos),n.itemsMatch(i,c)?n.playingItem=c:n.waitingItem=null),n.waitingItem=n.updateItem(n.waitingItem);var h=n.bufferingItem;if(h&&(d=n.updateItem(h,n.bufferedPos),n.itemsMatch(h,d)?n.bufferingItem=d:h.event&&(n.bufferingItem=n.playingItem,n.clearInterstitial(h.event,null))),e.forEach(function(e){e.assetList.forEach(function(e){n.clearAssetPlayer(e.identifier,null)})}),n.playerQueue.forEach(function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(i){Math.abs(r)>ju&&n.warn("".concat(i,' ("').concat(e.assetId,'" ').concat(e.timelineOffset,"->").concat(t,")"))}}}),u||t){if(n.hls.trigger(B.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),n.isInterstitial(i)&&l.indexOf(i.event.identifier)>-1)return n.warn('Interstitial "'.concat(i.event.identifier,'" removed while playing')),void n.primaryFallback(i.event);i&&n.trimInPlace(c,i),h&&d!==c&&n.trimInPlace(d,h),n.checkBuffer()}}},n.hls=e,n.HlsPlayerClass=r,n.assetListLoader=new ec(e),n.schedule=new Ju(n.onScheduleUpdate,e.logger),n.registerListeners(),n}return y(t,e),h(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(B.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(B.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(B.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(B.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(B.BUFFER_APPENDED,this.onBufferAppended,this),e.on(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(B.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(B.MEDIA_ENDED,this.onMediaEnded,this),e.on(B.ERROR,this.onError,this),e.on(B.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(B.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(B.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(B.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(B.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(B.BUFFER_CODECS,this.onBufferCodecs,this),e.off(B.BUFFER_APPENDED,this.onBufferAppended,this),e.off(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(B.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(B.MEDIA_ENDED,this.onMediaEnded,this),e.off(B.ERROR,this.onError,this),e.off(B.DESTROYING,this.onDestroying,this))}},{key:"startLoad",value:function(){this.resumeBuffering()}},{key:"stopLoad",value:function(){this.pauseBuffering()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}},{key:"onDestroying",value:function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}},{key:"removeMediaListeners",value:function(e){Ni(e,"play",this.onPlay),Ni(e,"pause",this.onPause),Ni(e,"seeking",this.onSeeking),Ni(e,"timeupdate",this.onTimeupdate)}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;Fi(r,"seeking",this.onSeeking),Fi(r,"timeupdate",this.onTimeupdate),Fi(r,"play",this.onPlay),Fi(r,"pause",this.onPause)}},{key:"onMediaAttached",value:function(e,t){var r=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!n){this.clearScheduleState();var i=this.findItemIndex(r);this.setSchedulePosition(i)}}},{key:"clearScheduleState",value:function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia,n=this.media;if(this.media=null,!r&&(n&&this.removeMediaListeners(n),this.detachedData)){var i=this.getBufferingPlayer();i&&(this.log("Removing schedule state for detachedData and ".concat(i)),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}},{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},r=function(t){return t?e.getAssetPlayer(t.identifier):t},n=function(t,n,a,s,o){if(t){var l=t[n].start,u=t.event;if(u){if("playout"===n||u.timelineOccupancy!==Ku.Point){var c=r(a);(null==c?void 0:c.interstitial)===u&&(l+=c.assetItem.startOffset+c[o])}}else l+=("bufferedPos"===s?i():e[s])-t.start;return l}return 0},i=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var r,n;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(n=e.schedule)?void 0:n.durations[t])||0},s=function(t,i){var a,s,o=e.effectivePlayingItem;if((null==o||null==(a=o.event)||!a.restrictions.skip)&&e.schedule){e.log("seek to ".concat(t,' "').concat(i,'"'));var l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,i),c=null==(s=e.schedule.items)?void 0:s[u],d=e.getBufferingPlayer(),h=null==d?void 0:d.interstitial,f=null==h?void 0:h.appendInPlace,v=l&&e.itemsMatch(l,c);if(l&&(f||v)){var g=r(e.playingAsset),p=(null==g?void 0:g.media)||e.primaryMedia;if(p){var y="primary"===i?p.currentTime:n(l,i,e.playingAsset,"timelinePos","currentTime"),m=t-y,E=(f?y:p.currentTime)+m;if(E>=0&&(!g||f||E<=g.duration))return void(p.currentTime=E)}}if(c){var k=t;if("primary"!==i){var S=t-c[i].start;k=c.start+S}var T=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!T&&!c.event.appendInPlace){if(l){var b=e.findItemIndex(l);if(u>b){var A=e.schedule.findJumpRestrictedIndex(b+1,u);if(A>b)return void e.setSchedulePosition(A)}var L=0;if(T)e.timelinePos=k,e.checkBuffer();else for(var R=c.event.assetList,I=t-(c[i]||c).start,w=R.length;w--;){var _=R[w];if(_.duration&&I>=_.startOffset&&I<_.startOffset+_.duration){L=w;break}}e.setSchedulePosition(u,L)}}else{var P=e.media||(f?null==d?void 0:d.media:null);P&&(P.currentTime=k)}}}},o=function(){var r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;var n=t();return e.isInterstitial(n)?n:null},l={get bufferedEnd(){var r,i=t(),a=e.bufferingItem;return a&&a===i&&(n(a,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-a.playout.start||(null==(r=e.bufferingAsset)?void 0:r.startOffset))||0},get currentTime(){var t=o(),r=e.effectivePlayingItem;return r&&r===t?n(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){var r=o(),n=e.effectivePlayingItem;n&&n===r&&s(t+n.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,r=null==(t=o())?void 0:t.event.assetList;return r?r.map(function(t){return e.getAssetPlayer(t.identifier)}):[]},get playingIndex(){var t,r=null==(t=o())?void 0:t.event;return r&&e.effectivePlayingAsset?r.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var r=t();return e.findItemIndex(r)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return i()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,"primary")},get duration(){return a("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){return function(t,r){var n;if(0!==t&&"primary"!==r&&null!=(n=e.schedule)&&n.length){var i,a=e.schedule.findItemIndexAtTime(t),s=null==(i=e.schedule.items)?void 0:i[a];if(s)return t+(s[r].start-s.start)}return t}(e.seekableStart,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var n=e.findItemIndex(t);if(r.appendInPlace){var i=t.playout.start+t.event.duration;s(i+.001,"playout")}else e.advanceAfterAssetEnded(r,n,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var n=this.media;!n&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(n=this.primaryMedia);var i=null==(t=n)?void 0:t.currentTime;if(void 0!==i&&x(i))return i}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"isInterstitial",value:function(e){return!(null==e||!e.event)}},{key:"retreiveMediaSource",value:function(e,t){var r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}},{key:"transferMediaFromPlayer",value:function(e,t){var r=e.interstitial.appendInPlace,n=e.media;if(r&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n)return void(this.detachedData={media:n});var i=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(mr(i))),this.detachedData=i}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}},{key:"transferMediaTo",value:function(e,t){var r,n,i=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,c=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else{var d=this.getBufferingPlayer();d?(s=d.transferMedia(),this.detachedData=s,a="".concat(d)):a=c?"detached MediaSource":"detached media"}if(!s)if(c)s=this.detachedData,this.log("using detachedData: MediaSource ".concat(mr(s)));else if(!this.detachedData||o.media===t){var h=this.playerQueue;h.length>1&&h.forEach(function(e){if(l&&e.interstitial.appendInPlace!==u){var t=e.interstitial;i.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&i.warn("Could not change append strategy for queued assets ".concat(t))}}),this.hls.detachMedia(),this.detachedData={media:t}}var f=s&&"mediaSource"in s&&"closed"!==(null==(n=s.mediaSource)?void 0:n.readyState);if(this.log("".concat(f?"transfering MediaSource":"attaching media"," to ").concat(l?e:"Primary"," from ").concat(a," (media.currentTime: ").concat(t.currentTime,")")),f||l){var v=f&&s?se({},s):{media:t},g=this.schedule;if(g&&l){var p=e.assetId===g.assetIdAtEnd;v.overrides={duration:g.duration,endOfStream:p||!1===e.appendInPlace}}if(!f&&u){var y=e,m=y.assetItem.timelineStart;if(m){var E=y.hls,k=Math.max(this.timelinePos-m,Number.EPSILON);E.startPosition!==k&&(this.log("Set ".concat(y," startPosition: ").concat(k)),E.config.startPosition=k,E.loadingEnabled&&E.startLoad(k))}}e.attachMedia(v)}else e.attachMedia(t)}}},{key:"onInterstitialCueEnter",value:function(){this.onTimeupdate()}},{key:"checkStart",value:function(){var e=this.schedule,t=null==e?void 0:e.events,r=this.hls;if(t&&!this.playbackDisabled&&this.media&&r){-1===this.bufferedPos&&(this.bufferedPos=0);var n=this.timelinePos,i=this.effectivePlayingItem;if(-1===n){if(!r.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");var a=r.startPosition;if(this.timelinePos=a,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(rc("checkStart (preroll)",a));var s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(a>=0||!this.primaryLive){this.log(rc("checkStart",a));var o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else 0===r.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(rc("checkStart (playing item)",i.start));var u=e.findItemIndex(i);this.setSchedulePosition(u)}}}},{key:"advanceAssetBuffering",value:function(e,t){var r=e.event,n=r.findAssetIndex(t),i=zu(r,n);if(r.isAssetPastPlayoutLimit(i)){if(this.schedule){var a,s=this.getNextItemIndex(e,!0),o=null==(a=this.schedule.items)?void 0:a[s];o&&this.bufferedToItem(o)}}else this.bufferedToEvent(e,i)}},{key:"livePrerollResumption",value:function(e,t){if(e.cue.pre&&this.primaryLive&&!x(e.resumeOffset)&&this.hls){var r=this.getLiveStartPos();if(t){var n=this.getBufferingPlayer();return r+(null!=n&&n.interstitial.cue.pre?n.remaining:0)}return r}}},{key:"getNextItemIndex",value:function(e,t){if(this.schedule){var r=this.livePrerollResumption(e.event,t);if(void 0!==r)return this.log("find next item index @".concat(r)),this.schedule.findItemIndexAtTime(r)}return this.findItemIndex(e)+1}},{key:"advanceAfterAssetEnded",value:function(e,t,r){var n=zu(e,r);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){var i=this.schedule.items;if(i){var a=i[t],s=a.event?this.getNextItemIndex(a):t+1;if(s>=i.length)return void this.setSchedulePosition(-1);var o=e.resumeTime;this.timelinePos<o&&(this.log(rc("advanceAfterAssetEnded",o)),this.timelinePos=o,e.appendInPlace&&!i[s].event&&this.hls.startLoad(o+.01),this.checkBuffer(this.bufferedPos<o)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){var l=e.assetList[n];l&&this.advanceInPlace(l.timelineStart)}this.setSchedulePosition(t,n)}}},{key:"setScheduleToAssetAtTime",value:function(e,t){var r=this.schedule;if(r){var n=t.parentIdentifier,i=r.getEvent(n);if(i){var a=r.findEventIndex(n),s=r.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,a,s-1)}}}},{key:"setSchedulePosition",value:function(e,t){var r,n=null==(r=this.schedule)?void 0:r.items;if(n&&!this.playbackDisabled){var i=e>=0?n[e]:null;this.log("setSchedulePosition ".concat(e,", ").concat(t," (").concat(i?Zu(i):i,") pos: ").concat(this.timelinePos));var a=this.waitingItem||this.playingItem,s=this.playingLastItem;if(this.isInterstitial(a)){var o=a.event,l=this.playingAsset,u=null==l?void 0:l.identifier,c=u?this.getAssetPlayer(u):null;if(c&&u&&(!this.eventItemsMatch(a,i)||void 0!==t&&u!==o.assetList[t].identifier)){var d,h=o.findAssetIndex(l);if(this.log("INTERSTITIAL_ASSET_ENDED ".concat(h+1,"/").concat(o.assetList.length," ").concat(Xu(l))),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(B.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:h,event:o,schedule:n.slice(0),scheduleIndex:e,player:c}),a!==this.playingItem)return void(this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),h));this.retreiveMediaSource(u,i),!c.media||null!=(d=this.detachedData)&&d.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(a,i)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log("INTERSTITIAL_ENDED ".concat(o," ").concat(Zu(a))),o.hasPlayed=!0,this.hls.trigger(B.INTERSTITIAL_ENDED,{event:o,schedule:n.slice(0),scheduleIndex:e}),o.cue.once&&this.hls)){var f;this.updateSchedule();var v=null==(f=this.schedule)?void 0:f.items;if(i&&v){var g=this.findItemIndex(i),p=this.livePrerollResumption(o);if(void 0!==p){var y=p,m=this.getNextItemIndex(a);if(!this.isInterstitial(n[m])){var E,k=null==(E=this.primaryDetails)?void 0:E.fragments;if(o.snapOptions.in&&k){var S=Dr(null,k,p);S&&(y=Math.min(Math.max(n[m].start,qu(y,S)),n[m].end))}}if(this.log(rc("live join (preroll)",y)),this.timelinePos=y,m!==g&&(m||0===m))return void this.advanceSchedule(m,v,void 0,a,s)}this.advanceSchedule(g,v,t,a,s)}return}}this.advanceSchedule(e,n,t,a,s)}}},{key:"advanceSchedule",value:function(e,t,r,n,i){var a=this,s=this.schedule;if(s){var o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(function(t){var r=t.interstitial,n=s.findEventIndex(r.identifier);(n<e||n>e+1)&&a.clearInterstitial(r,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var c=o.event;if(void 0===r){var d=zu(c,(r=c.cue.pre?0:s.findAssetIndex(c,this.timelinePos))-1);if(c.isAssetPastPlayoutLimit(d)||c.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(c,e,r);r=d}var h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(c,r);if(this.eventItemsMatch(o,h||n)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED ".concat(Zu(o)," ").concat(c.appendInPlace?"append in place":"")),c.hasPlayed=!1,this.hls.trigger(B.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading ".concat(c));if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial ".concat(c));this.waitingItem=this.endedItem=null,this.playingItem=o;var v=c.assetList[r];if(!v)return void this.advanceAfterAssetEnded(c,e,r||0);if(f||(f=this.getAssetPlayer(v.identifier)),null===f||f.destroyed){var g=c.assetList.length;this.warn("asset ".concat(r+1,"/").concat(g," player destroyed ").concat(c)),(f=this.createAssetPlayer(c,v,r)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(f,r,t,e,l),this.shouldPlay&&tc(f.media)}else o?(this.resumePrimary(o,e,n),this.shouldPlay&&tc(this.hls.media)):i&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}},{key:"resumePrimary",value:function(e,t,r){var n,i;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log("resuming ".concat(Zu(e)));var a=this.timelinePos;if(null!=(n=this.detachedData)&&n.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(rc("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),r){var s=null==(i=this.schedule)?void 0:i.items;s&&(this.log("INTERSTITIALS_PRIMARY_RESUMED ".concat(Zu(e))),this.hls.trigger(B.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}}},{key:"seekableStart",get:function(){var e;return this.primaryLive&&(null==(e=this.primaryDetails)?void 0:e.fragmentStart)||0}},{key:"getPrimaryResumption",value:function(e,t,r){var n=e.start;if(this.primaryLive){if(0===t)return this.hls.startPosition;var i=this.endedItem||this.playingItem,a=null!=i&&i.event?this.livePrerollResumption(i.event,r):void 0;if(void 0!==a)return a;var s=this.primaryDetails;if(s){var o=s.fragmentStart,l=s.edge;if(n<o||n>l&&!r){var u=this.hls.liveSyncPosition;return this.log("primary resumption out of bounds (".concat(n," [").concat(o,"-").concat(l,"]) snapping to liveSync ").concat(u)),u||o}}}return this.log("primary resumption itemStart: ".concat(n)),n}},{key:"getLiveStartPos",value:function(){var e,t=this.hls.startPosition,r=this.hls.liveSyncPosition||0,n=3*((null==(e=this.primaryDetails)?void 0:e.targetduration)||10);return-1===t||r&&r-t<n?r||0:t}},{key:"isAssetBuffered",value:function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:kn.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}},{key:"attachPrimary",value:function(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var n=this.primaryMedia;if(n){var i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,n),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(rc("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}}},{key:"startLoadingPrimaryAt",value:function(e,t){var r=this.hls,n=r.loadingEnabled,i=r.bufferingEnabled,a=r.startPosition,s=r.hasEnoughToStart;if(this.log("Start loading primary @".concat(e," bufferedPos: ").concat(this.bufferedPos," startPosition: ").concat(a," skip seek: ").concat(t," has enough ").concat(s," loadingEnabled: ").concat(n," bufferingEnabled: ").concat(i)),!t&&s||!n||Math.abs(a-e)>.1){var o=this.primaryDetails;if(null!=o&&o.live&&e+.5>=o.edge){var l=this.bufferingItem;return this.log("Resume primary loading when live passes ".concat(e," buffering item: ").concat(l?Zu(l):null)),r.pauseBuffering(),void(this.bufferPastEdge=!0)}r.startLoad(e,t)}else i||r.resumeBuffering()}},{key:"onManifestLoading",value:function(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(B.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(B.BUFFER_CODECS,this.onBufferCodecs,this)}},{key:"onLevelUpdated",value:function(e,t){if(-1!==t.level&&this.schedule){var r=this.hls.levels[t.level];if(r.details){var n=se(se({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=n;var i=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace,-1===i?0:i),this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){var a=this.primaryDetails,s=this.bufferedPos;if(null!=a&&a.live&&s+.5<a.edge){this.bufferPastEdge=!1;var o=this.bufferingItem;if(this.log("Live edge ".concat(a.edge," passed buffer: ").concat(s," buffering item: ").concat(o?Zu(o):null)),(null==o?void 0:o.end)===1/0){var l=this.playingItem,u=this.isInterstitial(l)&&l.event.appendInPlace;this.hls.startLoad(Math.max(s,o.start),u)}else{var c=this.getBufferingPlayer();if(c)c.bufferedInPlaceToEnd(this.primaryMedia,c.currentTime)&&c.hls&&c.hls.trigger(B.BUFFERED_TO_END,void 0)}}}}else this.checkStart()}}}},{key:"onAudioTrackUpdated",value:function(e,t){var r=this.hls.audioTracks[t.id],n=this.mediaSelection;if(n){var i=se(se({},n),{},{audio:r});this.mediaSelection=i}else this.altSelection=se(se({},this.altSelection),{},{audio:r})}},{key:"onSubtitleTrackUpdated",value:function(e,t){var r=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(n){var i=se(se({},n),{},{subtitles:r});this.mediaSelection=i}else this.altSelection=se(se({},this.altSelection),{},{subtitles:r})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=Sr(t);this.playerQueue.forEach(function(e){var n=e.hls;return n&&(n.setAudioOption(t)||n.setAudioOption(r))})}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r=Sr(t);this.playerQueue.forEach(function(e){var n=e.hls;return n&&(n.setSubtitleOption(t)||-1!==t.id&&n.setSubtitleOption(r))})}},{key:"onBufferCodecs",value:function(e,t){var r=t.tracks;r&&(this.requiredTracks=r)}},{key:"onBufferAppended",value:function(e,t){this.checkBuffer()}},{key:"onBufferFlushed",value:function(e,t){var r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){var n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}},{key:"onBufferedToEnd",value:function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var r=0;r<t.length;r++){var n=t[r];if(n.cue.post){var i=this.getEventItem(n.identifier);i&&this.eventItemsMatch(i,this.bufferingItem)&&this.bufferedToItem(i,0);break}}this.bufferedPos=Number.MAX_VALUE}}}},{key:"onMediaEnded",value:function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}},{key:"updateItem",value:function(e,t){var r,n=null==(r=this.schedule)?void 0:r.items;return e&&n&&n[this.findItemIndex(e,t)]||null}},{key:"trimInPlace",value:function(e,t){var r=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach(function(t,n){e.event.isAssetPastPlayoutLimit(n)&&r.clearAssetPlayer(t.identifier,null)});var n=e.end+.25,i=kn.bufferInfo(this.primaryMedia,n,0);if(i.end>n||(i.nextStart||0)>n){this.log("trim buffered interstitial ".concat(Zu(e)," (was ").concat(Zu(t),")"));this.attachPrimary(n,null,!0),this.flushFrontBuffer(n)}}}},{key:"itemsMatch",value:function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}},{key:"eventItemsMatch",value:function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))}},{key:"findEventIndex",value:function(e){return this.schedule?this.schedule.findEventIndex(e):-1}},{key:"getEventItem",value:function(e){if(this.schedule){var t,r=null==(t=this.schedule.items)?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(r)&&r.event.identifier===e)return r}}},{key:"findItemIndex",value:function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}},{key:"updateSchedule",value:function(){var e,t,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=this.mediaSelection;if(n){var i=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(t=this.schedule)||t.updateSchedule(n,[],i,r)}}},{key:"checkBuffer",value:function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var n=kn.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,r,e)}}},{key:"updateBufferedPos",value:function(e,t,r){var n=this.schedule,i=this.bufferingItem;if(!(this.bufferedPos>e)&&n)if(1===t.length&&this.itemsMatch(t[0],i))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u=this.findItemIndex(i),c=Math.min(u+1,t.length-1),d=t[c];if((-1===o&&i&&e>=i.end||null!=(l=d.event)&&l.appendInPlace&&e+.01>=d.start)&&(o=c),this.isInterstitial(i)){var h=i.event;if(c-s>1&&!1===h.appendInPlace)return;if(0===h.assetList.length&&h.assetListLoader)return}if(this.bufferedPos=e,o>u&&o>s)this.bufferedToItem(d);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else r&&a&&!this.itemsMatch(a,i)&&(o===s?this.bufferedToItem(a):o===s+1&&this.bufferedToItem(t[o]))}}},{key:"assetsBuffered",value:function(e,t){var r=this;return 0!==e.event.assetList.length&&!e.event.assetList.some(function(e){var n=r.getAssetPlayer(e.identifier);return!(null!=n&&n.bufferedInPlaceToEnd(t))})}},{key:"setBufferingItem",value:function(e){var t=this,r=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,r)&&n){var i=n.items,a=n.events;if(!i||!a)return r;var s=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));var l=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(Zu(e))+(r?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled)if(s){var u=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(function(e,r){var n=t.getAssetPlayer(e.identifier);n&&(r===u&&n.loadSource(),n.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(function(e){return e.pauseBuffering()});this.hls.trigger(B.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return r}},{key:"bufferedToItem",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==r){this.bufferingAsset=null;var n=this.getPrimaryResumption(e,this.findItemIndex(e),!0),i=this.bufferedPos=Math.max(n,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)if(a.mediaSource){this.attachPrimary(i,e,!0)}else this.startLoadingPrimaryAt(i);else{var s=this.playingItem,o=this.isInterstitial(s)&&s.event.appendInPlace;this.startLoadingPrimaryAt(i,o)}}}},{key:"bufferedToEvent",value:function(e,t){var r=e.event,n=0===r.assetList.length&&!r.assetListLoader,i=r.cue.once;if(n||!i){var a=this.preloadAssets(r,t);if(null!=a&&a.interstitial.appendInPlace){var s=this.primaryMedia;s&&this.bufferAssetPlayer(a,s)}}}},{key:"preloadAssets",value:function(e,t){var r=e.assetUrl,n=e.assetList.length,i=0===n&&!e.assetListLoader,a=e.cue.once;if(i){var s,o,l=e.timelineStart,u=this.playingItem,c=this.getBufferingPlayer();if(e.appendInPlace)this.isInterstitial(u)||(null==u||null==(s=u.nextEvent)?void 0:s.identifier)!==e.identifier||this.flushFrontBuffer(l+.25);var d=0;if(c&&!c.interstitial.cue.pre||!this.primaryLive||(d=this.getLiveStartPos(),c&&(d+=c.remaining)),d&&!e.cue.pre&&!e.cue.post){var h=d-l;h>0&&(o=Math.round(1e3*h)/1e3)}if(this.log("Load interstitial asset ".concat(t+1,"/").concat(r?1:n," ").concat(e).concat(d?" live-start: ".concat(d," start-offset: ").concat(o," (timeline-start: ").concat(l,")"):"")),r)return this.createAsset(e,0,0,l,e.duration,r);var f=this.assetListLoader.loadAssetList(e,o);f&&(e.assetListLoader=f)}else if(!a&&n){for(var v=t;v<n;v++){var g=e.assetList[v],p=this.getAssetPlayerQueueIndex(g.identifier);-1!==p&&!this.playerQueue[p].destroyed||g.error||this.createAssetPlayer(e,g,v)}var y=e.assetList[t];if(y){var m=this.getAssetPlayer(y.identifier);return m&&m.loadSource(),m}}return null}},{key:"flushFrontBuffer",value:function(e){var t=this,r=this.requiredTracks;if(r){var n=this.primaryDetails;if(!(n&&e>=n.edge))this.log("Removing front buffer starting at ".concat(e)),Object.keys(r).forEach(function(r){t.hls.trigger(B.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}}},{key:"getAssetPlayerQueueIndex",value:function(e){for(var t=this.playerQueue,r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}},{key:"getAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}},{key:"getBufferingPlayer",value:function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var r=0;r<e.length;r++)if(e[r].media===t)return e[r];return null}},{key:"createAsset",value:function(e,t,r,n,i,a){var s={parentIdentifier:e.identifier,identifier:Hu(e,a,t),duration:i,startOffset:r,timelineStart:n,uri:a};return this.createAssetPlayer(e,s,t)}},{key:"createAssetPlayer",value:function(e,t,r){var n=this,i=this.hls,a=i.userConfig,s=wr(i.loadLevelObj||i.levels[i.currentLevel],a.videoPreference),o=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack],u=0;if(this.primaryLive||e.appendInPlace){var c=this.timelinePos-t.timelineStart;if(c>=0){var d=t.duration;d&&c<d&&(u=c)}}var h=t.identifier,f=se(se({},a),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:o||a.audioPreference,subtitlePreference:l||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(f.timelineOffset=t.timelineStart));var v=f.cmcd;null!=v&&v.sessionId&&v.contentId&&(f.cmcd=ie({},v,{contentId:Jl(t.uri)})),this.getAssetPlayer(h)&&this.warn("Duplicate date range identifier ".concat(e," and asset ").concat(h));var g=new Qu(this.HlsPlayerClass,f,e,t);this.playerQueue.push(g),e.assetList[r]=t;var p=!0,y=function(i){if(i.live){var a=new Error("Interstitials MUST be VOD assets ".concat(e)),s={fatal:!0,type:N.OTHER_ERROR,details:U.INTERSTITIAL_ASSET_ITEM_ERROR,error:a},o=n.findEventIndex(e.identifier);n.handleAssetItemError(s,e,o,r,a.message)}else{var l=i.edge-i.fragmentStart,u=t.duration;(p||null===u||l>u)&&(p=!1,n.log('Interstitial asset "'.concat(h,'" duration change ').concat(u," > ").concat(l)),t.duration=l,n.updateSchedule())}};g.on(B.LEVEL_UPDATED,function(e,t){var r=t.details;return y(r)}),g.on(B.LEVEL_PTS_UPDATED,function(e,t){var r=t.details;return y(r)}),g.on(B.EVENT_CUE_ENTER,function(){return n.onInterstitialCueEnter()});var m=function(e,t){var r=n.getAssetPlayer(h);if(r&&t.tracks){r.off(B.BUFFER_CODECS,m),r.tracks=t.tracks;var i=n.primaryMedia;n.bufferingAsset===r.assetItem&&i&&!r.media&&n.bufferAssetPlayer(r,i)}};g.on(B.BUFFER_CODECS,m);g.on(B.BUFFERED_TO_END,function(){var t=n.getAssetPlayer(h);if(n.log("buffered to end of asset ".concat(t)),t&&n.schedule){var r=n.getEventItem(e.identifier);r&&n.advanceAssetBuffering(r,t.assetItem)}});var E=function(t){return function(){if(n.getAssetPlayer(h)&&n.schedule){n.shouldPlay=!0;var r=n.findEventIndex(e.identifier);n.advanceAfterAssetEnded(e,r,t)}}};return g.once(B.MEDIA_ENDED,E(r)),g.once(B.PLAYOUT_LIMIT_REACHED,E(1/0)),g.on(B.ERROR,function(t,i){if(n.schedule){var a=n.getAssetPlayer(h);if(i.details===U.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void n.handleInPlaceStall(e):(n.onTimeupdate(),void n.checkBuffer(!0));i.details!==U.BUFFER_SEEK_OVER_HOLE&&n.handleAssetItemError(i,e,n.findEventIndex(e.identifier),r,"Asset player error ".concat(i.error," ").concat(e))}}),g.on(B.DESTROYING,function(){if(n.getAssetPlayer(h)&&n.schedule){var t=new Error("Asset player destroyed unexpectedly ".concat(h)),i={fatal:!0,type:N.OTHER_ERROR,details:U.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};n.handleAssetItemError(i,e,n.findEventIndex(e.identifier),r,t.message)}}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(Xu(t))),this.hls.trigger(B.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:g}),g}},{key:"clearInterstitial",value:function(e,t){this.clearAssetPlayers(e,t),e.reset()}},{key:"clearAssetPlayers",value:function(e,t){var r=this;e.assetList.forEach(function(e){r.clearAssetPlayer(e.identifier,t)})}},{key:"resetAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'.concat(e,'" after error'));var r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}},{key:"clearAssetPlayer",value:function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var n=this.playerQueue[r];this.log("clear ".concat(n," toSegment: ").concat(t?Zu(t):t)),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(r,1),n.destroy()}}},{key:"emptyPlayerQueue",value:function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}},{key:"startAssetPlayer",value:function(e,t,r,n,i){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,(null==u?void 0:u.identifier)!==o&&(u&&(this.clearAssetPlayer(u.identifier,r[n]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED ".concat(t+1,"/").concat(l," ").concat(Xu(s))),this.hls.trigger(B.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,i)}},{key:"bufferAssetPlayer",value:function(e,t){var r;if(this.schedule){var n=e.interstitial,i=e.assetItem,a=this.getEventItem(n.identifier);if(a)if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=i,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime))this.advanceAssetBuffering(a,i);else{var s=this.getBufferingPlayer();if(s!==e){var o=n.appendInPlace;if(!o||!1!==(null==s?void 0:s.interstitial.appendInPlace)){var l=(null==s?void 0:s.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(o&&i!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering ".concat(e));if(l&&!Ie(l,e.tracks)){var u=new Error("Asset ".concat(Xu(i)," SourceBuffer tracks ('").concat(Object.keys(e.tracks),"') are not compatible with primary content tracks ('").concat(Object.keys(l),"')")),c={fatal:!0,type:N.OTHER_ERROR,details:U.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},d=n.findAssetIndex(i);return void this.handleAssetItemError(c,n,this.findEventIndex(n.identifier),d,u.message)}}this.transferMediaTo(e,t)}}}}}},{key:"handleInPlaceStall",value:function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var n=r.currentTime,i=t.findAssetIndex(e,n),a=e.assetList[i];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||n-a.timelineStart,l=s.duration-o;if(this.warn("Stalled at ".concat(o," of ").concat(o+l," in ").concat(s," ").concat(e," (media.currentTime: ").concat(n,")")),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r,s.currentTime))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,i)}}}}}},{key:"advanceInPlace",value:function(e){var t=this.primaryMedia;if(t&&t.currentTime<e){var r="advance currentTime to ".concat(e,", duration: ").concat(t.duration);t.duration>e?(this.log(r),t.currentTime=e):this.log("Cannot ".concat(r))}}},{key:"handleAssetItemError",value:function(e,t,r,n,i){if(e.details!==U.BUFFER_STALLED_ERROR){var a=t.assetList[n]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR ".concat(a?Xu(a):a," ").concat(e.error)),this.schedule){var s=(null==a?void 0:a.identifier)||"",o=this.getAssetPlayerQueueIndex(s),l=this.playerQueue[o]||null,u=this.schedule.items,c=ie({},e,{fatal:!1,errorAction:Xr(!0),asset:a,assetListIndex:n,event:t,schedule:u,scheduleIndex:r,player:l});if(this.hls.trigger(B.INTERSTITIAL_ASSET_ERROR,c),e.fatal){var d=this.playingAsset,h=this.bufferingAsset,f=new Error(i);if(a&&(this.clearAssetPlayer(s,null),a.error=f),t.assetList.some(function(e){return!e.error}))for(var v=n;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):(null==d?void 0:d.identifier)===s?this.advanceAfterAssetEnded(t,r,n):(null==h?void 0:h.identifier)===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}}}}},{key:"primaryFallback",value:function(e){var t=e.timelineStart,r=this.effectivePlayingItem,n=this.playingItem,i=this.seekableStart,a=this.hls.startPosition,s=this.timelinePos;if(this.isInterstitial(r)){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(s," playing: ").concat(Zu(r)," startPosition: ").concat(a," seekableStart: ").concat(i," error: ").concat(e.error)),-1===s&&(s=a),s=Math.max(s,i);var o=this.updateItem(r,s);this.itemsMatch(r,o)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===s)return void this.checkStart();if(this.schedule&&this.isInterstitial(n)){var l=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(l)}}},{key:"onAssetListLoaded",value:function(e,t){var r,n,i=this,a=t.event,s=a.identifier,o=t.assetListResponse.ASSETS;if(null!=(r=this.schedule)&&r.hasEvent(s)){var l=a.timelineStart,u=a.duration,c=0;o.forEach(function(e,t){var r=parseFloat(e.DURATION);i.createAsset(a,t,c,l+c,r,e.URI),c+=r}),a.duration=c,this.log("Loaded asset-list with duration: ".concat(c," (was: ").concat(u,") ").concat(a));var d=this.waitingItem,h=(null==d?void 0:d.event.identifier)===s;this.updateSchedule();var f=null==(n=this.bufferingItem)?void 0:n.event;if(h){var v=this.findEventIndex(s),g=this.getEventItem(s);if(g){if(!this.playingItem&&this.timelinePos>g.end)if(this.schedule.findItemIndexAtTime(this.timelinePos)!==v)return a.error=new Error("Interstitial ".concat(o.length?"no longer within playback range":"asset-list is empty"," ").concat(this.timelinePos," ").concat(a)),this.log(a.error.message),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(g)}this.setSchedulePosition(v)}else if((null==f?void 0:f.identifier)===s){var p=a.assetList[0];if(p){var y=this.getAssetPlayer(p.identifier);if(f.appendInPlace){var m=this.primaryMedia;y&&m&&this.bufferAssetPlayer(y,m)}else y&&y.loadSource()}}}}},{key:"onError",value:function(e,t){if(this.schedule)switch(t.details){case U.ASSET_LIST_PARSING_ERROR:case U.ASSET_LIST_LOAD_ERROR:case U.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case U.BUFFER_STALLED_ERROR:var n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace)return void this.handleInPlaceStall(n.event);var i=this.primaryMedia;this.log("Primary player stall @".concat(this.timelinePos," currentTime: ").concat(null==i?void 0:i.currentTime," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}])}(Ee),ic=function(){return h(function e(t){var r=this;c(this,e),this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e,t=r.media,n=r.levelDetails;if(t&&n&&r.hls){r.currentTime=t.currentTime;var i=r.hls.config,a=r.computeLatency();if(null!==a){r._latency=a;var s=i.lowLatencyMode,o=i.maxLiveSyncPlaybackRate;if(s&&1!==o&&n.live){var l=r.targetLatency;if(null!==l){var u=a-l,c=u<Math.min(r.maxLatency,l+n.targetduration),d=Zi(i)&&!(null==(e=r.hls.interstitialsManager)||null==(e=e.playingItem)||!e.event);if(c&&u>.05&&r.forwardBufferLength>1&&!d){var h=Math.min(2,Math.max(1,o)),f=Math.round(2/(1+Math.exp(-.75*u-r.edgeStalled))*20)/20,v=Math.min(h,Math.max(1,f));r.changeMediaPlaybackRate(t,v)}else 1!==t.playbackRate&&0!==t.playbackRate&&r.changeMediaPlaybackRate(t,1)}}}}},this.hls=t,this.registerListeners()},[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e,t=null==(e=this.hls)?void 0:e.config;if(!t)return 0;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;var r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return null;var t=this.hls.config,r=e.holdBack,n=e.partHoldBack,i=e.targetduration,a=t.liveSyncDuration,s=t.liveSyncDurationCount,o=t.lowLatencyMode,l=this.hls.userConfig,u=o&&n||r;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var c=i;return u+Math.min(this.stallCount*t.liveSyncOnStallIncrease,c)},set:function(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t||!this.hls)return null;var r=this.levelDetails;if(null===r)return null;var n=r.edge,i=e-t-this.edgeStalled,a=n-r.totalduration,s=n-(this.hls.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,i),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return 0;var t=3*(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.ERROR,this.onError,this),e.on(B.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.ERROR,this.onError,this),e.off(B.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}},{key:"onMediaDetaching",value:function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}},{key:"onManifestLoading",value:function(){this._latency=null,this.stallCount=0}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}},{key:"onAssetStarted",value:function(e,t){var r,n=this.hls,i=this.media||t.event.appendInPlace&&(null==n||null==(r=n.interstitialsManager)?void 0:r.playerQueue.reduce(function(e,t){return e||t.media},null));n&&i&&i.playbackRate>1&&i.playbackRate<=n.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(i,1)}},{key:"onError",value:function(e,t){var r;t.details===U.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}},{key:"changeMediaPlaybackRate",value:function(e,t){var r,n;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(n=this.targetLatency)?void 0:n.toFixed(3),", forwardBufferLength=").concat(this.forwardBufferLength.toFixed(3),": adjusting playback rate from ").concat(e.playbackRate," to ").concat(t)),e.playbackRate=t)}},{key:"estimateLiveEdge",value:function(){var e=this.levelDetails;return null===e?null:e.edge+e.age}},{key:"computeLatency",value:function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}])}(),ac=function(e){function t(e,r,n){var i;return c(this,t),(i=u(this,t,[e,r,n,"subtitle-stream-controller",W.SUBTITLE])).currentTrackId=-1,i.tracksBuffered=[],i.mainDetails=null,i.registerListeners(),i}return y(t,e),h(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),R(t,"onHandlerDestroying",this)([]),this.mainDetails=null}},{key:"registerListeners",value:function(){R(t,"registerListeners",this)([]);var e=this.hls;e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(B.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"unregisterListeners",value:function(){R(t,"unregisterListeners",this)([]);var e=this.hls;e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(B.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"startLoad",value:function(e,t){this.stopLoad(),this.state=Gi,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"onManifestLoading",value:function(){R(t,"onManifestLoading",this)([]),this.mainDetails=null}},{key:"onMediaDetaching",value:function(e,r){this.tracksBuffered=[],R(t,"onMediaDetaching",this)([e,r])}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details}},{key:"onSubtitleFragProcessed",value:function(e,t){var r=t.frag,n=t.part;if(t.success){var i=this.tracksBuffered[this.currentTrackId];if(i){for(var a,s=(n||r).start,o=0;o<i.length;o++)if(s>=i[o].start&&s<=i[o].end){a=i[o];break}var l=s+(n||r).duration;if(a?a.end=l:(a={start:s,end:l},i.push(a)),!n||l>=r.end){var u=this.fragmentTracker.fragBuffered(r);n&&u&&(u.range.subs={time:[{startPTS:r.start,endPTS:l}],partial:!0}),$(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n),this.media&&this.tickImmediate()}}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,n=t.endOffset;if(0===r&&n!==Number.POSITIVE_INFINITY){var i=n-1;if(i<=0)return;t.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(function(e){if(e)for(var t=0;t<e.length;)if(e[t].end<=i)e.shift();else{if(!(e[t].start<i))break;e[t].start=i,t++}}),this.fragmentTracker.removeFragmentsInRange(r,i,W.SUBTITLE)}}},{key:"onError",value:function(e,t){var r=t.frag;(null==r?void 0:r.type)===W.SUBTITLE&&(t.details===U.FRAG_GAP&&this.fragmentTracker.addAsGap(r),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Bi&&(this.state=Gi))}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,n=t.subtitleTracks;this.levels&&Ds(this.levels,n)?this.levels=n.map(function(e){return new gr(e)}):(this.tracksBuffered=[],this.levels=n.map(function(e){var t=new gr(e);return r.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,W.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r;if(this.currentTrackId=t.id,this.abortCurrentFrag(),null!=(r=this.levels)&&r.length&&-1!==this.currentTrackId){var n=this.levels[this.currentTrackId];null!=n&&n.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Bi&&this.setInterval(500)):this.mediaBuffer=null}else this.clearInterval()}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r,n=this.currentTrackId,i=this.levels,a=t.details,s=t.id;if(i){var o=i[s];if(!(s>=i.length)&&o){this.log("Subtitle track ".concat(s," loaded [").concat(a.startSN,",").concat(a.endSN,"]").concat(a.lastPartSn?"[part-".concat(a.lastPartSn,"-").concat(a.lastPartIndex,"]"):"",",duration:").concat(a.totalduration)),this.mediaBuffer=this.mediaBufferTimeRanges;var l=this.mainDetails,u=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var c;if(o.details)u=this.alignPlaylists(a,o.details,null==(c=this.levelLastLoaded)?void 0:c.details);a.alignedSliding||(Mi(l,a,this),u=a.fragmentStart)}o.details=a,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,u),s===n&&(this.hls.trigger(B.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tickImmediate())}}else this.warn("Subtitle tracks were reset while loading level ".concat(s))}},{key:"_handleFragmentLoadProgress",value:function(e){var t=e.frag,r=e.part,n=e.payload;r&&null!=n&&n.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(n,t,r)}},{key:"_handleFragmentLoadComplete",value:function(e){var t=e.frag,r=e.payload;!this.fragContextChanged(t)&&null!=r&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,null)}},{key:"shouldDecrypt",value:function(e){var t=e.decryptdata;return!!(null!=t&&t.key&&t.iv&&Mn(t.method))}},{key:"decryptPayload",value:function(e,t,r){var n=this,i=t.decryptdata,a=performance.now();this.decrypter.decrypt(new Uint8Array(e),i.key.buffer,i.iv.buffer,Fn(i.method)).then(function(e){n.fragContextChanged(t)||n.hls.trigger(B.FRAG_DECRYPTED,{frag:t,part:r,payload:e,stats:{tstart:a,tdecrypt:performance.now()}})}).catch(function(e){n.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:r}),r||(n.warn("".concat(e.name,": ").concat(e.message)),n.state=Gi)})}},{key:"doTick",value:function(){if(this.state===Gi&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;var t=this.currentTrackId,r=this.levels[t],n=null==r?void 0:r.details;if(!n||this.waitForLive(r)||this.waitForCdnTuneIn(n))return void(this.startFragRequested=!1);var i=this.config,a=this.playhead,s=kn.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a,i.maxBufferHole),o=s.end,l=s.len;if(l>Math.max(this.hls.maxBufferLength+n.levelTargetDuration,(null==(e=this.hls.mainForwardBufferInfo)?void 0:e.len)||0)||l&&!this.buffering)return;var u=this.getNextFragment(o,n);if(!u)return;if($(u)){var c,d=u.sn-n.startSN,h=n.fragments[d-1];u.cc!==(null==h?void 0:h.cc)||null!=(c=n.partList)&&c.length||this.fragmentTracker.getState(h)!==Qr||(u=h)}this.loadFragment(u,r,o)}}},{key:"loadFragment",value:function(e,r,n){var i=this.fragmentTracker.getState(e);i!==Qr&&i!==Jr||R(t,"loadFragment",this)([e,r,n])}},{key:"mediaBufferTimeRanges",get:function(){return new sc(this.tracksBuffered[this.currentTrackId]||[])}}])}($i),sc=h(function e(t){c(this,e),this.buffered=void 0;var r=function(e,r,n){if((r>>>=0)>n-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(r,") is greater than the maximum bound (").concat(n,")"));return t[r][e]};this.buffered={get length(){return t.length},end:function(e){return r("end",e,t.length)},start:function(e){return r("start",e,t.length)}}}),oc={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},lc=function(e){return String.fromCharCode(oc[e]||e)},uc=15,cc=42,dc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},hc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},fc={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},vc={25:2,26:4,29:6,30:8,31:10,27:13,28:15},gc=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],pc=function(){return h(function e(){c(this,e),this.time=null,this.verboseLevel=0},[{key:"log",value:function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;Le.log("".concat(this.time," [").concat(e,"] ").concat(r))}}}])}(),yc=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},mc=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),Ec=function(){return h(function e(){c(this,e),this.styles=mc},[{key:"foreground",get:function(){return this.styles.foreground},set:function(e){var t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}},{key:"underline",get:function(){return this.styles.underline},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}},{key:"italics",get:function(){return this.styles.italics},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}},{key:"background",get:function(){return this.styles.background},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}},{key:"flash",get:function(){return this.styles.flash},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}},{key:"reset",value:function(){this.styles=mc}},{key:"setStyles",value:function(e){var t=this.styles,r=Object.prototype.hasOwnProperty;this.styles={foreground:r.call(e,"foreground")?e.foreground:t.foreground,underline:r.call(e,"underline")?e.underline:t.underline,italics:r.call(e,"italics")?e.italics:t.italics,background:r.call(e,"background")?e.background:t.background,flash:r.call(e,"flash")?e.flash:t.flash}}},{key:"toString",value:function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}])}(),kc=function(){return h(function e(){c(this,e),this.uchar=" ",this.penState=new Ec},[{key:"reset",value:function(){this.uchar=" ",this.penState.reset()}},{key:"setChar",value:function(e,t){this.uchar=e,this.penState.styles=t.styles}},{key:"setPenState",value:function(e){this.penState.styles=e.styles}},{key:"copy",value:function(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}])}(),Sc=function(){return h(function e(t){c(this,e),this.chars=[],this.pos=0,this.currPenState=new Ec,this.cueStartTime=null,this.logger=void 0;for(var r=0;r<cc;r++)this.chars.push(new kc);this.logger=t},[{key:"equals",value:function(e){for(var t=this.chars,r=e.chars,n=0;n<cc;n++){var i=t[n],a=r[n];if(i.uchar!==a.uchar)return!1;var s=i.penState.styles,o=a.penState.styles;if(s!==o&&(s.foreground!==o.foreground||s.underline!==o.underline||s.italics!==o.italics||s.background!==o.background||s.flash!==o.flash))return!1}return!0}},{key:"copy",value:function(e){for(var t=0;t<cc;t++)this.chars[t].copy(e.chars[t])}},{key:"isEmpty",value:function(){for(var e=this.chars,t=0;t<cc;t++){var r=e[t];if(" "!==r.uchar)return!1;var n=r.penState.styles;if(n!==mc&&("white"!==n.foreground||n.underline||n.italics||"black"!==n.background||n.flash))return!1}return!0}},{key:"setCursor",value:function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=cc&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}},{key:"moveCursor",value:function(e){var t=Math.min(this.pos+e,cc);if(e>1)for(var r=this.pos+1;r<t;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}},{key:"backSpace",value:function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}},{key:"insertChar",value:function(e){var t=this;e>=144&&this.backSpace();var r=lc(e);this.pos>=cc?this.logger.log(0,function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"}):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))}},{key:"clearFromPos",value:function(e){var t;for(t=e;t<cc;t++)this.chars[t].reset()}},{key:"clear",value:function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}},{key:"clearToEndOfRow",value:function(){this.clearFromPos(this.pos)}},{key:"getTextString",value:function(){for(var e=[],t=!0,r=0;r<cc;r++){var n=this.chars[r].uchar;" "!==n&&(t=!1),e.push(n)}return t?"":e.join("")}},{key:"setPenStyles",value:function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}])}(),Tc=function(){return h(function e(t){c(this,e),this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var r=0;r<uc;r++)this.rows.push(new Sc(t));this.logger=t},[{key:"reset",value:function(){for(var e=0;e<uc;e++)this.rows[e].clear();this.currRow=14}},{key:"equals",value:function(e){for(var t=!0,r=0;r<uc;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}},{key:"copy",value:function(e){for(var t=0;t<uc;t++)for(var r=this.rows[t].chars,n=e.rows[t].chars,i=0;i<cc;i++){var a=r[i],s=n[i];a.uchar=s.uchar,a.penState.styles=s.penState.styles}}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<uc;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}},{key:"backSpace",value:function(){this.rows[this.currRow].backSpace()}},{key:"clearToEndOfRow",value:function(){this.rows[this.currRow].clearToEndOfRow()}},{key:"insertChar",value:function(e){this.rows[this.currRow].insertChar(e)}},{key:"setPen",value:function(e){this.rows[this.currRow].setPenStyles(e)}},{key:"moveCursor",value:function(e){this.rows[this.currRow].moveCursor(e)}},{key:"setCursor",value:function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}},{key:"setPAC",value:function(e){this.logger.log(2,function(){return"pacData = "+mr(e)});var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<uc;r++)this.rows[r].clear();var n=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){var a=i.rows[n].cueStartTime,s=this.logger.time;if(null!==a&&null!==s&&a<s)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(i.rows[n+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var u=e.indent,c=Math.max(u-1,0);l.setCursor(e.indent),e.color=l.chars[c].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)}},{key:"setBkgData",value:function(e){this.logger.log(2,function(){return"bkgData = "+mr(e)}),this.backSpace(),this.setPen(e),this.insertChar(32)}},{key:"setRollUpRows",value:function(e){this.nrRollUpRows=e}},{key:"rollUp",value:function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,function(){return e.getDisplayText()});var t=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")}},{key:"getDisplayText",value:function(e){e=e||!1;for(var t=[],r="",n=-1,i=0;i<uc;i++){var a=this.rows[i].getTextString();a&&(n=i+1,e?t.push("Row "+n+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}])}(),bc=function(){return h(function e(t,r,n){c(this,e),this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new Tc(n),this.nonDisplayedMemory=new Tc(n),this.lastOutputScreen=new Tc(n),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n},[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}},{key:"getHandler",value:function(){return this.outputFilter}},{key:"setHandler",value:function(e){this.outputFilter=e}},{key:"setPAC",value:function(e){this.writeScreen.setPAC(e)}},{key:"setBkgData",value:function(e){this.writeScreen.setBkgData(e)}},{key:"setMode",value:function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,function(){return"MODE="+e}),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}},{key:"insertChars",value:function(e){for(var t=this,r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);var n=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,function(){return n+": "+t.writeScreen.getDisplayText(!0)}),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)}),this.outputDataUpdate())}},{key:"ccRCL",value:function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}},{key:"ccBS",value:function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}},{key:"ccAOF",value:function(){}},{key:"ccAON",value:function(){}},{key:"ccDER",value:function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}},{key:"ccRU",value:function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}},{key:"ccFON",value:function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}},{key:"ccRDC",value:function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}},{key:"ccTR",value:function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}},{key:"ccRTD",value:function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}},{key:"ccEDM",value:function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}},{key:"ccCR",value:function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}},{key:"ccENM",value:function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}},{key:"ccEOC",value:function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,function(){return"DISP: "+e.displayedMemory.getDisplayText()})}this.outputDataUpdate(!0)}},{key:"ccTO",value:function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}},{key:"ccMIDROW",value:function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+mr(t)),this.writeScreen.setPen(t)}},{key:"outputDataUpdate",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}},{key:"cueSplitAtTime",value:function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}])}(),Ac=function(){return h(function e(t,r,n){c(this,e),this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new pc,this.field=t,this.outputFilters=[null,r,n]},[{key:"getHandler",value:function(e){return this.outputFilters[e]}},{key:"setHandler",value:function(e,t){var r;this.outputFilters[e]=t,null==(r=this.channels[e])||r.setHandler(t)}},{key:"getChannel",value:function(e){var t=this.channels[e];return t||(t=this.channels[e]=new bc(this.field+e-1,this.outputFilters[e],this.logger)),t}},{key:"addData",value:function(e,t){var r=this;this.logger.time=e;for(var n=function(e){var n=127&t[e],i=127&t[e+1],a=!1,s=null;if(0===n&&0===i)return 0;r.logger.log(3,function(){return"["+yc([t[e],t[e+1]])+"] -> ("+yc([n,i])+")"});var o=r.cmdHistory;if(n>=16&&n<=31){if(function(e,t,r){return r.a===e&&r.b===t}(n,i,o))return Lc(null,null,o),r.logger.log(3,function(){return"Repeated command ("+yc([n,i])+") is dropped"}),0;Lc(n,i,r.cmdHistory),(a=r.parseCmd(n,i))||(a=r.parseMidrow(n,i)),a||(a=r.parsePAC(n,i)),a||(a=r.parseBackgroundAttributes(n,i))}else Lc(null,null,o);if(!a&&(s=r.parseChars(n,i))){var l=r.currentChannel;if(l&&l>0)r.getChannel(l).insertChars(s);else r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,function(){return"Couldn't parse cleaned data "+yc([n,i])+" orig: "+yc([t[e],t[e+1]])})},i=0;i<t.length;i+=2)n(i)}},{key:"parseCmd",value:function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,n=this.getChannel(r);return 20===e||21===e||28===e||29===e?32===t?n.ccRCL():33===t?n.ccBS():34===t?n.ccAOF():35===t?n.ccAON():36===t?n.ccDER():37===t?n.ccRU(2):38===t?n.ccRU(3):39===t?n.ccRU(4):40===t?n.ccFON():41===t?n.ccRDC():42===t?n.ccTR():43===t?n.ccRTD():44===t?n.ccEDM():45===t?n.ccCR():46===t?n.ccENM():47===t&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}},{key:"parseMidrow",value:function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var n=this.channels[r];return!!n&&(n.ccMIDROW(t),this.logger.log(3,function(){return"MIDROW ("+yc([e,t])+")"}),!0)}return!1}},{key:"parsePAC",value:function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;var n=e<=23?1:2;return r=t>=64&&t<=95?1===n?dc[e]:fc[e]:1===n?hc[e]:vc[e],this.getChannel(n).setPAC(this.interpretPAC(r,t)),this.currentChannel=n,!0}},{key:"interpretPAC",value:function(e,t){var r,n={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,n.underline=!(1&~r),r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=4*Math.floor((r-16)/2),n}},{key:"parseChars",value:function(e,t){var r,n,i=null,a=null;(e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19)?(n=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,function(){return"Special char '"+lc(n)+"' in channel "+r}),i=[n]):e>=32&&e<=127&&(i=0===t?[e]:[e,t]);return i&&this.logger.log(3,function(){return"Char codes = "+yc(i).join(",")}),i}},{key:"parseBackgroundAttributes",value:function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var n={};16===e||24===e?(r=Math.floor((t-32)/2),n.background=gc[r],t%2==1&&(n.background=n.background+"_semi")):45===t?n.background="transparent":(n.foreground="black",47===t&&(n.underline=!0));var i=e<=23?1:2;return this.getChannel(i).setBkgData(n),!0}},{key:"reset",value:function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}Lc(null,null,this.cmdHistory)}},{key:"cueSplitAtTime",value:function(e){for(var t=0;t<this.channels.length;t++){var r=this.channels[t];r&&r.cueSplitAtTime(e)}}}])}();function Lc(e,t,r){r.a=e,r.b=t}var Rc=function(){return h(function e(t,r){c(this,e),this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r},[{key:"dispatchCue",value:function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}},{key:"newCue",value:function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}},{key:"reset",value:function(){this.cueRanges=[],this.startTime=null}}])}(),Ic=function(){return h(function e(t){c(this,e),this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(B.MANIFEST_LOADING,this.onManifestLoading,this),t.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(B.FRAG_LOADING,this.onFragLoading,this),t.on(B.FRAG_LOADED,this.onFragLoaded,this),t.on(B.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(B.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(B.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(B.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(B.BUFFER_APPENDED,this.onBufferAppended,this),t.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this)},[{key:"destroy",value:function(){var e=this.hls;e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(B.FRAG_LOADING,this.onFragLoading,this),e.off(B.FRAG_LOADED,this.onFragLoaded,this),e.off(B.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(B.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(B.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(B.BUFFER_APPENDED,this.onBufferAppended,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}},{key:"initCea608Parsers",value:function(){var e=new Rc(this,"textTrack1"),t=new Rc(this,"textTrack2"),r=new Rc(this,"textTrack3"),n=new Rc(this,"textTrack4");this.cea608Parser1=new Ac(1,e,t),this.cea608Parser2=new Ac(3,r,n)}},{key:"addCues",value:function(e,t,r,n,i){for(var a=!1,s=i.length;s--;){var o=i[s],l=wc(o[0],o[1],t,r);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],r),a=!0,l/(r-t)>.5))return}if(a||i.push([t,r]),this.config.renderTextTracksNatively){var u=this.cueCache[e];if(u){var c=this.Cues.newCue(null,t,r,n);c.length&&u.push.apply(u,c)}else{var d=this.captionsTracks[e].track;this.Cues.newCue(d,t,r,n)}}else{var h,f=this.Cues.newCue(null,t,r,n),v=null==(h=this.captionsProperties[e])?void 0:h.media;this.hls.trigger(B.CUES_PARSED,{type:"captions",cues:f,track:e,closedCaptions:v})}}},{key:"onInitPtsFound",value:function(e,t){var r=this,n=t.id,i=t.timestampOffsets,a=this.unparsedVttFrags;n===W.MAIN&&(this.initPTS=i),a.length&&(this.unparsedVttFrags=[],a.forEach(function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(B.FRAG_LOADED,e):r.hls.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}},{key:"createCaptionsTrack",value:function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}},{key:"createNativeTrack",value:function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,n=this.cueCache,i=this.media,a=t[e],s=a.label,o=a.languageCode;i&&(n[e]=[],r[e]=vu(i,"captions",s,o,"hidden"))}}},{key:"createNonNativeTrack",value:function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(B.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia;if(this.media=null,!r){if(this.config.renderTextTracksNatively){var n=this.captionsTracks,i=this.cueCache;for(var a in n)n[a].remove(),delete i[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}},{key:"onManifestLoading",value:function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=t.subtitleTracks||[];if(r.length&&!this.config.renderTextTracksNatively&&!Ds(this.tracks,r)){var n=r.map(function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}});this.hls.trigger(B.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}this.tracks=r}},{key:"onManifestLoaded",value:function(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var n="textTrack".concat(t[1]),i=r.captionsProperties[n];i&&(i.label=e.name,e.lang&&(i.languageCode=e.lang),i.media=e)}})}},{key:"closedCaptionsForLevel",value:function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}},{key:"onFragLoading",value:function(e,t){if(this.enabled&&t.frag.type===W.MAIN){var r,n,i=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,c=null!=(r=null==(n=t.part)?void 0:n.index)?r:-1;i&&a&&(u!==s+1||u===s&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(i.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}},{key:"onFragLoaded",value:function(e,t){var r,n=t.frag,i=t.payload;if(n.level<this.tracks.length&&n.type===W.SUBTITLE)if(i.byteLength||null!=(r=n.initSegment)&&null!=(r=r.data)&&r.byteLength){var a=n.decryptdata,s="stats"in t;if(null==a||!a.encrypted||s){var o=this.tracks[n.level],l=this.vttCCs;l[n.cc]||(l[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),(null==o?void 0:o.textCodec)===nu?this._parseIMSC1(t):this._parseVTTs(t)}}else{var u="part"in t?t.part:null;this.hls.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:u,error:new Error("Empty subtitle payload")})}}},{key:"_parseIMSC1",value:function(e){var t=this,r=e.frag,n=e.payload,i="part"in e?e.part:null,a=this.hls;ou(n,this.initPTS[r.cc],function(e){t._appendCues(e,r.level),a.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r,part:i})},function(e){a.logger.log("Cannot parse IMSC1 (sn: ".concat(r.sn," @").concat(r.start,"): ").concat(e)),a.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,part:i,error:e})})}},{key:"_parseVTTs",value:function(e){var t,r=this,n=e.frag,i=e.payload,a="part"in e?e.part:null,s=this.initPTS,o=this.unparsedVttFrags,l=s.length-1;if(s[n.cc]||-1!==l){var u=this.hls,c=null==(t=n.initSegment)?void 0:t.data;ru(c?At(c,new Uint8Array(i)).buffer:i,this.initPTS[n.cc],this.vttCCs,n.cc,(a&&!c?a:n).start,function(e){r._appendCues(e,n.level),u.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n,part:a})},function(t){var i=t.message.startsWith("Missing initPTS");u.logger.log("".concat(i?"Deferred parsing of":"Cannot parse"," VTT cue (sn: ").concat(n.sn," @").concat(n.start,"): ").concat(t)),i?o.push(e):(r.config.enableIMSC1&&r._fallbackToIMSC1(e),u.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:a,error:t}))})}else o.push(e)}},{key:"_fallbackToIMSC1",value:function(e){var t=this,r=e.frag,n=e.payload,i=this.tracks[r.level];i.textCodec||ou(n,this.initPTS[r.cc],function(){i.textCodec=nu,t._parseIMSC1(e)},function(){i.textCodec="wvtt"})}},{key:"_appendCues",value:function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var n,i=null==(n=this.tracks[t].trackNode)?void 0:n.track;if(!i||"disabled"===i.mode)return;e.forEach(function(e){return pu(i,e)})}else{var a=this.tracks[t];if(!a)return;var s=a.default?"default":"subtitles"+t;r.trigger(B.CUES_PARSED,{type:"subtitles",cues:e,track:s,subtitleTrack:a})}}},{key:"onFragDecrypted",value:function(e,t){t.frag.type===W.SUBTITLE&&this.onFragLoaded(B.FRAG_LOADED,t)}},{key:"onSubtitleTracksCleared",value:function(){this.tracks=[],this.captionsTracks={}}},{key:"onFragParsingUserdata",value:function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var r=t.frag,n=t.samples;if(r.type!==W.MAIN||"NONE"!==this.closedCaptionsForLevel(r))for(var i=0;i<n.length;i++){var a=n[i].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(n[i].pts,s[0]),this.cea608Parser2.addData(n[i].pts,s[1])}}}}},{key:"onBufferAppended",value:function(e,t){if(this.config.renderTextTracksNatively){var r,n=t.type,i=t.timeRanges;if("video"===n&&null!=(r=i[n])&&r.length){var a=this.captionsTracks,s=this.cueCache;Object.keys(s).forEach(function(e){var t,r=null==(t=a[e])?void 0:t.track;if(r)for(var n=s[e],i=0;i<n.length;i++)pu(r,n[i]);delete s[e]})}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,n=t.endOffset,i=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<n)){if(!a||"video"===a){var o=this.captionsTracks,l=this.cueCache;Object.keys(o).forEach(function(e){return yu(o[e].track,r,n)}),Object.keys(l).forEach(function(e){for(var t=l[e],i=t.length;i--;){var a=t[i];a.startTime>=r&&a.endTime<=n&&t.splice(i,1)}})}this.config.renderTextTracksNatively&&0===r&&void 0!==i&&this.tracks.forEach(function(e){var t,n=null==(t=e.trackNode)?void 0:t.track;n&&yu(n,r,i)})}}},{key:"extractCea608Data",value:function(e){for(var t=[[],[]],r=31&e[0],n=2,i=0;i<r;i++){var a=e[n++],s=127&e[n++],o=127&e[n++];if(0!==s||0!==o)if(!!(4&a)){var l=3&a;0!==l&&1!==l||(t[l].push(s),t[l].push(o))}}return t}}])}();function wc(e,t,r,n){return Math.min(t,n)-Math.max(e,r)}var _c=/\s/,Pc={newCue:function(e,t,r,n){for(var i,a,s,o,l,u=[],c=self.VTTCue||self.TextTrackCue,d=0;d<n.rows.length;d++)if(s=!0,o=0,l="",!(i=n.rows[d]).isEmpty()){for(var h,f=0;f<i.chars.length;f++)_c.test(i.chars[f].uchar)&&s?o++:(l+=i.chars[f].uchar,s=!1);i.cueStartTime=t,t===r&&(r+=1e-4),o>=16?o--:o++;var v=Ql(l.trim()),g=tu(t,r,v);null!=e&&null!=(h=e.cues)&&h.getCueById(g)||((a=new c(t,r,v)).id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return e&&u.length&&(u.sort(function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line}),u.forEach(function(t){return pu(e,t)})),u}},Dc=function(){return h(function e(){c(this,e),this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new V},[{key:"destroy",value:function(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}},{key:"load",value:function(e,t,r){var n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}},{key:"loadtimeout",value:function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(ve(e,this.stats.retry,!0))this.retry(e);else{var t;Le.warn("timeout while loading ".concat(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}}},{key:"retry",value:function(e){var t=this,r=this.context,n=this.stats;this.retryDelay=he(e,n.retry),n.retry++,Le.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==r?void 0:r.url,", retrying ").concat(n.retry,"/").concat(e.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(function(){return t.loadInternal()},this.retryDelay)}}])}();var Cc=/(\d+)-(\d+)\/(\d+)/,Oc=function(e){function t(e){var r;return c(this,t),(r=u(this,t)).fetchSetup=void 0,r.request=null,r.response=null,r.controller=null,r.fetchSetup=e.fetchSetup||xc,r}return y(t,e),h(t,[{key:"destroy",value:function(){this.request=null,R(t,"destroy",this)([]),this.response=null,this.controller=null,this.fetchSetup=null}},{key:"abortInternal",value:function(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}},{key:"getNetworkDetails",value:function(){return this.response}},{key:"resetInternalLoader",value:function(){this.response=null}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context,n=this.stats;if(t&&r){n.loading.first=0,n.loaded=0,n.aborted=!1,this.controller=new self.AbortController;var i=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(ie({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(r,this.controller.signal),a="arraybuffer"===r.responseType,s=a?"byteLength":"length",o=t.loadPolicy,l=o.maxTimeToFirstByteMs,u=o.maxLoadTimeMs;this.request=this.fetchSetup(r,i),self.clearTimeout(this.requestTimeout),t.timeout=l&&x(l)?l:u,this.requestTimeout=self.setTimeout(function(){e.loadtimeout()},t.timeout),(As(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(i){var s;e.response=i;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(e.requestTimeout),t.timeout=u,e.requestTimeout=self.setTimeout(function(){e.loadtimeout()},u-(o-n.loading.start)),!i.ok){var l=i.status,c=i.statusText;throw new Mc(c||"fetch, bad network response",l,i)}n.loading.first=o,n.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=Cc.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(x(r))return r}var n=e.get("Content-Length");if(n)return parseInt(n)}(i.headers)||n.total;var d=null==(s=e.callbacks)?void 0:s.onProgress;return d&&x(t.highWaterMark)?e.loadProgressively(i,n,r,t.highWaterMark,d):a?i.arrayBuffer():"json"===r.responseType?i.json():i.text()}).then(function(i){var a,o,l=e.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(e.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var u=i[s];u&&(n.loaded=n.total=u);var c={url:l.url,data:i,code:l.status},d=null==(a=e.callbacks)?void 0:a.onProgress;d&&!x(t.highWaterMark)&&d(n,r,i,l),null==(o=e.callbacks)||o.onSuccess(c,n,r,l)}).catch(function(i){if(self.clearTimeout(e.requestTimeout),!n.aborted){var a,s=i&&i.code||0,o=i?i.message:null,l=t.loadPolicy.errorRetry;if(ve(l,n.retry,!1,{url:r.url,data:void 0,code:s}))e.retry(l);else Le.error("".concat(s," while loading ").concat(r.url)),null==(a=e.callbacks)||a.onError({code:s,text:o},r,i?i.details:null,n)}})}}},{key:"getCacheAge",value:function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.response?this.response.headers.get(e):null}},{key:"loadProgressively",value:function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,a=new ea,s=e.body.getReader(),o=function(){return s.read().then(function(s){if(s.done)return a.dataLength&&i(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<n||a.dataLength?(a.push(l),a.dataLength>=n&&i(t,r,a.flush().buffer,e)):i(t,r,l.buffer,e),o()}).catch(function(){return Promise.reject()})};return o()}}])}(Dc);function xc(e,t){return new self.Request(e.url,t)}var Mc=function(e){function t(e,r,n){var i;return c(this,t),(i=u(this,t,[e])).code=void 0,i.details=void 0,i.code=r,i.details=n,i}return y(t,e),h(t)}(O(Error)),Fc=/^age:\s*[\d.]+\s*$/im,Nc=function(e){function t(e){var r;return c(this,t),(r=u(this,t)).xhrSetup=void 0,r.loader=null,r.xhrSetup=e.xhrSetup||null,r}return y(t,e),h(t,[{key:"destroy",value:function(){R(t,"destroy",this)([]),this.loader=null,this.xhrSetup=null}},{key:"abortInternal",value:function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}},{key:"getNetworkDetails",value:function(){return this.loader}},{key:"resetInternalLoader",value:function(){this.loader=null}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context;if(t&&r){var n=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then(function(){if(e.loader===n&&!e.stats.aborted)return a.call(e,n,r.url,r)}).catch(function(t){if(e.loader===n&&!e.stats.aborted)return n.open("GET",r.url,!0),a.call(e,n,r.url,r)}).then(function(){e.loader!==n||e.stats.aborted||e.openAndSendXhr(n,r,t)}).catch(function(t){var a;null==(a=e.callbacks)||a.onError({code:n.status,text:t.message},r,n,i)}):this.openAndSendXhr(n,r,t)}}},{key:"openAndSendXhr",value:function(e,t,r){e.readyState||e.open("GET",t.url,!0);var n=t.headers,i=r.loadPolicy,a=i.maxTimeToFirstByteMs,s=i.maxLoadTimeMs;if(n)for(var o in n)e.setRequestHeader(o,n[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes=".concat(t.rangeStart,"-").concat(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=a&&x(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}},{key:"readystatechange",value:function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var n=t.readyState,i=this.config;if(!r.aborted&&n>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===n)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var c="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=c,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(r,e,o,t);var h={url:t.responseURL,data:o,code:a};return e.rangeEnd&&c!==e.rangeEnd-e.rangeStart&&Le.warn("Payload length ".concat(c," does not match requested Range: bytes=").concat(e.rangeStart,"-").concat(e.rangeEnd-1)),void(null==(u=this.callbacks)||u.onSuccess(h,r,e,t))}}var f,v=i.loadPolicy.errorRetry;if(ve(v,r.retry,!1,{url:e.url,data:void 0,code:a}))this.retry(v);else Le.error("".concat(a," while loading ").concat(e.url)),null==(f=this.callbacks)||f.onError({code:a,text:t.statusText},e,t,r)}}}},{key:"loadprogress",value:function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}},{key:"getCacheAge",value:function(){var e=null;if(this.loader&&Fc.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.loader&&new RegExp("^".concat(e,":\\s*[\\d.]+\\s*$"),"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}])}(Dc),Uc=se(se({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Nc,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:$n,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:Mu,abrController:_r,bufferController:Us,capLevelController:qs,errorController:Wr,fpsController:jl,id3TrackController:Iu,gapController:Eu,latencyController:ic},{cueHandler:Pc,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:ac,subtitleTrackController:mu,timelineController:Ic,audioStreamController:_s,audioTrackController:Os,emeController:Ul,cmcdController:Cl,contentSteeringController:Ol,iframeController:Gu,interstitialsController:nc});function Bc(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==t.liveMaxUnchangedPlaylistRefresh){var n=t.liveMaxUnchangedPlaylistRefresh,i=function(e,t,r){return Math.max(t,Math.min(e,r))}(n,2,1/0);i!==n&&r.warn('hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from '.concat(n," to ").concat(i,".")),t.liveMaxUnchangedPlaylistRefresh=i}var a=Gc(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(function(e){var n="".concat("level"===e?"playlist":e,"LoadPolicy"),i=void 0===t[n],o=[];s.forEach(function(r){var s="".concat(e,"Loading").concat(r),l=t[s];if(void 0!==l&&i){o.push(s);var u=a[n].default;switch(t[n]={default:u},r){case"TimeOut":u.maxLoadTimeMs=l,u.maxTimeToFirstByteMs=l;break;case"MaxRetry":u.errorRetry.maxNumRetry=l,u.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":u.errorRetry.retryDelayMs=l,u.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=l,u.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&r.warn('hls.js config: "'.concat(o.join('", "'),'" setting(s) are deprecated, use "').concat(n,'": ').concat(mr(t[n])))}),se(se({},a),t)}function Gc(e){return e&&"object"===_(e)?Array.isArray(e)?e.map(Gc):Object.keys(e).reduce(function(t,r){return t[r]=Gc(e[r]),t},{}):e}function jc(e,t){var r=e.loader;r!==Oc&&r!==Nc?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=Oc,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Kc=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,[e,"level-controller"]))._levels=[],n._firstLevel=-1,n._maxAutoLevel=-1,n._startLevel=void 0,n.currentLevel=null,n.currentLevelIndex=-1,n.manualLevelIndex=-1,n.steering=void 0,n.lastABRSwitchTime=-1,n._iframeVariants=[],n.onParsedComplete=void 0,n.steering=r,n._registerListeners(),n}return y(t,e),h(t,[{key:"_registerListeners",value:function(){var e=this.hls;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.ERROR,this.onError,this)}},{key:"_unregisterListeners",value:function(){var e=this.hls;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.ERROR,this.onError,this)}},{key:"destroy",value:function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),R(t,"destroy",this)([])}},{key:"stopLoad",value:function(){this._levels.forEach(function(e){e.loadError=0,e.fragmentError=0}),R(t,"stopLoad",this)([])}},{key:"resetLevels",value:function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}},{key:"onManifestLoading",value:function(e,t){this.resetLevels()}},{key:"onManifestLoaded",value:function(e,t){var r=this,n=this.hls.config.preferManagedMediaSource,i=[],a={},s={},o=!1,l=!1,u=!1,c=!1;t.levels.forEach(function(e){var t=e.attrs,d=qc(e,n),h=e.audioCodec,f=e.videoCodec,v=e.imageCodec,g=e.width,p=e.height;if(d){o||(o=!(!g||!p)),l||(l=!!f),u||(u=!!h),c||(c=!!v);var y=t.CODECS,m=t["FRAME-RATE"],E=t["HDCP-LEVEL"],k=t["PATHWAY-ID"],S=t.RESOLUTION,T=t["VIDEO-RANGE"],b="".concat(k||".","-"),A="".concat(b).concat(e.bitrate,"-").concat(S,"-").concat(m,"-").concat(y,"-").concat(T,"-").concat(E);if(a[A])if(a[A].uri===e.url||e.attrs["PATHWAY-ID"])e.iframes||(a[A].addGroupId("audio",t.AUDIO),a[A].addGroupId("text",t.SUBTITLES));else{var L=s[A]+=1;e.attrs["PATHWAY-ID"]=new Array(L+1).join(".");var R=r.createLevel(e);a[A]=R,i.push(R)}else{var I=r.createLevel(e);a[A]=I,s[A]=1,i.push(I)}}else r.log('Some or all CODECS not supported "'.concat(t.CODECS,'"'))}),this.filterAndSortMediaOptions(i,t,o,l,u,c)}},{key:"createLevel",value:function(e){var t=new gr(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!Vc(r.videoCodec,this.hls.config.preferManagedMediaSource)){var n=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(r.videoCodec,'"'));this.log(n.message),t.supportedResult=nr(n,[])}return t}},{key:"filterAndSortMediaOptions",value:function(e,t,r,n,i,a){var s,o=this,l=[],u=[],c=e,d=(null==(s=t.stats)?void 0:s.parsing)||{},h=this.hls.config.preferManagedMediaSource;if((r||n)&&i&&(c=c.filter(function(e){var t,r=e.videoCodec,n=e.videoRange,i=e.width,a=e.height;return(!!r||!(!i||!a))&&(!!(t=n)&&ur.indexOf(t)>-1)})),n&&a&&(c=c.filter(function(e){return!e.imageCodec})),0===c.length)return Promise.resolve().then(function(){if(o.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: ".concat(mr(t.levels.map(function(e){return e.attrs.CODECS}).filter(function(e,t,r){return r.indexOf(e)===t}))),o.warn(r),e+=" (".concat(r,")"));var n=new Error(e);o.hls.trigger(B.ERROR,{type:N.MEDIA_ERROR,details:U.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:n,reason:r})}}),void(d.end=performance.now());t.audioTracks&&Wc(l=t.audioTracks.filter(function(e){return!e.audioCodec||Hc(e.audioCodec,h)})),t.subtitles&&Wc(u=t.subtitles);var f=c.slice(0);c.sort(function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&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 ur.indexOf(e.videoRange)-ur.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var n=qt(e.videoCodec),i=qt(t.videoCodec);if(n!==i)return i-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=Wt(e.codecSet),s=Wt(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});var v=f[0];if(this.steering&&(c=this.steering.filterParsedLevels(c)).length!==f.length)for(var g=0;g<f.length;g++)if(f[g].pathwayId===c[0].pathwayId){v=f[g];break}this._levels=c;for(var p=0;p<c.length;p++)if(c[p]===v){var y;this._firstLevel=p;var m=v.bitrate,E=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(c.length," level(s) found, first bitrate: ").concat(m)),void 0===(null==(y=this.hls.userConfig)?void 0:y.abrEwmaDefaultEstimate)){var k=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);k>E&&E===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=k)}break}var S=t.iframeVariants.filter(function(e){return qc(e,h)});this._iframeVariants=S;var T=i&&!n,b=this.hls.config,A=!(!b.audioStreamController||!b.audioTrackController),L={levels:c,audioTracks:l,subtitleTracks:u,iframeVariants:S,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:n,altAudio:A&&!T&&l.some(function(e){return!!e.url})};d.end=performance.now(),this.hls.trigger(B.MANIFEST_PARSED,L)}},{key:"iframeVariants",get:function(){return 0===this._iframeVariants.length?null:this._iframeVariants}},{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),n=e<0;if(this.hls.trigger(B.ERROR,{type:N.OTHER_ERROR,details:U.LEVEL_SWITCH_ERROR,level:e,fatal:n,error:r,reason:r.message}),n)return;e=Math.min(e,t.length-1)}var i=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,i!==e||!a||s!==l){this.log("Switching to level ".concat(e," (").concat(o.height?o.height+"p ":"").concat(o.videoRange?o.videoRange+" ":"").concat(o.codecSet?o.codecSet+" ":"","@").concat(o.bitrate,")").concat(l?" with Pathway "+l:""," from level ").concat(i).concat(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(B.LEVEL_SWITCHING,u);var c=o.details;if(!c||c.live){var d=this.switchParams(o.uri,null==a?void 0:a.details,c);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),r=e.filter(function(e){return-1!==t.indexOf(e)});if(e.length<1)return void this.warn("pathwayPriority ".concat(e," should contain at least one pathway from list: ").concat(t));this.steering.pathwayPriority=r}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===q.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}},{key:"onFragBuffered",value:function(e,t){var r=t.frag;if(r.type===W.MAIN){var n=r.elementaryStreams;if(!Object.keys(n).some(function(e){return!!n[e]}))return;var i=this._levels[r.level];null!=i&&i.loadError&&(this.log("Resetting level error count of ".concat(i.loadError," on frag buffered")),i.loadError=0)}}},{key:"onLevelLoaded",value:function(e,t){var r,n,i=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index ".concat(i)),void(null!=(n=t.deliveryDirectives)&&n.skip&&(a.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);var o=s.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(i,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)}},{key:"loadPlaylist",value:function(e){R(t,"loadPlaylist",this)([]),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}},{key:"loadingPlaylist",value:function(e,r){R(t,"loadingPlaylist",this)([e,r]);var n=this.getUrlWithDirectives(e.uri,r),i=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],s=e.details,o=null==s?void 0:s.age;this.log("Loading level index ".concat(i).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(a?" Pathway "+a:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(n)),this.hls.trigger(B.LEVEL_LOADING,{url:n,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){var t=this.currentLevelIndex;if(-1===this.manualLevelIndex&&e!==t&&-1!==e){var r=this.hls.config.abrSwitchInterval;if(r>0){var n=performance.now(),i=n-this.lastABRSwitchTime,a=1e3*r;if(this.lastABRSwitchTime>-1&&i<a)return void this.warn("Preventing ABR level switch: ".concat(t," -> ").concat(e," (").concat(Math.round(i),"ms < ").concat(a,"ms / ").concat(r,"s)"));this.lastABRSwitchTime=n,this.log("Allowing ABR level switch: ".concat(t," -> ").concat(e," (").concat(Math.round(i),"ms >= ").concat(a,"ms / ").concat(r,"s)"))}}this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}},{key:"removeLevel",value:function(e){var t,r=this;if(1!==this._levels.length){var n=this._levels.filter(function(t,n){return n!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(function(e){return e.level=-1})),!1)});_i(n),this._levels=n,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var i=n.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(B.LEVELS_UPDATED,{levels:n})}}},{key:"onLevelsUpdated",value:function(e,t){var r=t.levels;this._levels=r}},{key:"checkMaxAutoUpdated",value:function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,n=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(B.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}])}(Ps);function Hc(e,t){return Kt(e,"audio",t)}function Vc(e,t){return Kt(e,"video",t)}function qc(e,t){var r=e.audioCodec,n=e.videoCodec;r&&(e.audioCodec=r=Xt(r,t)||void 0),n&&(n=e.videoCodec=function(e){for(var t=e.split(","),r=0;r<t.length;r++){var n=t[r].split(".");n.length>2&&"avc1"===n[0]&&(t[r]="avc1.".concat(parseInt(n[1]).toString(16)).concat(("000"+parseInt(n[2]).toString(16)).slice(-4)))}return t.join(",")}(n));var i=e.unknownCodecs;return!((null==i?void 0:i.length)||0||r&&!Hc(r,t)||n&&!Vc(n,t))}function Wc(e){var t={};e.forEach(function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}var Yc=function(e){function t(e,r){var n;return c(this,t),(n=u(this,t,["key-loader",r])).config=void 0,n.keyLoaderInfo={},n.emeController=null,n.config=e,n}return y(t,e),h(t,[{key:"abort",value:function(e){for(var t in this.keyLoaderInfo){var r=this.keyLoaderInfo[t].loader;if(r){var n;if(e&&e!==(null==(n=r.context)?void 0:n.frag.type))return;r.abort()}}}},{key:"destroy",value:function(){for(var e in this.keyLoaderInfo){var t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}},{key:"loadClear",value:function(e,t,r){return this.emeController?this.emeController.loadClear(e,t,r):null}},{key:"load",value:function(e,t){var r=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(function(n){return r.loadInternal(e,t,n)}):this.loadInternal(e,t)}},{key:"loadInternal",value:function(e,t,r){var n=this;r&&e.setKeyFormat(r);var i=e.decryptdata;if(!i){var a=new Error(r?"Expected frag.decryptdata to be defined after setting format ".concat(r):"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"));return Promise.reject(zc(e,U.KEY_LOAD_ERROR,a))}var s=e;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(s):t?t.then(function(){return n.loadKeyEME(s)}):this.loadKeyEME(s);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(s);default:return Promise.reject(zc(e,U.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'.concat(i.method,'"'))))}}},{key:"loadKeyEME",value:function(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&null!=(t=e.initSegment)&&t.data){var r=function(e){var t=[];return kt(e,function(e){return t.push(e.subarray(8,24))}),t}(e.initSegment.data);if(r.length){var n=r[0],i=e.decryptdata.uri;if(n.some(function(e){return 0!==e}))this.log("Using keyId found in init segment ".concat(ze(n)," keyUri: ").concat(i)),ei.setKeyIdForUri(i,n);else{var a=ei.addKeyIdForUri(i);this.log("Patching empty keyId with ".concat(ze(a)," keyUri: ").concat(i)),n=a}e.decryptdata.keyId=n}}return this.emeController.loadKey(e).then(function(){return{frag:e,keyInfo:{decryptdata:e.decryptdata}}})}return Promise.reject(zc(e,U.KEY_LOAD_ERROR,new Error("emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"))))}},{key:"loadKeyHTTP",value:function(e){var t=this,r=e.decryptdata,n=r.uri;if(!n)return Promise.reject(zc(e,U.KEY_LOAD_ERROR,new Error('Invalid key URI: "'.concat(n,'"'))));var i=this.keyLoaderInfo[n];if(i){if(i.decryptdata.key)return r.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(function(t){return r.key=i.decryptdata.key,se(se({},t),{},{frag:e})})}this.log("Loading".concat(r.keyId?" keyId: "+ze(r.keyId):""," URI: ").concat(r.uri," from ").concat(e.type," ").concat(e.level));var a=this.config,s=new(0,a.loader)(a);e.keyLoader=s;var o=this.keyLoaderInfo[n]={decryptdata:r,keyLoadPromise:null,loader:s};return o.keyLoadPromise=new Promise(function(r,i){var l={type:q.KEY,keyInfo:o,frag:e,responseType:"arraybuffer",url:n},u=a.keyLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(e,n,a,s){var o=a.frag,l=a.keyInfo,u=a.url;if(!o.decryptdata||l!==t.keyLoaderInfo[u])return i(zc(o,U.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=l.loader=l.keyLoadPromise=null,r({frag:o,keyInfo:l})},onError:function(r,a,s,o){t.resetLoader(a),i(zc(e,U.KEY_LOAD_ERROR,new Error("HTTP Error ".concat(r.code," loading key ").concat(r.text)),s,se({url:n,data:void 0},r)))},onTimeout:function(r,n,a){t.resetLoader(n),i(zc(e,U.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),a))},onAbort:function(r,n,a){t.resetLoader(n),i(zc(e,U.INTERNAL_ABORTED,new Error("key loading aborted"),a))}};s.load(l,c,d)})}},{key:"resetLoader",value:function(e){var t=e.frag,r=e.keyInfo,n=e.url,i=r.loader;t.keyLoader===i&&(t.keyLoader=r.loader=r.keyLoadPromise=null),delete this.keyLoaderInfo[n],i&&i.destroy()}}])}(Ee);function zc(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:U.KEY_LOAD_ERROR,r=arguments.length>2?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;return new pn({type:N.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:r,networkDetails:n||null})}function Xc(e){switch(e.type){case q.AUDIO_TRACK:return W.AUDIO;case q.SUBTITLE_TRACK:return W.SUBTITLE;default:return W.MAIN}}function Qc(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var $c=function(){return h(function e(t){c(this,e),this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()},[{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){this.destroyInternalLoaders()}},{key:"registerListeners",value:function(){var e=this.hls;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(B.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_LOADING,this.onLevelLoading,this),e.off(B.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(B.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"createInternalLoader",value:function(e){var t=this.hls.config,r=t.pLoader,n=t.loader,i=new(r||n)(t);return this.loaders[e.type]=i,i}},{key:"getInternalLoader",value:function(e){return this.loaders[e.type]}},{key:"resetInternalLoader",value:function(e){this.loaders[e]&&delete this.loaders[e]}},{key:"destroyInternalLoaders",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}},{key:"destroy",value:function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}},{key:"onManifestLoading",value:function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:q.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}},{key:"onLevelLoading",value:function(e,t){var r=t.id,n=t.level,i=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:n,pathwayId:i,responseType:"text",type:q.LEVEL,url:a,deliveryDirectives:s,levelOrTrack:o})}},{key:"onAudioTrackLoading",value:function(e,t){var r=t.id,n=t.groupId,i=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:n,level:null,responseType:"text",type:q.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:s})}},{key:"onSubtitleTrackLoading",value:function(e,t){var r=t.id,n=t.groupId,i=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:n,level:null,responseType:"text",type:q.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:s})}},{key:"onLevelsUpdated",value:function(e,t){var r=this.loaders[q.LEVEL];if(r){var n=r.context;n&&!t.levels.some(function(e){return e===n.levelOrTrack})&&(r.abort(),delete this.loaders[q.LEVEL])}}},{key:"load",value:function(e){var t,r,n,i=this,a=this.hls.config,s=this.getInternalLoader(e);if(s){var o=this.hls.logger,l=s.context;if((null==l?void 0:l.levelOrTrack)===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives))return void(l.url===e.url?o.log("[playlist-loader]: ignore ".concat(e.url," ongoing request")):o.log("[playlist-loader]: ignore ".concat(e.url," in favor of ").concat(l.url)));o.log("[playlist-loader]: aborting previous loader for type: ".concat(e.type)),s.abort()}if((r=e.type===q.MANIFEST?a.manifestLoadPolicy.default:ie({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),x(null==(t=e.deliveryDirectives)?void 0:t.part))&&(e.type===q.LEVEL&&null!==e.level?n=this.hls.levels[e.level].details:e.type===q.AUDIO_TRACK&&null!==e.id?n=this.hls.audioTracks[e.id].details:e.type===q.SUBTITLE_TRACK&&null!==e.id&&(n=this.hls.subtitleTracks[e.id].details),n)){var u=n.partTarget,c=n.targetduration;if(u&&c){var d=1e3*Math.max(3*u,.8*c);r=ie({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}var h=r.errorRetry||r.timeoutRetry||{},f={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},v={onSuccess:function(e,t,r,n){var a=i.getInternalLoader(r);i.resetInternalLoader(r.type);var s=e.data;t.parsing.start=performance.now(),oi.isMediaPlaylist(s)||r.type!==q.MANIFEST?i.handleTrackOrLevelPlaylist(e,t,r,n||null,a):i.handleMasterPlaylist(e,t,r,n)},onError:function(e,t,r,n){i.handleNetworkError(t,r,!1,e,n)},onTimeout:function(e,t,r){i.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,f,v)}},{key:"checkAutostartLoad",value:function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,n=t.startPosition,i=e.forceStartLoad;(r||i)&&(this.hls.logger.log("".concat(r?"auto":"force"," startLoad with configured startPosition ").concat(n)),this.hls.startLoad(n))}}},{key:"handleMasterPlaylist",value:function(e,t,r,n){var i=this,a=this.hls,s=e.data,o=Qc(e,r),l=oi.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,l.playlistParsingError,n,t);var u=l.contentSteering,c=l.levels,d=l.iframeVariants,h=l.sessionData,f=l.sessionKeys,v=l.startTimeOffset,g=l.variableList;this.variableList=g,c.forEach(function(e){var t=e.unknownCodecs;if(t)for(var r=i.hls.config.preferManagedMediaSource,n=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];Kt(o,"audio",r)?(e.audioCodec=n=n?"".concat(n,",").concat(o):o,Gt.audio[n.substring(0,4)]=2,t.splice(s,1)):Kt(o,"video",r)&&(e.videoCodec=a=a?"".concat(a,",").concat(o):o,Gt.video[a.substring(0,4)]=2,t.splice(s,1))}});var p=oi.parseMasterPlaylistMedia(s,o,l),y=p.AUDIO,m=void 0===y?[]:y,E=p.SUBTITLES,k=p["CLOSED-CAPTIONS"];m.length&&(m.some(function(e){return!e.url})||!c[0].audioCodec||c[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new wn({}),bitrate:0,url:""})));a.trigger(B.MANIFEST_LOADED,{levels:c,audioTracks:m,subtitles:E,iframeVariants:d,captions:k,contentSteering:u,url:o,stats:t,networkDetails:n,sessionData:h,sessionKeys:f,startTimeOffset:v,variableList:g})}},{key:"handleTrackOrLevelPlaylist",value:function(e,t,r,n,i){var a=this.hls,s=r.id,o=r.level,l=r.type,u=Qc(e,r),c=x(o)?o:x(s)?s:0,d=Xc(r),h=oi.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===q.MANIFEST){var f={attrs:new wn({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+Li(h,0),a.trigger(B.MANIFEST_LOADED,{levels:[f],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=h,this.handlePlaylistLoaded(h,e,t,r,n,i)}},{key:"handleManifestParsingError",value:function(e,t,r,n,i){this.hls.trigger(B.ERROR,{type:N.NETWORK_ERROR,details:U.MANIFEST_PARSING_ERROR,fatal:t.type===q.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:i})}},{key:"handleNetworkError",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0,a="A network ".concat(r?"timeout":"error"+(n?" (status "+n.code+")":"")," occurred while loading ").concat(e.type);e.type===q.LEVEL?a+=": ".concat(e.level," id: ").concat(e.id):e.type!==q.AUDIO_TRACK&&e.type!==q.SUBTITLE_TRACK||(a+=" id: ".concat(e.id,' group-id: "').concat(e.groupId,'"'));var s=new Error(a);this.hls.logger.warn("[playlist-loader]: ".concat(a));var o=U.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case q.MANIFEST:o=r?U.MANIFEST_LOAD_TIMEOUT:U.MANIFEST_LOAD_ERROR,l=!0;break;case q.LEVEL:o=r?U.LEVEL_LOAD_TIMEOUT:U.LEVEL_LOAD_ERROR,l=!1;break;case q.AUDIO_TRACK:o=r?U.AUDIO_TRACK_LOAD_TIMEOUT:U.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case q.SUBTITLE_TRACK:o=r?U.SUBTITLE_TRACK_LOAD_TIMEOUT:U.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var c={type:N.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:s,networkDetails:t,stats:i};if(n){var d=e.url;t&&"url"in t&&(d=t.url),c.response=se({url:d,data:void 0},n)}this.hls.trigger(B.ERROR,c)}},{key:"handlePlaylistLoaded",value:function(e,t,r,n,i,a){var s=this.hls,o=n.type,l=n.level,u=n.levelOrTrack,c=n.id,d=n.groupId,h=n.deliveryDirectives,f=Qc(t,n),v=Xc(n),g="number"==typeof n.level&&v===W.MAIN?l:void 0;u&&"iframes"in u&&u.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);var p=e.playlistParsingError;if(p){if(this.hls.logger.warn("".concat(p," ").concat(e.url)),!s.config.ignorePlaylistParsingErrors)return void s.trigger(B.ERROR,{type:N.NETWORK_ERROR,details:U.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:n,level:g,parent:v,networkDetails:i,stats:r});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case q.MANIFEST:case q.LEVEL:if(g)if(u){if(u!==s.levels[g]){var y=s.levels.indexOf(u);y>-1&&(g=y)}}else g=0;s.trigger(B.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:g||0,id:c||0,stats:r,networkDetails:i,deliveryDirectives:h,withoutMultiVariant:o===q.MANIFEST,context:n});break;case q.AUDIO_TRACK:s.trigger(B.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:i,deliveryDirectives:h,context:n});break;case q.SUBTITLE_TRACK:s.trigger(B.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:i,deliveryDirectives:h,context:n})}else{var m=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(B.ERROR,{type:N.NETWORK_ERROR,details:U.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:n,level:g,parent:v,networkDetails:i,stats:r})}}}])}(),Jc=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};c(this,e),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ia,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var r=this.logger=function(e,t,r){var n=Te();if("object"===("undefined"==typeof console?"undefined":_(console))&&!0===e||"object"===_(e)){var i=["debug","log","info","warn","error"];i.forEach(function(t){n[t]=be(t,e,r)});try{n.log('Debug logs enabled for "'.concat(t,'" in hls.js version ',"1.7.3"))}catch(a){return Te()}i.forEach(function(t){Ae[t]=be(t,e)})}else ie(Ae,n);return n}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),n=this.config=Bc(e.DefaultConfig,t,r);this.userConfig=t,n.progressive&&jc(n,r);var i=n.streamController,a=n.abrController,s=n.bufferController,o=n.capLevelController,l=n.errorController,u=n.fpsController,d=n.id3TrackController,h=n.iframeController,f=n.gapController,v=new l(this),g=this.abrController=new a(this),p=new en(this),y=n.interstitialsController,m=y?this.interstitialsController=new y(this,e):null,E=s?this.bufferController=new s(this,p):null,k=o?this.capLevelController=new o(this):null,S=u?new u(this):null,T=n.cmcdController,b=T?this.cmcdController=new T(this):null,A=new $c(this),L=n.contentSteeringController,R=L?new L(this):null,I=this.levelController=new Kc(this,R),w=d?new d(this):void 0,P=new Yc(this.config,this.logger),D=this.streamController=new i(this,p,P),C=this.gapController=f?new f(this,p):void 0;k&&k.setStreamController(D);var O=[A,I,D];m&&O.splice(1,0,m),R&&O.splice(1,0,R),this.networkControllers=O;var x=[g];E&&x.push(E),C&&x.push(C),k&&x.push(k),S&&(S.setStreamController(D),x.push(S)),w&&x.push(w),x.push(p),this.audioTrackController=this.createController(n.audioTrackController,O);var M=n.audioStreamController;M&&O.push(this.audioStreamController=new M(this,p,P)),this.subtitleTrackController=this.createController(n.subtitleTrackController,O);var F=n.subtitleStreamController;F&&O.push(this.subtititleStreamController=new F(this,p,P)),this.createController(n.timelineController,x),P.emeController=this.emeController=this.createController(n.emeController,x),b&&x.push(b),this.latencyController=this.createController(n.latencyController,x),this.coreComponents=x,this.iframeController=h?new h(this,e):void 0,O.push(v);var N=v.onErrorOut;"function"==typeof N&&this.on(B.ERROR,N,v),this.on(B.MANIFEST_LOADED,A.onManifestLoaded,A)}return h(e,[{key:"createController",value:function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(e,t,r)}},{key:"once",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(e,t,r)}},{key:"removeAllListeners",value:function(e){this._emitter.removeAllListeners(e)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,n=arguments.length>3?arguments[3]:void 0;this._emitter.off(e,t,r,n)}},{key:"listeners",value:function(e){return this._emitter.listeners(e)}},{key:"emit",value:function(e,t,r){return this._emitter.emit(e,t,r)}},{key:"trigger",value:function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(n){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;var r=e===B.ERROR;this.trigger(B.ERROR,{type:N.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,fatal:r,event:e,error:n}),this.triggeringException=!1}}return!1}},{key:"listenerCount",value:function(e){return this._emitter.listenerCount(e)}},{key:"destroy",value:function(){this.logger.log("destroy"),this.trigger(B.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(function(e){return e.destroy()}),this.networkControllers.length=0,this.coreComponents.forEach(function(e){return e.destroy()}),this.coreComponents.length=0,this.iframeController=void 0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}},{key:"attachMedia",value:function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument (".concat(e,")"));this.trigger(B.ERROR,{type:N.OTHER_ERROR,details:U.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var r="media"in e,n=r?e.media:e,i=r?e:{media:n};this._media=n,this.trigger(B.MEDIA_ATTACHING,i)}}},{key:"detachMedia",value:function(){this.logger.log("detachMedia");var e={};this.trigger(B.MEDIA_DETACHING,e),this._media=null,this.trigger(B.MEDIA_DETACHED,e)}},{key:"transferMedia",value:function(){var e;this._media=null;var t=(null==(e=this.bufferController)?void 0:e.transferMedia())||null,r={transferMedia:t};return this.trigger(B.MEDIA_DETACHING,r),this.trigger(B.MEDIA_DETACHED,r),t}},{key:"loadSource",value:function(e){var t;this.stopLoad();var r=this.media,n=this._url,i=this._url=H.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(i)),r&&n&&(n!==i||null!=(t=this.bufferController)&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(B.MANIFEST_LOADING,{url:e})}},{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"startLoad",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,t=arguments.length>1?arguments[1]:void 0;this.logger.log("startLoad(".concat(e+(t?", <skip seek to start>":""),")")),this.started=!0,this.resumeBuffering();for(var r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);}},{key:"stopLoad",value:function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}},{key:"loadingEnabled",get:function(){return this.started&&this.streamController.state!==Bi}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"resumeBuffering",value:function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(function(e){e.resumeBuffering&&e.resumeBuffering()}))}},{key:"pauseBuffering",value:function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(function(e){e.pauseBuffering&&e.pauseBuffering()}))}},{key:"inFlightFragments",get:function(){var e=v({},W.MAIN,this.streamController.inFlightFrag);return this.audioStreamController&&(e[W.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[W.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}},{key:"swapAudioCodec",value:function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{key:"recoverMediaError",value:function(){this.logger.log("recoverMediaError");var e=this._media,t=this.started,r=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(r?this.startLoad(r):this.config.autoStartLoad||this.startLoad()))}},{key:"removeLevel",value:function(e){this.levelController.removeLevel(e)}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=Oe()),e}},{key:"levels",get:function(){var e=this.levelController.levels;return e||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:".concat(e)),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:".concat(e)),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:".concat(e)),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=this.capLevelController,r=!!e;t&&r!==this.config.capLevelToPlayerSize&&(r?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:".concat(e)),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return lr.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,n=0;n<r;n++)if(e[n].maxBitrate>=t)return n;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,n=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,n)for(var i=e;i--;){var a=t[i].attrs["HDCP-LEVEL"];if(a&&a<=n)return i}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"audioForwardBufferInfo",get:function(){var e;return(null==(e=this.audioStreamController)?void 0:e.getFwdBufferInfo())||null}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"setAudioOption",value:function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}},{key:"setSubtitleOption",value:function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"nextAudioTrack",get:function(){var e,t;return null!=(e=null==(t=this.audioStreamController)?void 0:t.nextAudioTrack)?e:-1},set:function(e){var t=this.audioTrackController;t&&(t.nextAudioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){var e,t;return null!=(e=null==(t=this.latencyController)?void 0:t.liveSyncPosition)?e:null}},{key:"latency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.latency)||0}},{key:"maxLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.maxLatency)||0}},{key:"targetLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.targetLatency)||null},set:function(e){this.latencyController&&(this.latencyController.targetLatency=e)}},{key:"drift",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.drift)||null}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}},{key:"iframeVariants",get:function(){var e=this.levelController.iframeVariants;return e||[]}},{key:"createIFramePlayer",value:function(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}},{key:"createImageIFramePlayer",value:function(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}},{key:"getMediaDecodingInfo",value:function(e){return ir(e,kr(arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks),navigator.mediaCapabilities)}}],[{key:"version",get:function(){return aa}},{key:"isMSESupported",value:function(){return _u()}},{key:"isSupported",value:function(){return function(){if(!_u())return!1;var e=Re();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(function(t){return e.isTypeSupported(Vt(t,"video"))})||["mp4a.40.2","fLaC"].some(function(t){return e.isTypeSupported(Vt(t,"audio"))}))}()}},{key:"getMediaSource",value:function(){return Re()}},{key:"Events",get:function(){return B}},{key:"MetadataSchema",get:function(){return ga}},{key:"ErrorTypes",get:function(){return N}},{key:"ErrorDetails",get:function(){return U}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:Uc},set:function(t){e.defaultConfig=t}}])}();Jc.defaultConfig=void 0;var Zc=/iPhone|iPad|iPod|iOS/i.test(navigator.userAgent),ed=function(){if("undefined"==typeof navigator)return!1;var e=navigator.userAgent||"",t=navigator.platform||"",r="number"==typeof navigator.maxTouchPoints?navigator.maxTouchPoints:0;return!!/iPad/i.test(e)||(!!(/Macintosh/i.test(e)&&r>1)||"MacIntel"===t&&r>1)},td=function(){return Zc||ed()},rd=function(){if("undefined"==typeof navigator)return!1;var e=navigator.userAgent||"";return/UCBrowser|UCWEB|UBrowser|Quark|AliApp|QHBrowser/i.test(e)},nd=["hvc1.1.6.L93.B0","hev1.1.6.L93.B0","hvc1","hev1"];function id(e){return"probably"===e||"maybe"===e}var ad=function(){var e=!!(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).isEncrypt,t=function(){if("undefined"==typeof navigator)return!1;var e=navigator.userAgent||"";return!!td()||/Safari/i.test(e)&&!/Chrome|Chromium|CriOS|Edg|Android/i.test(e)}(),r=function(){if("undefined"==typeof document)return!1;var e=document.createElement("video");return!(!e||"function"!=typeof e.canPlayType)&&(id(e.canPlayType("application/vnd.apple.mpegurl"))||id(e.canPlayType("application/x-mpegURL")))}(),n=function(){if("undefined"==typeof document)return{supported:!1,detail:""};var e=document.createElement("video");if(!e||"function"!=typeof e.canPlayType)return{supported:!1,detail:""};for(var t=0;t<nd.length;t++){var r=nd[t],n='video/mp4; codecs="'.concat(r,'"'),i=e.canPlayType(n);if(id(i))return{supported:!0,detail:i,codec:r,mime:n}}return{supported:!1,detail:""}}(),i=n.supported;return e?{supported:!1,reason:"encrypted",nativeHls:r,nativeHevc:i,isSafariLike:t}:r&&t?i?{supported:!0,reason:"ok",nativeHls:r,nativeHevc:i,isSafariLike:t,nativeHevcDetail:n}:{supported:!1,reason:"no_native_hevc",nativeHls:r,nativeHevc:i,isSafariLike:t}:{supported:!1,reason:"no_native_hls",nativeHls:r,nativeHevc:i,isSafariLike:t}},sd=!1;function od(){if(!sd&&"undefined"!=typeof document)if(document.querySelector("[data-hx-player-style]"))sd=!0;else{sd=!0;var e=document.createElement("style");e.setAttribute("data-hx-player-style","1"),e.textContent=".ylc-player-container,\r\n.ylc-live-player-container {\r\n position: relative;\r\n width: 100%;\r\n height: 100%;\r\n background: #000;\r\n overflow: hidden;\r\n isolation: isolate;\r\n transform: translateZ(0);\r\n -webkit-transform: translateZ(0);\r\n}\r\n\r\n.ylc-video-player,\r\n.ylc-live-player-video {\r\n position: relative;\r\n z-index: 0;\r\n width: 100%;\r\n height: 100%;\r\n background: #000;\r\n overflow: hidden;\r\n object-fit: contain;\r\n pointer-events: none;\r\n -webkit-appearance: none;\r\n appearance: none;\r\n}\r\n\r\n.ylc-video-player::-webkit-media-controls,\r\n.ylc-video-player::-webkit-media-controls-enclosure,\r\n.ylc-video-player::-webkit-media-controls-overlay-enclosure,\r\n.ylc-video-player::-webkit-media-controls-panel,\r\n.ylc-video-player::-webkit-media-controls-start-playback-button,\r\n.ylc-video-player::-webkit-media-controls-overlay-play-button,\r\n.ylc-video-player::-webkit-media-controls-timeline,\r\n.ylc-video-player::-webkit-media-controls-current-time-display,\r\n.ylc-video-player::-webkit-media-controls-time-remaining-display,\r\n.ylc-video-player::-webkit-media-controls-mute-button,\r\n.ylc-video-player::-webkit-media-controls-toggle-closed-captions-button,\r\n.ylc-video-player::-webkit-media-controls-volume-slider,\r\n.ylc-video-player::-webkit-media-controls-fullscreen-button,\r\n.ylc-video-player::-webkit-media-controls-play-button,\r\n.ylc-video-player::-internal-media-controls-overflow-button {\r\n display: none !important;\r\n opacity: 0 !important;\r\n pointer-events: none !important;\r\n -webkit-appearance: none !important;\r\n visibility: hidden !important;\r\n width: 0 !important;\r\n height: 0 !important;\r\n max-height: 0 !important;\r\n}\r\n\r\n.ylc-video-canvas-mirror {\r\n position: absolute;\r\n left: 0;\r\n top: 0;\r\n width: 100%;\r\n height: 100%;\r\n z-index: 1;\r\n background: #000;\r\n pointer-events: none;\r\n display: block;\r\n}\r\n\r\n.ylc-video-touch-mask {\r\n position: absolute;\r\n left: 0;\r\n top: 0;\r\n width: 100%;\r\n height: 100%;\r\n z-index: 2;\r\n background: transparent;\r\n}\r\n\r\n.ylc-video-player-loading {\r\n display: none;\r\n position: absolute;\r\n left: 50%;\r\n top: 50%;\r\n z-index: 3;\r\n width: 48px;\r\n height: 48px;\r\n margin: -24px 0 0 -24px;\r\n pointer-events: none;\r\n}\r\n\r\n.ylc-video-player-loading.is-show {\r\n display: block;\r\n}\r\n\r\n.ylc-video-player-loading-spinner {\r\n width: 100%;\r\n height: 100%;\r\n box-sizing: border-box;\r\n border: 3px solid rgba(255, 255, 255, 0.25);\r\n border-top-color: #fff;\r\n border-radius: 50%;\r\n animation: ylc-player-spin 0.7s linear infinite;\r\n}\r\n\r\n@keyframes ylc-player-spin {\r\n to {\r\n transform: rotate(360deg);\r\n }\r\n}\r\n\r\n.ylc-video-player-control {\r\n position: absolute;\r\n bottom: 0;\r\n left: 0;\r\n width: 100%;\r\n height: 65px;\r\n z-index: 2147483646;\r\n padding: 8px;\r\n background: linear-gradient(180deg, rgba(8, 9, 13, 0), rgba(8, 9, 13, 0.8));\r\n box-sizing: border-box;\r\n pointer-events: auto;\r\n}\r\n\r\n.ylc-video-player-progerss {\r\n display: flex;\r\n align-items: center;\r\n position: relative;\r\n width: 100%;\r\n height: 30px;\r\n}\r\n\r\n.ylc-video-player-progress-hover-time {\r\n display: none;\r\n position: absolute;\r\n bottom: calc(100% - 4px);\r\n left: 0;\r\n z-index: 100;\r\n padding: 2px 6px;\r\n background: rgba(0, 0, 0, 0.75);\r\n color: #fff;\r\n font-size: 12px;\r\n line-height: 16px;\r\n border-radius: 2px;\r\n white-space: nowrap;\r\n pointer-events: none;\r\n transform: translateX(-50%);\r\n}\r\n\r\n.ylc-video-player-progress-hover-time.is-show {\r\n display: block;\r\n}\r\n\r\n.ylc-video-player-progress-line-bg {\r\n position: absolute;\r\n left: 0;\r\n width: 100%;\r\n height: 3px;\r\n z-index: 9;\r\n background: hsla(0, 15%, 90%, 0.4);\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-progress-line {\r\n position: absolute;\r\n left: 0;\r\n width: 0;\r\n height: 3px;\r\n z-index: 99;\r\n background: #fff;\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-progress-line-dot {\r\n position: absolute;\r\n left: 0;\r\n width: 15px;\r\n height: 15px;\r\n z-index: 99;\r\n border-radius: 50%;\r\n background: #fff;\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-btn-bar-container {\r\n display: flex;\r\n justify-content: space-between;\r\n position: relative;\r\n width: 100%;\r\n}\r\n\r\n.ylc-video-player-btn-bar-left,\r\n.ylc-video-player-btn-bar-right {\r\n display: flex;\r\n align-items: center;\r\n}\r\n\r\n.ylc-video-player-play-button,\r\n.ylc-video-player-pause-button {\r\n display: block;\r\n width: 20px;\r\n height: 20px;\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-pause-button {\r\n display: none;\r\n}\r\n\r\n.ylc-video-player-current-time,\r\n.ylc-video-player-total-time,\r\n.ylc-video-player-time-split {\r\n color: #fff;\r\n font-size: 12px;\r\n}\r\n\r\n.ylc-video-player-current-time {\r\n margin-left: 10px;\r\n}\r\n\r\n.ylc-video-player-time-split {\r\n padding: 0 5px;\r\n}\r\n\r\n.ylc-video-player-rate-button,\r\n.ylc-video-player-line-button {\r\n position: relative;\r\n color: #fff;\r\n font-size: 12px;\r\n margin-left: 10px;\r\n cursor: pointer;\r\n user-select: none;\r\n}\r\n\r\n.ylc-video-player-volume-button,\r\n.ylc-video-player-mute-button,\r\n.ylc-video-player-exit-full-screen-button {\r\n width: 20px;\r\n height: 20px;\r\n cursor: pointer;\r\n margin-left: 10px;\r\n}\r\n\r\n.ylc-video-player-full-screen-button {\r\n width: 16px;\r\n height: 16px;\r\n cursor: pointer;\r\n margin-left: 10px;\r\n}\r\n\r\n.ylc-video-player-mute-button,\r\n.ylc-video-player-exit-full-screen-button {\r\n display: none;\r\n}\r\n\r\n.ylc-video-player-rate-list,\r\n.ylc-video-player-line-panel {\r\n display: none;\r\n position: absolute;\r\n left: 50%;\r\n bottom: 100%;\r\n transform: translateX(-50%);\r\n z-index: 20;\r\n min-width: 72px;\r\n margin: 0;\r\n padding: 6px 0;\r\n list-style: none;\r\n background: rgba(0, 0, 0, 0.85);\r\n border-radius: 4px;\r\n}\r\n\r\n.ylc-video-player-line-panel {\r\n padding: 0 0 12px;\r\n background: transparent;\r\n min-width: auto;\r\n}\r\n\r\n.ylc-video-player-line-list {\r\n min-width: 72px;\r\n margin: 0;\r\n padding: 6px 0;\r\n list-style: none;\r\n background: rgba(0, 0, 0, 0.85);\r\n border-radius: 4px;\r\n}\r\n\r\n.ylc-video-player-rate-item,\r\n.ylc-video-player-line-item {\r\n padding: 8px 14px;\r\n text-align: center;\r\n white-space: nowrap;\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-rate-item.active,\r\n.ylc-video-player-line-item.active {\r\n font-weight: 600;\r\n}\r\n\r\n.ylc-live-player-badge {\r\n position: absolute;\r\n top: 12px;\r\n left: 12px;\r\n padding: 2px 8px;\r\n border-radius: 2px;\r\n background: #e53935;\r\n color: #fff;\r\n font-size: 12px;\r\n font-weight: 600;\r\n letter-spacing: 1px;\r\n z-index: 2;\r\n}\r\n\r\n.ylc-live-player-status {\r\n position: absolute;\r\n left: 50%;\r\n top: 50%;\r\n transform: translate(-50%, -50%);\r\n color: rgba(255, 255, 255, 0.85);\r\n font-size: 14px;\r\n z-index: 2;\r\n pointer-events: none;\r\n}\r\n\r\n.ylc-live-player-controls {\r\n position: absolute;\r\n left: 0;\r\n right: 0;\r\n bottom: 0;\r\n height: 48px;\r\n display: flex;\r\n align-items: center;\r\n padding: 0 12px;\r\n box-sizing: border-box;\r\n background: linear-gradient(transparent, rgba(0, 0, 0, 0.65));\r\n z-index: 2;\r\n}\r\n\r\n.ylc-live-player-controls img {\r\n width: 28px;\r\n height: 28px;\r\n margin-right: 10px;\r\n cursor: pointer;\r\n user-select: none;\r\n}\r\n\r\n.ylc-live-pause-button,\r\n.ylc-live-exit-full-screen-button {\r\n display: none;\r\n}\r\n",document.head.appendChild(e)}}var ld=/quark-video-controls|browser-video-controls|uc-video-controls|ucbrowser|ali-video-controls|qh-video-controls|miui-video|mi-video-controls|xiaomi-video|video-overlay-controls|mibrowser|mi-browser|video-player-controller|native-video-controls|sys-video-controls/i,ud=/^ylc-/,cd=/^(SCRIPT|STYLE|LINK|META)$/,dd=!1;function hd(){if(od(),!dd&&"undefined"!=typeof document){if(dd=!0,!document.querySelector('meta[name="x5-video-player-type"]')){var e=document.createElement("meta");e.setAttribute("name","x5-video-player-type"),e.setAttribute("content","h5"),document.head.appendChild(e)}if(!document.querySelector('meta[name="x5-video-player-fullscreen"]')){var t=document.createElement("meta");t.setAttribute("name","x5-video-player-fullscreen"),t.setAttribute("content","false"),document.head.appendChild(t)}}}function fd(e){if(!e||1!==e.nodeType)return!1;if(e.getAttribute&&e.getAttribute("data-ylc"))return!0;var t=e.className&&String(e.className);return!!t&&String(t).split(/\s+/).some(function(e){return ud.test(e)})}function vd(e){if(!e||1!==e.nodeType||fd(e))return!1;if(cd.test(e.tagName))return!1;var t=e.className&&String(e.className),r=e.id&&String(e.id),n="".concat(t||""," ").concat(r||"");return!!ld.test(n)||!(!e.getAttribute||!e.getAttribute("data-browser-controls"))}function gd(e){if(e&&1===e.nodeType){try{return void e.remove()}catch(t){}try{e.style.setProperty("display","none","important"),e.style.setProperty("opacity","0","important"),e.style.setProperty("pointer-events","none","important"),e.style.setProperty("visibility","hidden","important")}catch(t){}}}function pd(e){e&&(e.controls=!1,e.setAttribute("controlsList","nodownload nofullscreen noremoteplayback noplaybackrate"),e.hasAttribute("controls")&&e.removeAttribute("controls"))}var yd=function(){return h(function e(){c(this,e)},null,[{key:"injectStyle",value:function(){hd()}},{key:"stripNativeControls",value:function(e){pd(e)}},{key:"attach",value:function(e){hd(),pd(e);var t=function(e){vd(e)&&gd(e)},r=function(e){(function(e){if(vd(e))return!0;if(!e||1!==e.nodeType||fd(e))return!1;if(cd.test(e.tagName))return!1;var t=e.className&&String(e.className),r=e.id&&String(e.id),n="".concat(t||""," ").concat(r||"");return/video|media|player/i.test(n)&&/control|toolbar|bar|overlay|panel/i.test(n)})(e)&&gd(e)},n=new MutationObserver(function(t){t.forEach(function(t){"attributes"!==t.type?t.addedNodes.forEach(function(t){r(t),pd(e)}):pd(e)})});n.observe(e,{attributes:!0,attributeFilter:["controls"],childList:!0,subtree:!0});var i=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(r)})}),a=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&t(e)})})}),s="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent||"")?50:200,o=setInterval(function(){pd(e);var r=e.parentElement;r&&Array.from(r.children).forEach(function(r){r!==e&&t(r)})},s),l=setTimeout(function(){if(e.parentElement){i.observe(e.parentElement,{childList:!0,subtree:!1});var t=e.closest(".ylc-player-container");t&&a.observe(t,{childList:!0})}},0),u=["play","playing","pause","loadedmetadata","loadeddata","canplay","seeking","seeked"],c=function(){return pd(e)};u.forEach(function(t){return e.addEventListener(t,c)});var d=function(t){t&&"function"==typeof t.preventDefault&&t.preventDefault();try{e.webkitExitFullScreen&&e.webkitExitFullScreen()}catch(Ry){}pd(e)};e.addEventListener("webkitbeginfullscreen",d);var h=e.remove;return e.remove=function(){clearInterval(o),clearTimeout(l),n.disconnect(),i.disconnect(),a.disconnect(),u.forEach(function(t){return e.removeEventListener(t,c)}),e.removeEventListener("webkitbeginfullscreen",d),h.call(this)},rd()&&e.setAttribute("airplay","allow"),e}}])}(),md="https://shanhu-live-user-1317978474.cos.accelerate.myqcloud.com/web/shplayer_icon";function Ed(e){var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstElementChild}var kd=function(){function e(){c(this,e)}return h(e,null,[{key:"injectStyle",value:function(){od(),yd.injectStyle()}},{key:"createVideoElement",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=document.createElement("video");t.className="ylc-video-player",t.muted=!!e.muted,e.poster&&(t.poster=e.poster),yd.stripNativeControls(t),t.setAttribute("x5-video-player-type","h5"),t.setAttribute("x5-video-player-fullscreen","false"),t.setAttribute("x5-video-orientation","portrait"),t.setAttribute("x5-playsinline","true"),t.setAttribute("crossorigin","anonymous"),t.crossOrigin="anonymous",t.setAttribute("playsinline","true"),t.setAttribute("webkit-inline","true"),t.setAttribute("webkit-playsinline","true"),t.setAttribute("x-webkit-airplay","allow"),t.setAttribute("preload","metadata"),t.setAttribute("disablePictureInPicture","true"),t.setAttribute("controlsList","nodownload nofullscreen noremoteplayback noplaybackrate"),t.playsInline=!0,t.disablePictureInPicture=!0,"disableRemotePlayback"in t&&(t.disableRemotePlayback=!0),t.setAttribute("t7-video-player-type","inline"),t.setAttribute("t7-video-player-fullscreen","false"),rd()&&t.setAttribute("airplay","allow");var r=t.play.bind(t);return t.play=function(){return t.setAttribute("t7-video-player-type","inline"),t.setAttribute("x5-video-player-type","h5"),t.setAttribute("x5-video-player-fullscreen","false"),t.controls=!1,t.removeAttribute("controls"),r()},yd.attach(t),t}},{key:"mount",value:function(t){e.injectStyle();var r=Ed(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.showControls,r=void 0===t||t,n=e.currentLine,i=2===Number(void 0===n?1:n)?2:1,a=r?'\n <div class="ylc-video-player-control">\n <div class="ylc-video-player-progerss">\n <div class="ylc-video-player-progress-hover-time">00:00</div>\n <div class="ylc-video-player-progress-line-dot"></div>\n <div class="ylc-video-player-progress-line-bg"></div>\n <div class="ylc-video-player-progress-line"></div>\n </div>\n <div class="ylc-video-player-btn-bar-container">\n <div class="ylc-video-player-btn-bar-left">\n <img class="ylc-video-player-play-button" src="'.concat(md,'/play_pause.png" alt="">\n <img class="ylc-video-player-pause-button" src="').concat(md,'/new_play_pause.png" alt="">\n <span id="ylcCurrentTime" class="ylc-video-player-current-time">00:00 </span>\n <span class="ylc-video-player-time-split">/</span>\n <span id="ylcTotalTime" class="ylc-video-player-total-time">00:00</span>\n </div>\n <div class="ylc-video-player-btn-bar-right">\n \x3c!-- 切线路 UI 暂时关闭\n <div class="ylc-video-player-line-button">\n <span class="ylc-video-player-line-label">').concat(2===i?"线路2":"线路1",'</span>\n <div class="ylc-video-player-line-panel">\n <ul class="ylc-video-player-line-list">\n <li class="ylc-video-player-line-item').concat(1===i?" active":"",'" data-value="1">线路1</li>\n <li class="ylc-video-player-line-item').concat(2===i?" active":"",'" data-value="2">线路2</li>\n </ul>\n </div>\n </div>\n --\x3e\n <div class="ylc-video-player-rate-button">\n <span>倍数</span>\n <ul class="ylc-video-player-rate-list">\n <li class="ylc-video-player-rate-item" data-value="3">3.0X</li>\n <li class="ylc-video-player-rate-item" data-value="2">2.0X</li>\n <li class="ylc-video-player-rate-item active" data-value="1">1.0X</li>\n <li class="ylc-video-player-rate-item" data-value="0.5">0.5X</li>\n </ul>\n </div>\n <img class="ylc-video-player-volume-button" src="').concat(md,'/yinliang.png" alt="">\n <img class="ylc-video-player-mute-button" src="').concat(md,'/jingyin.png" alt="">\n <img class="ylc-video-player-full-screen-button" src="').concat(md,'/ylc_full_screen.png" alt="">\n <img class="ylc-video-player-exit-full-screen-button" src="').concat(md,'/ylc_exit_screen.png" alt="">\n </div>\n </div>\n </div>'):"";return'\n <div class="ylc-player-container">\n <div class="ylc-video-touch-mask" data-ylc="touch-mask"></div>\n <div class="ylc-video-player-loading" aria-hidden="true">\n <div class="ylc-video-player-loading-spinner"></div>\n </div>\n '.concat(a,"\n </div>\n ")}({showControls:!(!t.options||!t.options.controls),currentLine:t.currentLine})),n=e.createVideoElement(t.options||{});return n.controls=!1,n.removeAttribute("controls"),r.insertBefore(n,r.firstChild),t.container=r,t.videoElm=n,t.touchMask=r.querySelector(".ylc-video-touch-mask"),t.loadingElm=r.querySelector(".ylc-video-player-loading"),r}}])}(),Sd=function(){return h(function e(t){c(this,e),this.target=t,this.eventsQueue={}},[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.eventsQueue[e]||(this.eventsQueue[e]={methods:[],onceFlags:[]}),this.eventsQueue[e].methods.includes(t)||(this.eventsQueue[e].methods.push(t),this.eventsQueue[e].onceFlags.push(!!r))}},{key:"once",value:function(e,t){this.on(e,t,!0)}},{key:"emit",value:function(e){for(var t=this,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];var a=this.eventsQueue[e];if(a){var s=a.methods,o=a.onceFlags,l=[],u=[];s.forEach(function(r,i){try{r.apply(t.target,n)}catch(a){console.error("[VideoPlayer Events]",e,a)}o[i]||(l.push(r),u.push(!1))}),a.methods=l,a.onceFlags=u}}},{key:"off",value:function(e,t){var r=this.eventsQueue[e];if(r)if(t){var n=r.methods.indexOf(t);n>=0&&(r.methods.splice(n,1),r.onceFlags.splice(n,1)),r.methods.length||delete this.eventsQueue[e]}else delete this.eventsQueue[e]}},{key:"removeAll",value:function(){this.eventsQueue={}}}])}(),Td="wss://log-reporting.huaxiacloud.net/ws",bd=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};c(this,e),this.options=k({baseUrl:Td,connectTimeoutMs:1e4,reconnectDelayMs:2e3,maxReconnect:5,autoReconnect:!0},t),this.ws=null,this.userId=null!=this.options.userId?String(this.options.userId):"",this.terminal=this.options.terminal||e.detectTerminal(),this.sessionId="",this._manualClose=!1,this._connecting=!1,this._reconnectCount=0,this._connectTimer=null,this._reconnectTimer=null,this._pendingQueue=[],this._connectingPromise=null}return h(e,[{key:"connected",get:function(){return!(!this.ws||this.ws.readyState!==WebSocket.OPEN)}},{key:"buildUrl",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.userId,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.terminal,r=this.options.baseUrl||Td,n="user_id=".concat(encodeURIComponent(String(e)),"&terminal=").concat(encodeURIComponent(t));return r.includes("?")?"".concat(r,"&").concat(n):"".concat(r,"?").concat(n)}},{key:"connect",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return null!=t.userId&&(this.userId=String(t.userId)),t.terminal&&(this.terminal=t.terminal),this.connected?Promise.resolve(this):this._connecting?this._connectingPromise||Promise.resolve(this):(this._manualClose=!1,this._connecting=!0,this.sessionId="",this._connectingPromise=new Promise(function(t,r){var n=!1,i="";try{i=e.buildUrl()}catch(s){return e._connecting=!1,e._logError("连接参数错误",s),void r(s)}e._clearConnectTimer(),e._clearReconnectTimer();try{e.ws=new WebSocket(i)}catch(s){return e._connecting=!1,e._logError("创建 WebSocket 失败",s),e._scheduleReconnect(),void r(s)}var a=e.options.connectTimeoutMs||1e4;e._connectTimer=setTimeout(function(){var t=new Error("[LogWebSocket] 连接超时(".concat(a,"ms): ").concat(i));if(e._logError("连接超时",t),"function"==typeof e.options.onTimeout)try{e.options.onTimeout(t)}catch(s){}try{e.ws&&e.ws.close()}catch(s){}e.ws=null,e._connecting=!1,n||(n=!0,r(t)),e._scheduleReconnect()},a),e.ws.onopen=function(){if(e._clearConnectTimer(),e._connecting=!1,e._reconnectCount=0,e._logInfo("连接成功",{url:i}),"function"==typeof e.options.onOpen)try{e.options.onOpen()}catch(s){}n||(n=!0,t(e))},e.ws.onmessage=function(t){if(e._handleMessage(t.data),"function"==typeof e.options.onMessage)try{e.options.onMessage(t.data,t)}catch(s){}},e.ws.onerror=function(t){if(e._logError("连接异常",t),"function"==typeof e.options.onError)try{e.options.onError(t)}catch(s){}},e.ws.onclose=function(t){if(e._clearConnectTimer(),e._connecting=!1,e.ws=null,e.sessionId="",e._logInfo("连接关闭",{code:t.code,reason:t.reason}),"function"==typeof e.options.onClose)try{e.options.onClose(t)}catch(s){}n||(n=!0,r(new Error("[LogWebSocket] 连接关闭 code=".concat(t.code)))),e._manualClose||!1===e.options.autoReconnect||e._scheduleReconnect()}}),this._connectingPromise)}},{key:"report",value:function(e){var t=e;if(!this.connected||!this.sessionId)return this._pendingQueue.push(t),this.connected||this._connecting||this._manualClose||!this.userId||this.connect().catch(function(){}),!1;try{return this.ws.send(this._normalizePayload(t)),!0}catch(r){return this._logError("上报失败",r),this._pendingQueue.push(t),!1}}},{key:"_handleMessage",value:function(e){var t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch(n){return}if(t&&"object"===_(t)){var r=t.session_id||t.sessionId;("session"===t.type||r)&&r&&(this.sessionId=String(r),this._logInfo("收到 session_id",{sessionId:this.sessionId}),this._flushPending())}}},{key:"disconnect",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"client disconnect";if(this._manualClose=!0,this._connecting=!1,this._clearConnectTimer(),this._clearReconnectTimer(),this._reconnectCount=0,this.sessionId="",this.ws){try{this.ws.close(e,t)}catch(r){this._logError("断开连接失败",r)}this.ws=null}}},{key:"clearPending",value:function(){this._pendingQueue=[]}},{key:"_normalizePayload",value:function(e){if(null==e)return"";if("string"==typeof e){try{var t=JSON.parse(e);if(t&&"object"===_(t)&&!Array.isArray(t))return JSON.stringify(this._attachSessionId(t))}catch(r){}return e}if(e instanceof ArrayBuffer||e instanceof Blob)return e;if("object"===_(e))try{return JSON.stringify(this._attachSessionId(e))}catch(r){return String(e)}return String(e)}},{key:"_attachSessionId",value:function(e){var t=k({},e);return this.sessionId&&(null==t.playSessionId&&(t.playSessionId=this.sessionId),t.content&&"object"===_(t.content)&&!Array.isArray(t.content)&&(t.content=k({},t.content),null==t.content.playSessionId&&(t.content.playSessionId=this.sessionId))),t}},{key:"_flushPending",value:function(){var e=this;this.connected&&this.sessionId&&this._pendingQueue.length&&this._pendingQueue.splice(0,this._pendingQueue.length).forEach(function(t){try{e.ws.send(e._normalizePayload(t))}catch(r){e._logError("补发队列失败",r),e._pendingQueue.push(t)}})}},{key:"_scheduleReconnect",value:function(){var e=this;if(!this._manualClose&&!1!==this.options.autoReconnect){var t=this.options.maxReconnect;if(-1!==t&&this._reconnectCount>=t)this._logError("重试次数已达上限,停止重连",{maxReconnect:t,reconnectCount:this._reconnectCount});else if(!this._reconnectTimer){this._reconnectCount+=1;var r=this.options.reconnectDelayMs||2e3,n=Math.min(r*Math.pow(1.5,this._reconnectCount-1),3e4);this._logInfo("准备重试连接",{reconnectCount:this._reconnectCount,delay:n}),this._reconnectTimer=setTimeout(function(){e._reconnectTimer=null,e.connect().catch(function(){})},n)}}}},{key:"_clearConnectTimer",value:function(){this._connectTimer&&(clearTimeout(this._connectTimer),this._connectTimer=null)}},{key:"_clearReconnectTimer",value:function(){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null)}},{key:"_logInfo",value:function(e,t){void 0!==t?console.log("[LogWebSocket] ".concat(e),t):console.log("[LogWebSocket] ".concat(e))}},{key:"_logError",value:function(e,t){void 0!==t?console.error("[LogWebSocket] ".concat(e),t):console.error("[LogWebSocket] ".concat(e))}}],[{key:"getInstance",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e._instance?t&&Object.keys(t).length&&(e._instance.options=k(k({},e._instance.options),t),null!=t.userId&&(e._instance.userId=String(t.userId)),t.terminal&&(e._instance.terminal=t.terminal)):e._instance=new e(t),e._instance}},{key:"connect",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e.getInstance(t).connect(t)}},{key:"report",value:function(t){return e.getInstance().report(t)}},{key:"getSessionId",value:function(){return e._instance&&e._instance.sessionId||""}},{key:"disconnect",value:function(t,r){e._instance&&e._instance.disconnect(t,r)}},{key:"isConnected",value:function(){return!(!e._instance||!e._instance.connected)}},{key:"detectTerminal",value:function(){return function(){var e=navigator.userAgent.toLowerCase(),t=/android|webos|iphone|ipod|blackberry|iemobile|opera mini/.test(e);return/ipad/.test(e)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1?"ipad":t?"h5":"pc"}()}}])}();v(bd,"_instance",null);var Ad={info:"流程日志",error:"错误日志",click:"点击事件日志",operate:"操作日志",fetch:"接口日志",metric:"指标日志"},Ld=function(){function e(){c(this,e)}return h(e,null,[{key:"setAppContext",value:function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).appId;null!=t&&(e._appId=t)}},{key:"info",value:function(t,r){e._report("info",t,r)}},{key:"error",value:function(t,r){e._report("error",t,r)}},{key:"click",value:function(t,r){e._report("click",t,r)}},{key:"operate",value:function(t,r){e._report("operate",t,r)}},{key:"fetch",value:function(t,r){e._report("fetch",t,r)}},{key:"metric",value:function(t,r){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).sampleEvery,i=void 0===n?10:n;e._metricCount+=1,i>1&&e._metricCount%i!==1||e._report("metric",t,r)}},{key:"_report",value:function(t,r,n){bd.report({content:{eventType:t,eventName:Ad[t]||"流程日志",eventCode:"",errorCode:"error"===t?"error":"",message:r,params:n,appId:e._appId}})}}])}();v(Ld,"_metricCount",0),v(Ld,"_appId","");var Rd=function(){function e(){c(this,e)}return h(e,null,[{key:"loadWasm",value:(i=o(S().m(function t(){return S().w(function(t){for(;;)switch(t.n){case 0:if(!e.module){t.n=1;break}return t.a(2,e.module);case 1:if(!e.loadPromise){t.n=2;break}return t.a(2,e.loadPromise);case 2:return e.isLoading=!0,e.loadPromise=e._loadWasmOnce().then(function(t){return e.module=t,e.isLoading=!1,t}).catch(function(t){throw e.isLoading=!1,e.loadPromise=null,t}),t.a(2,e.loadPromise)}},t)})),function(){return i.apply(this,arguments)})},{key:"_loadWasmOnce",value:(n=o(S().m(function t(){var r,n,i,a,s,o,l,u,c,d,h,f;return S().w(function(t){for(;;)switch(t.n){case 0:return r=Date.now(),n="".concat(e.baseUrl,"/decryptor/decryptor.js?v=").concat(r),i="".concat(e.baseUrl,"/decryptor/decryptor.wasm?v=").concat(r),t.n=1,fetch(n);case 1:if((a=t.v).ok){t.n=2;break}throw new Error("Failed to fetch decryptor.js: ".concat(a.status));case 2:return t.n=3,a.text();case 3:return s=t.v,t.n=4,fetch(i);case 4:if((o=t.v).ok){t.n=5;break}throw new Error("Failed to fetch decryptor.wasm: ".concat(o.status));case 5:return h=Uint8Array,t.n=6,o.arrayBuffer();case 6:if(f=t.v,l=new h(f),s=(s=(s=s.replace(/import\.meta\.url/g,JSON.stringify(n))).replace(/import\.meta/g,"{}")).replace(/export\s+default\s+Module\s*;?/,"window.__decryptorModuleExport = Module;"),(u=document.createElement("script")).type="text/javascript",u.textContent=s,document.head.appendChild(u),c=window.__decryptorModuleExport,u.remove(),delete window.__decryptorModuleExport,"function"==typeof c){t.n=7;break}throw new Error("Module export not found");case 7:return t.n=8,c({wasmBinary:l,locateFile:function(e){return e&&-1!==String(e).indexOf(".wasm")?i:e}});case 8:return d=t.v,t.a(2,d)}},t)})),function(){return n.apply(this,arguments)})},{key:"normalizeFileId",value:function(e){if("string"==typeof e&&e.trim())return e.trim();if(e&&"object"===_(e)){var t=e.fileid,r=e.fileId;if("string"==typeof t&&t.trim())return t.trim();if("string"==typeof r&&r.trim())return r.trim()}throw new Error("invalid fileid")}},{key:"normalizeAuthCipher",value:function(e,t){if("string"==typeof t&&t.trim())return t.trim();if(e&&"object"===_(e)){var r=e.authCipher,n=e.authToken,i=e.encryptedAuth;if("string"==typeof r&&r.trim())return r.trim();if("string"==typeof n&&n.trim())return n.trim();if("string"==typeof i&&i.trim())return i.trim()}throw new Error("invalid authCipher")}},{key:"decryptSegment",value:(r=o(S().m(function t(r,n,i){var a,s,o,l,u,c,d,h,f,v,g,p,y,m,E,k,T,b;return S().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.n=1,e.loadWasm();case 1:if(a=t.v,s=a.cwrap("decrypt_ts_segment","number",["number","number","number","number","number","number"]),o=a.cwrap("free_buffer",null,["number"]),l=a.cwrap("last_error","number",[]),u=e.normalizeFileId(n),c=e.normalizeAuthCipher(n,i),d=a._malloc(r.length),a.HEAPU8.set(r,d),h=u.length+1,f=a._malloc(h),a.stringToUTF8(u,f,h),v=c.length+1,g=a._malloc(v),a.stringToUTF8(c,g,v),p=a._malloc(4),y=a._malloc(4),t.p=2,0===(m=s(d,r.length,f,g,p,y))){t.n=3;break}throw E=l(),new Error("decrypt_ts_segment failed(".concat(m,"): ").concat(a.UTF8ToString(E)));case 3:return k=a.getValue(p,"*"),T=a.getValue(y,"i32"),(b=new Uint8Array(T)).set(a.HEAPU8.subarray(k,k+T)),o(k),t.a(2,b);case 4:return t.p=4,a._free(d),a._free(f),a._free(g),a._free(p),a._free(y),t.f(4);case 5:return t.a(2)}},t,null,[[2,,4,5]])})),function(e,t,n){return r.apply(this,arguments)})},{key:"decrypt",value:(t=o(S().m(function t(r,n,i){var a;return S().w(function(t){for(;;)if(0===t.n)return a="string"==typeof n?n:Array.from(n).map(function(e){return String.fromCharCode(e)}).join(""),t.a(2,e.decryptSegment(r,a,i))},t)})),function(e,r,n){return t.apply(this,arguments)})},{key:"init",value:function(){console.log("TsDecrypt initialized")}}]);var t,r,n,i}();v(Rd,"module",null),v(Rd,"isLoading",!1),v(Rd,"loadPromise",null),v(Rd,"baseUrl","https://wanzibook-res-1317978474.cos.ap-guangzhou.myqcloud.com/web/ffmpeglib");var Id,wd,_d=new Map,Pd=function(e){var t=function(e){var t;return(null==e||null===(t=e[0])||void 0===t?void 0:t.url)||null}(e);return t&&_d.get(t)||null},Dd=function(e,t){for(var r=[],n=e.split("\n"),i=new URL(t),a=0;a<n.length;a++){var s=n[a].trim();if(s&&!s.startsWith("#")&&s.includes(".ts")){var o=s;if(!o.startsWith("http"))if(o.startsWith("/"))o="".concat(i.protocol,"//").concat(i.host).concat(o);else{var l=i.pathname.substring(0,i.pathname.lastIndexOf("/")+1);o="".concat(i.protocol,"//").concat(i.host).concat(l).concat(o)}r.push(o)}}return r},Cd=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e||!e.length)return{validCdnIndices:[],baseM3u8Url:null};var r=e[0].url,n=[];if(e.forEach(function(e,r){var i=t[e.url];i&&n.push({index:r,url:e.url,tsUrls:Dd(i,e.url)})}),0===n.length)return{validCdnIndices:[],baseM3u8Url:null};var i=n[0].tsUrls.length,a=n.filter(function(e){return e.tsUrls.length===i}),s={};a.forEach(function(e){s[e.index]=e.tsUrls});var o=a.map(function(e){return e.index});return _d.set(r,{tsMap:s,validCdnIndices:o,baseM3u8Url:r}),{validCdnIndices:o,baseM3u8Url:r}},Od=function(e){function t(e){var r;if(c(this,t),(r=u(this,t,[e])).cdnList=e.cdnList||[],r.switchCdn=e.switchCdn||!1,r.isEncrypt=e.isEncrypt||!1,r.encryptedData=e.encryptedData||"",r.fileId=e.fileId||"",r.m3u8Cache=e.m3u8Cache||null,r.switchCdn&&r.cdnList.length>0)try{Cd(r.cdnList,r.m3u8Cache||{})}catch(n){}return r}return y(t,e),h(t,[{key:"load",value:function(e,r,n){var i=e&&e.url,a=e&&e.frag;if(i&&i.match(/\.ts(\?.*)?$/)&&a)return this.stats&&this.stats.loading&&(this.stats.loading.start=performance.now()),void(this.switchCdn?this.loadTsWithCdnFailover(e,r,n):this.loadTsOnce(i,e,r,n));R(t,"load",this)([e,r,n])}},{key:"loadTsWithCdnFailover",value:function(e,t,r){var n,i,a=this,s=e.frag,o=e.url,l=(n=this.cdnList,(i=Pd(n))&&i.validCdnIndices.length?i.validCdnIndices.slice():n&&n.length?n.map(function(e,t){return t}):[]);if(l.length){var u=function(t){if(t>=l.length)r.onError({code:0,text:"all cdn failed"},e,null,a.stats);else{var n=l[t],i=function(e,t,r){var n=Pd(e);if(!n)return null;var i=n.tsMap[r];return!i||t<0||t>=i.length?null:i[t]}(a.cdnList,s.sn,n)||o;a.customDownload(i,function(n,s){s?u(t+1):a.deliverTsData(i,n,e,r)})}};u(0)}else this.loadTsOnce(o,e,t,r)}},{key:"loadTsOnce",value:function(e,t,r,n){var i=this;this.customDownload(e,function(r,a){a?n.onError({code:0,text:a.message},t,null,i.stats):i.deliverTsData(e,r,t,n)})}},{key:"deliverTsData",value:function(e,t,r,n){var i=this.stats;i&&i.loading&&(i.loading.first=i.loading.first||performance.now(),i.loading.end=performance.now(),i.loaded=i.total=t.byteLength);var a=function(t){n.onSuccess({url:e,data:t},i,r,null)};if(this.isEncrypt){var s=new Uint8Array(t);Rd.decrypt(s,this.fileId,this.encryptedData).then(a).catch(function(){n.onError({code:0,text:"decrypt failed"},r,null,i)})}else a(t)}},{key:"customDownload",value:function(e,t){fetch(e).then(function(e){if(!e.ok)throw new Error("HTTP ".concat(e.status));return e.arrayBuffer()}).then(function(e){return t(e,null)}).catch(function(e){return t(null,e)})}},{key:"abort",value:function(){}},{key:"abortFragment",value:function(){}}])}(Jc.DefaultConfig.loader),xd=function(){return h(function e(t){c(this,e),this.config=t||{},this.context=null,this.stats={aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:0,end:0,first:0},parsing:{start:0,end:0},buffering:{start:0,end:0,first:0}}},[{key:"load",value:function(e,t,r){var n=this;this.context=e;var i=e.url;this.stats.loading.start=performance.now(),this.stats.aborted=!1;var a=this.config.m3u8Cache&&this.config.m3u8Cache[i];if(a)return this.stats.loading.first=this.stats.loading.start,void Promise.resolve().then(function(){n.deliverPlaylist(i,a,r)});fetch(i,{method:"GET",headers:{Accept:"application/vnd.apple.mpegurl, */*"}}).then(function(e){if(!e.ok)throw new Error("HTTP ".concat(e.status,": ").concat(e.statusText));return n.stats.loading.first=performance.now(),e.text()}).then(function(e){n.config.m3u8Cache&&(n.config.m3u8Cache[i]=e),n.deliverPlaylist(i,e,r)}).catch(function(t){r.onError({code:t.status||0,text:t.message},e,null,n.stats)})}},{key:"deliverPlaylist",value:function(e,t,r){this.stats.loading.end=performance.now(),this.stats.loaded=t.length,this.stats.total=t.length,this.stats.parsing.start=performance.now();var n=t.replace(/#EXT-X-KEY:[^\r\n]*\r?\n?/g,"");this.stats.parsing.end=performance.now(),r.onSuccess({url:e,data:n,code:200},this.stats,this.context,null)}},{key:"abort",value:function(){}},{key:"destroy",value:function(){this.context=null}},{key:"getCacheAge",value:function(){return null}},{key:"getResponseHeader",value:function(){return null}}])}(),Md=function(){return h(function e(){c(this,e)},null,[{key:"createHlsInstance",value:function(e,t,r,n){Rd.loadWasm();var i=new Jc({loader:Od,pLoader:xd,cdnList:r,switchCdn:t,isEncrypt:n.isEncrypt,encryptedData:n.encryptedData,fileId:n.fileId,m3u8Cache:n.m3u8Cache||null,fragLoadingTimeOut:864e5,manifestLoadingTimeOut:864e5,levelLoadingTimeOut:864e5});return i.attachMedia(e),i.on(Jc.Events.ERROR,function(e,t){if(t&&"bufferAppendError"===t.details&&t.fatal&&i)try{i.recoverMediaError()}catch(r){}}),i}},{key:"startLoad",value:function(e,t){if(!e)throw new Error("HLS 实例不存在");e.loadSource(t)}},{key:"destroyHlsInstance",value:function(e){e&&e.destroy()}}])}(),Fd=function(){return h(function e(){c(this,e)},null,[{key:"changeBtnStatus",value:function(e){e.options.controls&&(e.playButton.style.display="playing"===e.status?"none":"block",e.pauseButton.style.display="playing"===e.status?"block":"none")}}])}(),Nd=function(){return h(function e(){c(this,e)},null,[{key:"timeDouble",value:function(e){return e<10?"0".concat(e):e}},{key:"dealTime",value:function(e){var t=Math.floor(e/60),r=Math.floor(e%60);return"".concat(this.timeDouble(t),":").concat(this.timeDouble(r))}},{key:"updateDurationTime",value:function(e){if(e.options.controls){var t=e.videoElm.duration;e.totalTimeElm.textContent=this.dealTime(t)}}},{key:"updateCurrentTime",value:function(e,t){if(e.options.controls&&e.timeElm){var r=null!=t?t:e.videoElm.currentTime;Number.isFinite(r)&&(e.timeElm.textContent=this.dealTime(r))}}}])}(),Ud=function(){return h(function e(){c(this,e)},null,[{key:"updateLine",value:function(e,t){if(e.options.controls&&e.progressLine){var r=t;if(null==r){var n=e.videoElm&&e.videoElm.duration;if(!n||!Number.isFinite(n))return;r=e.videoElm.currentTime/n}Number.isFinite(r)&&(r=Math.max(0,Math.min(1,r)),e.progressLine.style.width="".concat(100*r,"%"),this.updateLineDot(e,r))}}},{key:"updateLineDot",value:function(e,t){e.options.controls&&e.progressLineDot&&(e.progressLineDot.style.left="".concat(100*t,"%"))}}])}(),Bd=function(){function e(){c(this,e)}return h(e,null,[{key:"getFullscreenTarget",value:function(e){var t=e&&e.options&&e.options.fullscreenElement;if(!t)return e.container;if(t instanceof HTMLElement)return t;if("string"==typeof t){var r=document.querySelector(t);if(r)return r;var n=document.getElementById(t.replace(/^#/,""));if(n)return n}return e.container}},{key:"changeFullScreen",value:function(e,t){e.isFullScreen=t,t?(e.exitFullScreenButton.style.display="block",e.fullScreenButton.style.display="none"):(e.exitFullScreenButton.style.display="none",e.fullScreenButton.style.display="block")}},{key:"fullScreen",value:function(t){if(Zc||ed())t.videoElm&&t.videoElm.webkitEnterFullscreen?t.videoElm.webkitEnterFullscreen():console.warn("iOS video fullscreen not supported");else{var r=e.getFullscreenTarget(t);r.requestFullscreen?r.requestFullscreen():r.mozRequestFullScreen?r.mozRequestFullScreen():r.webkitRequestFullScreen&&(r.webkitRequestFullScreen(),setTimeout(function(){document.dispatchEvent(new Event("fullscreenchange"))},0))}}},{key:"exitFullScreen",value:function(e){Zc?e.videoElm&&e.videoElm.webkitExitFullscreen&&e.videoElm.webkitExitFullscreen():document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}}])}(),Gd=function(){function e(){c(this,e)}return h(e,null,[{key:"changeVolume",value:function(t,r){e.sync(t,r)}},{key:"sync",value:function(e,t){e.videoElm&&(e.videoElm.muted=!t),e.options&&e.options.controls&&e.volumeButton&&e.muteButton&&(t?(e.volumeButton.style.display="block",e.muteButton.style.display="none"):(e.volumeButton.style.display="none",e.muteButton.style.display="block"))}}])}(),jd=function(){return h(function e(t,r){c(this,e),v(this,"events",{}),this.slider=t,this.track=r,this.isDragging=!1,this.startX=0,this.startLeft=0,this.maxOffset=0,this.init()},[{key:"init",value:function(){this.maxOffset=this.track.offsetWidth,this.bindEvents()}},{key:"bindEvents",value:function(){var e=this;this.slider.addEventListener("mousedown",function(t){e.startDrag(t)}),document.addEventListener("mousemove",function(t){e.isDragging&&e.onDrag(t)}),document.addEventListener("mouseup",function(){e.stopDrag()}),this.slider.addEventListener("touchstart",function(t){e.startDragTouch(t)}),document.addEventListener("touchmove",function(t){e.isDragging&&e.onDragTouch(t)}),document.addEventListener("touchend",function(){e.stopDrag()})}},{key:"startDrag",value:function(e){e.preventDefault(),this.isDragging=!0,this.maxOffset=this.track.offsetWidth,this.startX=e.clientX,this.startLeft=this.slider.offsetLeft,this.slider.classList.add("dragging"),this.emit("dragstart",this.getCurrentValue())}},{key:"onDrag",value:function(e){if(this.isDragging){e.preventDefault();var t=e.clientX-this.startX,r=this.startLeft+t;r=Math.max(0,Math.min(this.maxOffset,r)),this.slider.style.left=r+"px",this.emit("drag",this.getCurrentValue())}}},{key:"stopDrag",value:function(){this.isDragging&&(this.isDragging=!1,this.slider.classList.remove("dragging"),this.emit("dragend",this.getCurrentValue()))}},{key:"startDragTouch",value:function(e){e.preventDefault(),this.isDragging=!0,this.maxOffset=this.track.offsetWidth;var t=e.touches[0];this.startX=t.clientX,this.startLeft=this.slider.offsetLeft,this.slider.classList.add("dragging"),this.emit("dragstart",this.getCurrentValue())}},{key:"onDragTouch",value:function(e){if(this.isDragging){e.preventDefault();var t=e.touches[0].clientX-this.startX,r=this.startLeft+t;r=Math.max(0,Math.min(this.maxOffset,r)),this.slider.style.left=r+"px",this.emit("drag",this.getCurrentValue())}}},{key:"getCurrentValue",value:function(){return this.slider.offsetLeft/this.maxOffset}},{key:"setValue",value:function(e){var t=(e=Math.max(0,Math.min(1,e)))*this.maxOffset;this.slider.style.left=t+"px"}},{key:"on",value:function(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}},{key:"emit",value:function(e,t){this.events[e]&&this.events[e].forEach(function(e){return e(t)})}}])}(),Kd=function(){function e(){c(this,e)}return h(e,null,[{key:"getList",value:function(e){var t=e&&e.container||e&&e.videoElm&&e.videoElm.parentElement;return t?t.querySelector(".ylc-video-player-rate-list"):null}},{key:"changeRate",value:function(t,r){t.videoElm.playbackRate=Number(r);var n=e.getList(t);if(n){n.querySelectorAll("li.ylc-video-player-rate-item").forEach(function(e){e.classList.remove("active")});var i=n.querySelector('li[data-value="'.concat(r,'"]'));i&&i.classList.add("active")}}},{key:"showRatePannel",value:function(t){var r=e.getList(t);r&&(r.style.display="block")}},{key:"hideRatePannel",value:function(t){var r=e.getList(t);r&&(r.style.display="none")}}])}(),Hd=function(){function e(){c(this,e)}return h(e,null,[{key:"getRoot",value:function(e){return e.container||e.videoElm&&e.videoElm.parentElement}},{key:"getPanel",value:function(t){var r=e.getRoot(t);return r?r.querySelector(".ylc-video-player-line-panel"):null}},{key:"changeLineUI",value:function(t,r){var n=e.getRoot(t);if(n){var i=n.querySelector(".ylc-video-player-line-list"),a=n.querySelector(".ylc-video-player-line-label");if(i){i.querySelectorAll("li.ylc-video-player-line-item").forEach(function(e){e.classList.remove("active")});var s=i.querySelector('li[data-value="'.concat(r,'"]'));s&&s.classList.add("active"),a&&(a.textContent=2===Number(r)?"线路2":"线路1")}}}},{key:"showLinePannel",value:function(t){var r=e.getPanel(t);r&&(r.style.display="block")}},{key:"hideLinePannel",value:function(t){var r=e.getPanel(t);r&&(r.style.display="none")}}])}(),Vd=function(){function e(t){c(this,e),this.player=t,this.progressLineBg=null,this.rateButton=null,this._lineHideTimer=null}return h(e,[{key:"collectRefs",value:function(){var e=this.player,t=function(t){return e.container.querySelector(t)};e.playButton=t(".ylc-video-player-play-button"),e.pauseButton=t(".ylc-video-player-pause-button"),e.timeElm=t(".ylc-video-player-current-time"),e.totalTimeElm=t(".ylc-video-player-total-time"),this.progressWrap=t(".ylc-video-player-progerss"),this.progressLineBg=t(".ylc-video-player-progress-line-bg"),e.progressLine=t(".ylc-video-player-progress-line"),e.progressLineDot=t(".ylc-video-player-progress-line-dot"),e.progressHoverTime=t(".ylc-video-player-progress-hover-time"),e.fullScreenButton=t(".ylc-video-player-full-screen-button"),e.exitFullScreenButton=t(".ylc-video-player-exit-full-screen-button"),e.volumeButton=t(".ylc-video-player-volume-button"),e.muteButton=t(".ylc-video-player-mute-button"),this.rateButton=t(".ylc-video-player-rate-button"),Gd.sync(e,!e.videoElm.muted)}},{key:"bind",value:function(){var e=this,t=this.player;if(t.playButton){t.playButton.addEventListener("click",function(){Ld.click("VideoPlayer日志-点击了内部播放按钮"),t.play()}),t.pauseButton.addEventListener("click",function(){Ld.click("VideoPlayer日志-点击了内部暂停按钮"),t.pause()});var r=function(e,r){var n=t.videoElm&&t.videoElm.duration;if(n&&Number.isFinite(n)){var i=(e.clientX-r.left)/r.width;Number.isFinite(i)&&t.seek(Math.max(0,Math.min(1,i))*n)}};t.progressLine.addEventListener("click",function(t){Ld.click("VideoPlayer日志-点击了内部进度条快进"),r(t,e.progressLineBg.getBoundingClientRect())}),this.progressLineBg.addEventListener("click",function(e){Ld.click("VideoPlayer日志-点击了内部进度条背景快进"),r(e,e.target.getBoundingClientRect())});this.progressWrap&&(this.progressWrap.addEventListener("mousemove",function(r){var n=t.videoElm&&t.videoElm.duration,i=t.progressHoverTime,a=e.progressLineBg;if(i&&a)if(!n||!Number.isFinite(n)||n<=0)i.classList.remove("is-show");else{var s=a.getBoundingClientRect();if(s.width){var o=Math.max(0,Math.min(1,(r.clientX-s.left)/s.width));i.textContent=Nd.dealTime(o*n),i.classList.add("is-show");var l=i.offsetWidth/2,u=Math.max(l,Math.min(s.width-l,o*s.width));i.style.left="".concat(u,"px")}}}),this.progressWrap.addEventListener("mouseleave",function(){t.progressHoverTime&&t.progressHoverTime.classList.remove("is-show")})),t.progressSlider=new jd(t.progressLineDot,this.progressLineBg),t.progressSlider.on("drag",function(e){var r=t.videoElm&&t.videoElm.duration;Ud.updateLine(t,e),Number.isFinite(r)&&Nd.updateCurrentTime(t,e*r),Ld.operate("VideoPlayer日志-正在拖拽内部进度条快进")}),t.progressSlider.on("dragend",function(e){var r=t.videoElm&&t.videoElm.duration;Ld.operate("VideoPlayer日志-结束拖拽内部进度条快进",{value:e,duration:r}),r&&Number.isFinite(r)&&t.seek(e*r)}),t.fullScreenButton.addEventListener("click",function(){Ld.click("VideoPlayer日志-点击了内部全屏按钮"),t.requestFullscreen(),t.events.emit("fullscreenchange",!0)}),t.exitFullScreenButton.addEventListener("click",function(){Ld.click("VideoPlayer日志-点击了内部退出全屏按钮"),t.exitFullscreen(),t.events.emit("fullscreenchange",!1)}),t.volumeButton.addEventListener("click",function(){Ld.click("VideoPlayer日志-点击了静音按钮"),Gd.changeVolume(t,!1),t.events.emit("volumechange",!1)}),t.muteButton.addEventListener("click",function(){Ld.click("VideoPlayer日志-点击了开启音量按钮"),Gd.changeVolume(t,!0),t.events.emit("volumechange",!0)}),this.rateButton.addEventListener("mouseenter",function(){t.events.emit("ratePannelChange",!0),Kd.showRatePannel(t)}),this.rateButton.addEventListener("mouseleave",function(){t.events.emit("ratePannelChange",!1),Kd.hideRatePannel(t)});var n=this.rateButton.querySelector(".ylc-video-player-rate-list");n&&n.querySelectorAll("li.ylc-video-player-rate-item").forEach(function(e){e.addEventListener("click",function(){Kd.changeRate(t,e.getAttribute("data-value")||1)})})}}},{key:"_bindLineButton",value:function(){var e=this,t=this.player,r=t.lineButton;if(r){var n=function(){e._lineHideTimer&&(clearTimeout(e._lineHideTimer),e._lineHideTimer=null)};r.addEventListener("mouseenter",function(){n(),t.events.emit("linePannelChange",!0),Hd.showLinePannel(t)}),r.addEventListener("mouseleave",function(){n(),e._lineHideTimer=setTimeout(function(){t.events.emit("linePannelChange",!1),Hd.hideLinePannel(t)},320)}),r.addEventListener("click",function(e){if(!(e.target&&e.target.closest&&e.target.closest(".ylc-video-player-line-item"))){e.stopPropagation(),n();var i=r.querySelector(".ylc-video-player-line-panel");if(i){var a="none"===i.style.display||!i.style.display;t.events.emit("linePannelChange",a),a?Hd.showLinePannel(t):Hd.hideLinePannel(t)}}});var i=r.querySelector(".ylc-video-player-line-list");i&&i.querySelectorAll("li.ylc-video-player-line-item").forEach(function(e){e.addEventListener("pointerdown",function(){var r=o(S().m(function r(n){var i;return S().w(function(r){for(;;)switch(r.p=r.n){case 0:return n.preventDefault(),n.stopPropagation(),i=Number(e.getAttribute("data-value"))||1,Hd.hideLinePannel(t),r.p=1,r.n=2,t.switchLine(i);case 2:r.v&&Hd.changeLineUI(t,i),r.n=4;break;case 3:r.p=3,r.v;case 4:return r.a(2)}},r,null,[[1,3]])}));return function(e){return r.apply(this,arguments)}}())})}}}],[{key:"mount",value:function(t){if(!(t&&t.options&&t.options.controls&&t.container))return null;var r=new e(t);return r.collectRefs(),r.bind(),r}}])}(),qd="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Wd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Yd(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}function zd(){return wd?Id:(wd=1,Id=TypeError)}var Xd,Qd,$d,Jd,Zd,eh,th,rh,nh,ih,ah,sh,oh,lh,uh,ch,dh,hh,fh,vh,gh,ph,yh,mh,Eh,kh,Sh,Th,bh,Ah,Lh,Rh,Ih,wh,_h,Ph,Dh,Ch,Oh,xh,Mh,Fh,Nh,Uh,Bh,Gh,jh,Kh,Hh,Vh,qh,Wh,Yh,zh,Xh,Qh,$h,Jh,Zh,ef,tf,rf,nf,af,sf,of,lf,uf,cf,df,hf,ff,vf,gf,pf,yf,mf,Ef,kf,Sf,Tf,bf,Af,Lf,Rf,If,wf,_f,Pf=Yd(Object.freeze({__proto__:null,default:{}}));function Df(){if(Qd)return Xd;Qd=1;var e="function"==typeof Map&&Map.prototype,t=Object.getOwnPropertyDescriptor&&e?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,r=e&&t&&"function"==typeof t.get?t.get:null,n=e&&Map.prototype.forEach,i="function"==typeof Set&&Set.prototype,a=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,s=i&&a&&"function"==typeof a.get?a.get:null,o=i&&Set.prototype.forEach,l="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,u="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,c="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,d=Boolean.prototype.valueOf,h=Object.prototype.toString,f=Function.prototype.toString,v=String.prototype.match,g=String.prototype.slice,p=String.prototype.replace,y=String.prototype.toUpperCase,m=String.prototype.toLowerCase,E=RegExp.prototype.test,k=Array.prototype.concat,S=Array.prototype.join,T=Array.prototype.slice,b=Math.floor,A="function"==typeof BigInt?BigInt.prototype.valueOf:null,L=Object.getOwnPropertySymbols,R="function"==typeof Symbol&&"symbol"===_(Symbol.iterator)?Symbol.prototype.toString:null,I="function"==typeof Symbol&&"object"===_(Symbol.iterator),w="function"==typeof Symbol&&Symbol.toStringTag&&(_(Symbol.toStringTag)===I||"symbol")?Symbol.toStringTag:null,P=Object.prototype.propertyIsEnumerable,D=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function C(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||E.call(/e/,t))return t;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var n=e<0?-b(-e):b(e);if(n!==e){var i=String(n),a=g.call(t,i.length+1);return p.call(i,r,"$&_")+"."+p.call(p.call(a,/([0-9]{3})/g,"$&_"),/_$/,"")}}return p.call(t,r,"$&_")}var O=Pf,x=O.custom,M=H(x)?x:null,F={__proto__:null,double:'"',single:"'"},N={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function U(e,t,r){var n=r.quoteStyle||t,i=F[n];return i+e+i}function B(e){return p.call(String(e),/"/g,"&quot;")}function G(e){return!w||!("object"===_(e)&&(w in e||void 0!==e[w]))}function j(e){return"[object Array]"===W(e)&&G(e)}function K(e){return"[object RegExp]"===W(e)&&G(e)}function H(e){if(I)return e&&"object"===_(e)&&e instanceof Symbol;if("symbol"===_(e))return!0;if(!e||"object"!==_(e)||!R)return!1;try{return R.call(e),!0}catch(t){}return!1}Xd=function e(t,i,a,h){var y=i||{};if(q(y,"quoteStyle")&&!q(F,y.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(q(y,"maxStringLength")&&("number"==typeof y.maxStringLength?y.maxStringLength<0&&y.maxStringLength!==1/0:null!==y.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var E=!q(y,"customInspect")||y.customInspect;if("boolean"!=typeof E&&"symbol"!==E)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(q(y,"indent")&&null!==y.indent&&"\t"!==y.indent&&!(parseInt(y.indent,10)===y.indent&&y.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(q(y,"numericSeparator")&&"boolean"!=typeof y.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var b=y.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return z(t,y);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var L=String(t);return b?C(t,L):L}if("bigint"==typeof t){var x=String(t)+"n";return b?C(t,x):x}var N=void 0===y.depth?5:y.depth;if(void 0===a&&(a=0),a>=N&&N>0&&"object"===_(t))return j(t)?"[Array]":"[Object]";var V=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=S.call(Array(e.indent+1)," ")}return{base:r,prev:S.call(Array(t+1),r)}}(y,a);if(void 0===h)h=[];else if(Y(h,t)>=0)return"[Circular]";function X(t,r,n){if(r&&(h=T.call(h)).push(r),n){var i={depth:y.depth};return q(y,"quoteStyle")&&(i.quoteStyle=y.quoteStyle),e(t,i,a+1,h)}return e(t,y,a+1,h)}if("function"==typeof t&&!K(t)){var te=function(e){if(e.name)return e.name;var t=v.call(f.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),re=ee(t,X);return"[Function"+(te?": "+te:" (anonymous)")+"]"+(re.length>0?" { "+S.call(re,", ")+" }":"")}if(H(t)){var ne=I?p.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):R.call(t);return"object"!==_(t)||I?ne:Q(ne)}if(function(e){if(!e||"object"!==_(e))return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var ie="<"+m.call(String(t.nodeName)),ae=t.attributes||[],se=0;se<ae.length;se++)ie+=" "+ae[se].name+"="+U(B(ae[se].value),"double",y);return ie+=">",t.childNodes&&t.childNodes.length&&(ie+="..."),ie+="</"+m.call(String(t.nodeName))+">"}if(j(t)){if(0===t.length)return"[]";var oe=ee(t,X);return V&&!function(e){for(var t=0;t<e.length;t++)if(Y(e[t],"\n")>=0)return!1;return!0}(oe)?"["+Z(oe,V)+"]":"[ "+S.call(oe,", ")+" ]"}if(function(e){return"[object Error]"===W(e)&&G(e)}(t)){var le=ee(t,X);return"cause"in Error.prototype||!("cause"in t)||P.call(t,"cause")?0===le.length?"["+String(t)+"]":"{ ["+String(t)+"] "+S.call(le,", ")+" }":"{ ["+String(t)+"] "+S.call(k.call("[cause]: "+X(t.cause),le),", ")+" }"}if("object"===_(t)&&E){if(M&&"function"==typeof t[M]&&O)return O(t,{depth:N-a});if("symbol"!==E&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!r||!e||"object"!==_(e))return!1;try{r.call(e);try{s.call(e)}catch(ie){return!0}return e instanceof Map}catch(t){}return!1}(t)){var ue=[];return n&&n.call(t,function(e,r){ue.push(X(r,t,!0)+" => "+X(e,t))}),J("Map",r.call(t),ue,V)}if(function(e){if(!s||!e||"object"!==_(e))return!1;try{s.call(e);try{r.call(e)}catch(t){return!0}return e instanceof Set}catch(n){}return!1}(t)){var ce=[];return o&&o.call(t,function(e){ce.push(X(e,t))}),J("Set",s.call(t),ce,V)}if(function(e){if(!l||!e||"object"!==_(e))return!1;try{l.call(e,l);try{u.call(e,u)}catch(ie){return!0}return e instanceof WeakMap}catch(t){}return!1}(t))return $("WeakMap");if(function(e){if(!u||!e||"object"!==_(e))return!1;try{u.call(e,u);try{l.call(e,l)}catch(ie){return!0}return e instanceof WeakSet}catch(t){}return!1}(t))return $("WeakSet");if(function(e){if(!c||!e||"object"!==_(e))return!1;try{return c.call(e),!0}catch(t){}return!1}(t))return $("WeakRef");if(function(e){return"[object Number]"===W(e)&&G(e)}(t))return Q(X(Number(t)));if(function(e){if(!e||"object"!==_(e)||!A)return!1;try{return A.call(e),!0}catch(t){}return!1}(t))return Q(X(A.call(t)));if(function(e){return"[object Boolean]"===W(e)&&G(e)}(t))return Q(d.call(t));if(function(e){return"[object String]"===W(e)&&G(e)}(t))return Q(X(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&t===globalThis||void 0!==qd&&t===qd)return"{ [object globalThis] }";if(!function(e){return"[object Date]"===W(e)&&G(e)}(t)&&!K(t)){var de=ee(t,X),he=D?D(t)===Object.prototype:t instanceof Object||t.constructor===Object,fe=t instanceof Object?"":"null prototype",ve=!he&&w&&Object(t)===t&&w in t?g.call(W(t),8,-1):fe?"Object":"",ge=(he||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(ve||fe?"["+S.call(k.call([],ve||[],fe||[]),": ")+"] ":"");return 0===de.length?ge+"{}":V?ge+"{"+Z(de,V)+"}":ge+"{ "+S.call(de,", ")+" }"}return String(t)};var V=Object.prototype.hasOwnProperty||function(e){return e in this};function q(e,t){return V.call(e,t)}function W(e){return h.call(e)}function Y(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}function z(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return z(g.call(e,0,t.maxStringLength),t)+n}var i=N[t.quoteStyle||"single"];return i.lastIndex=0,U(p.call(p.call(e,i,"\\$1"),/[\x00-\x1f]/g,X),"single",t)}function X(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+y.call(t.toString(16))}function Q(e){return"Object("+e+")"}function $(e){return e+" { ? }"}function J(e,t,r,n){return e+" ("+t+") {"+(n?Z(r,n):S.call(r,", "))+"}"}function Z(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+S.call(e,","+r)+"\n"+t.prev}function ee(e,t){var r=j(e),n=[];if(r){n.length=e.length;for(var i=0;i<e.length;i++)n[i]=q(e,i)?t(e[i],e):""}var a,s="function"==typeof L?L(e):[];if(I){a={};for(var o=0;o<s.length;o++)a["$"+s[o]]=s[o]}for(var l in e)q(e,l)&&(r&&String(Number(l))===l&&l<e.length||I&&a["$"+l]instanceof Symbol||(E.call(/[^\w$]/,l)?n.push(t(l,e)+": "+t(e[l],e)):n.push(l+": "+t(e[l],e))));if("function"==typeof L)for(var u=0;u<s.length;u++)P.call(e,s[u])&&n.push("["+t(s[u])+"]: "+t(e[s[u]],e));return n}return Xd}function Cf(){if(Jd)return $d;Jd=1;var e=Df(),t=zd(),r=function(e,t,r){for(var n,i=e;null!=(n=i.next);i=n)if(n.key===t)return i.next=n.next,r||(n.next=e.next,e.next=n),n};return $d=function(){var n,i={assert:function(r){if(!i.has(r))throw new t("Side channel does not contain "+e(r))},delete:function(e){var t=function(e,t){if(e)return r(e,t,!0)}(n,e);return t&&n&&!n.next&&(n=void 0),!!t},get:function(e){return function(e,t){if(e){var n=r(e,t);return n&&n.value}}(n,e)},has:function(e){return function(e,t){return!!e&&!!r(e,t)}(n,e)},set:function(e,t){n||(n={next:void 0}),function(e,t,n){var i=r(e,t);i?i.value=n:e.next={key:t,next:e.next,value:n}}(n,e,t)}};return i}}function Of(){return eh?Zd:(eh=1,Zd=Object)}function xf(){return rh?th:(rh=1,th=Error)}function Mf(){return ih?nh:(ih=1,nh=EvalError)}function Ff(){return sh?ah:(sh=1,ah=RangeError)}function Nf(){return lh?oh:(lh=1,oh=ReferenceError)}function Uf(){return ch?uh:(ch=1,uh=SyntaxError)}function Bf(){return hh?dh:(hh=1,dh=URIError)}function Gf(){return vh?fh:(vh=1,fh=Math.abs)}function jf(){return ph?gh:(ph=1,gh=Math.floor)}function Kf(){return mh?yh:(mh=1,yh=Math.max)}function Hf(){return kh?Eh:(kh=1,Eh=Math.min)}function Vf(){return Th?Sh:(Th=1,Sh=Math.pow)}function qf(){return Ah?bh:(Ah=1,bh=Math.round)}function Wf(){return Rh?Lh:(Rh=1,Lh=Number.isNaN||function(e){return e!=e})}function Yf(){if(wh)return Ih;wh=1;var e=Wf();return Ih=function(t){return e(t)||0===t?t:t<0?-1:1}}function zf(){return Ph?_h:(Ph=1,_h=Object.getOwnPropertyDescriptor)}function Xf(){if(Ch)return Dh;Ch=1;var e=zf();if(e)try{e([],"length")}catch(t){e=null}return Dh=e}function Qf(){if(xh)return Oh;xh=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch(t){e=!1}return Oh=e}function $f(){if(Uh)return Nh;Uh=1;var e="undefined"!=typeof Symbol&&Symbol,t=Fh?Mh:(Fh=1,Mh=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"===_(Symbol.iterator))return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var a=Object.getOwnPropertyDescriptor(e,t);if(42!==a.value||!0!==a.enumerable)return!1}return!0});return Nh=function(){return"function"==typeof e&&("function"==typeof Symbol&&("symbol"===_(e("foo"))&&("symbol"===_(Symbol("bar"))&&t())))}}function Jf(){return Gh?Bh:(Gh=1,Bh="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function Zf(){return Kh?jh:(Kh=1,jh=Of().getPrototypeOf||null)}function ev(){if(Vh)return Hh;Vh=1;var e=Object.prototype.toString,t=Math.max,r=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var i=0;i<t.length;i+=1)r[i+e.length]=t[i];return r};return Hh=function(n){var i=this;if("function"!=typeof i||"[object Function]"!==e.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var a,s=function(e,t){for(var r=[],n=t,i=0;n<e.length;n+=1,i+=1)r[i]=e[n];return r}(arguments,1),o=t(0,i.length-s.length),l=[],u=0;u<o;u++)l[u]="$"+u;if(a=Function("binder","return function ("+function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r}(l,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof a){var e=i.apply(this,r(s,arguments));return Object(e)===e?e:this}return i.apply(n,r(s,arguments))}),i.prototype){var c=function(){};c.prototype=i.prototype,a.prototype=new c,c.prototype=null}return a},Hh}function tv(){if(Wh)return qh;Wh=1;var e=ev();return qh=Function.prototype.bind||e}function rv(){return zh?Yh:(zh=1,Yh=Function.prototype.call)}function nv(){return Qh?Xh:(Qh=1,Xh=Function.prototype.apply)}function iv(){if(ef)return Zh;ef=1;var e=tv(),t=nv(),r=rv(),n=Jh?$h:(Jh=1,$h="undefined"!=typeof Reflect&&Reflect&&Reflect.apply);return Zh=n||e.call(r,t)}function av(){if(rf)return tf;rf=1;var e=tv(),t=zd(),r=rv(),n=iv();return tf=function(i){if(i.length<1||"function"!=typeof i[0])throw new t("a function is required");return n(e,r,i)}}function sv(){if(af)return nf;af=1;var e,t=av(),r=Xf();try{e=[].__proto__===Array.prototype}catch(s){if(!s||"object"!==_(s)||!("code"in s)||"ERR_PROTO_ACCESS"!==s.code)throw s}var n=!!e&&r&&r(Object.prototype,"__proto__"),i=Object,a=i.getPrototypeOf;return nf=n&&"function"==typeof n.get?t([n.get]):"function"==typeof a&&function(e){return a(null==e?e:i(e))}}function ov(){if(of)return sf;of=1;var e=Jf(),t=Zf(),r=sv();return sf=e?function(t){return e(t)}:t?function(e){if(!e||"object"!==_(e)&&"function"!=typeof e)throw new TypeError("getProto: not an object");return t(e)}:r?function(e){return r(e)}:null}function lv(){if(uf)return lf;uf=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=tv();return lf=r.call(e,t)}function uv(){if(df)return cf;var e;df=1;var t=Of(),r=xf(),n=Mf(),i=Ff(),a=Nf(),s=Uf(),o=zd(),l=Bf(),u=Gf(),c=jf(),d=Kf(),h=Hf(),f=Vf(),v=qf(),g=Yf(),p=Function,y=function(e){try{return p('"use strict"; return ('+e+").constructor;")()}catch(t){}},m=Xf(),E=Qf(),k=function(){throw new o},S=m?function(){try{return k}catch(e){try{return m(arguments,"callee").get}catch(t){return k}}}():k,T=$f()(),b=ov(),A=Zf(),L=Jf(),R=nv(),I=rv(),w={},P="undefined"!=typeof Uint8Array&&b?b(Uint8Array):e,D={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?e:ArrayBuffer,"%ArrayIteratorPrototype%":T&&b?b([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":w,"%AsyncGenerator%":w,"%AsyncGeneratorFunction%":w,"%AsyncIteratorPrototype%":w,"%Atomics%":"undefined"==typeof Atomics?e:Atomics,"%BigInt%":"undefined"==typeof BigInt?e:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?e:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":"undefined"==typeof Float16Array?e:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?e:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?e:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?e:FinalizationRegistry,"%Function%":p,"%GeneratorFunction%":w,"%Int8Array%":"undefined"==typeof Int8Array?e:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?e:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":T&&b?b(b([][Symbol.iterator]())):e,"%JSON%":"object"===("undefined"==typeof JSON?"undefined":_(JSON))?JSON:e,"%Map%":"undefined"==typeof Map?e:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&T&&b?b((new Map)[Symbol.iterator]()):e,"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":m,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?e:Promise,"%Proxy%":"undefined"==typeof Proxy?e:Proxy,"%RangeError%":i,"%ReferenceError%":a,"%Reflect%":"undefined"==typeof Reflect?e:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?e:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&T&&b?b((new Set)[Symbol.iterator]()):e,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":T&&b?b(""[Symbol.iterator]()):e,"%Symbol%":T?Symbol:e,"%SyntaxError%":s,"%ThrowTypeError%":S,"%TypedArray%":P,"%TypeError%":o,"%Uint8Array%":"undefined"==typeof Uint8Array?e:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?e:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?e:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?e:Uint32Array,"%URIError%":l,"%WeakMap%":"undefined"==typeof WeakMap?e:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?e:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?e:WeakSet,"%Function.prototype.call%":I,"%Function.prototype.apply%":R,"%Object.defineProperty%":E,"%Object.getPrototypeOf%":A,"%Math.abs%":u,"%Math.floor%":c,"%Math.max%":d,"%Math.min%":h,"%Math.pow%":f,"%Math.round%":v,"%Math.sign%":g,"%Reflect.getPrototypeOf%":L};if(b)try{null.error}catch(q){var C=b(b(q));D["%Error.prototype%"]=C}var O=function e(t){var r;if("%AsyncFunction%"===t)r=y("async function () {}");else if("%GeneratorFunction%"===t)r=y("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=y("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&b&&(r=b(i.prototype))}return D[t]=r,r},x={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},M=tv(),F=lv(),N=M.call(I,Array.prototype.concat),U=M.call(R,Array.prototype.splice),B=M.call(I,String.prototype.replace),G=M.call(I,String.prototype.slice),j=M.call(I,RegExp.prototype.exec),K=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,H=/\\(\\)?/g,V=function(e,t){var r,n=e;if(F(x,n)&&(n="%"+(r=x[n])[0]+"%"),F(D,n)){var i=D[n];if(i===w&&(i=O(n)),void 0===i&&!t)throw new o("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new s("intrinsic "+e+" does not exist!")};return cf=function(e,t){if("string"!=typeof e||0===e.length)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new o('"allowMissing" argument must be a boolean');if(null===j(/^%?[^%]*%?$/,e))throw new s("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=G(e,0,1),r=G(e,-1);if("%"===t&&"%"!==r)throw new s("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new s("invalid intrinsic syntax, expected opening `%`");var n=[];return B(e,K,function(e,t,r,i){n[n.length]=r?B(i,H,"$1"):t||e}),n}(e),n=r.length>0?r[0]:"",i=V("%"+n+"%",t),a=i.name,l=i.value,u=!1,c=i.alias;c&&(n=c[0],U(r,N([0,1],c)));for(var d=1,h=!0;d<r.length;d+=1){var f=r[d],v=G(f,0,1),g=G(f,-1);if(('"'===v||"'"===v||"`"===v||'"'===g||"'"===g||"`"===g)&&v!==g)throw new s("property names with quotes must have matching quotes");if("constructor"!==f&&h||(u=!0),F(D,a="%"+(n+="."+f)+"%"))l=D[a];else if(null!=l){if(!(f in l)){if(!t)throw new o("base intrinsic for "+e+" exists, but the property is not available.");return}if(m&&d+1>=r.length){var p=m(l,f);l=(h=!!p)&&"get"in p&&!("originalValue"in p.get)?p.get:l[f]}else h=F(l,f),l=l[f];h&&!u&&(D[a]=l)}}return l},cf}function cv(){if(ff)return hf;ff=1;var e=uv(),t=av(),r=t([e("%String.prototype.indexOf%")]);return hf=function(n,i){var a=e(n,!!i);return"function"==typeof a&&r(n,".prototype.")>-1?t([a]):a}}function dv(){if(gf)return vf;gf=1;var e=uv(),t=cv(),r=Df(),n=zd(),i=e("%Map%",!0),a=t("Map.prototype.get",!0),s=t("Map.prototype.set",!0),o=t("Map.prototype.has",!0),l=t("Map.prototype.delete",!0),u=t("Map.prototype.size",!0);return vf=!!i&&function(){var e,t={assert:function(e){if(!t.has(e))throw new n("Side channel does not contain "+r(e))},delete:function(t){if(e){var r=l(e,t);return 0===u(e)&&(e=void 0),r}return!1},get:function(t){if(e)return a(e,t)},has:function(t){return!!e&&o(e,t)},set:function(t,r){e||(e=new i),s(e,t,r)}};return t}}function hv(){if(Ef)return mf;Ef=1;var e=zd(),t=Df(),r=Cf(),n=dv(),i=function(){if(yf)return pf;yf=1;var e=uv(),t=cv(),r=Df(),n=dv(),i=zd(),a=e("%WeakMap%",!0),s=t("WeakMap.prototype.get",!0),o=t("WeakMap.prototype.set",!0),l=t("WeakMap.prototype.has",!0),u=t("WeakMap.prototype.delete",!0);return pf=a?function(){var e,t,c={assert:function(e){if(!c.has(e))throw new i("Side channel does not contain "+r(e))},delete:function(r){if(a&&r&&("object"===_(r)||"function"==typeof r)){if(e)return u(e,r)}else if(n&&t)return t.delete(r);return!1},get:function(r){return a&&r&&("object"===_(r)||"function"==typeof r)&&e?s(e,r):t&&t.get(r)},has:function(r){return a&&r&&("object"===_(r)||"function"==typeof r)&&e?l(e,r):!!t&&t.has(r)},set:function(r,i){a&&r&&("object"===_(r)||"function"==typeof r)?(e||(e=new a),o(e,r,i)):n&&(t||(t=n()),t.set(r,i))}};return c}:n}(),a=i||n||r;return mf=function(){var r,n={assert:function(r){if(!n.has(r)){var i=r&&Object(r)===r?"the given object key":t(r);throw new e("Side channel does not contain "+i)}},delete:function(e){return!!r&&r.delete(e)},get:function(e){return r&&r.get(e)},has:function(e){return!!r&&r.has(e)},set:function(e,t){r||(r=a()),r.set(e,t)}};return n}}function fv(){if(Sf)return kf;Sf=1;var e=String.prototype.replace,t=/%20/g,r="RFC3986";return kf={default:r,formatters:{RFC1738:function(r){return e.call(r,t,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:r}}function vv(){if(bf)return Tf;bf=1;var e=fv(),t=hv(),r=Qf(),n=Object.prototype.hasOwnProperty,i=Array.isArray,a=t(),s=function(e,t){return a.set(e,t),e},o=function(e){return a.has(e)},l=function(e){return a.get(e)},u=function(e,t){a.set(e,t)},c=function(){for(var e=[],t=0;t<256;++t)e[e.length]="%"+((t<16?"0":"")+t.toString(16)).toUpperCase();return e}(),d=function(e,t){for(var r=t&&t.plainObjects?{__proto__:null}:{},n=0;n<e.length;++n)void 0!==e[n]&&(r[n]=e[n]);return r},h=function(e,t,n){"__proto__"===t&&r?r(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n},f=1024;return Tf={arrayToObject:d,assign:function(e,t){return Object.keys(t).reduce(function(e,r){return h(e,r,t[r]),e},e)},combine:function(e,t,r,n,a){if(o(e)){if(a)throw new RangeError("Array limit exceeded. Only "+r+" element"+(1===r?"":"s")+" allowed in an array.");for(var c=i(t)?t:[t],h=l(e),f=0;f<c.length;++f)e[h+=1]=c[f];return u(e,h),e}var v=[].concat(e,t);if(v.length>r){if(a)throw new RangeError("Array limit exceeded. Only "+r+" element"+(1===r?"":"s")+" allowed in an array.");return s(d(v,{plainObjects:n}),v.length-1)}return v},compact:function(e){for(var r=[{obj:{o:e},prop:"o"}],n=t(),a=0;a<r.length;++a)for(var s=r[a],o=s.obj[s.prop],l=Object.keys(o),u=0;u<l.length;++u){var c=l[u],d=o[c];"object"!==_(d)||null===d||n.has(d)||(r[r.length]={obj:o,prop:c},n.set(d,!0))}return function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(i(r)){for(var n=[],a=0;a<r.length;++a)void 0!==r[a]&&(n[n.length]=r[a]);t.obj[t.prop]=n}}}(r),e},decode:function(e,t,r){var n=e.replace(/\+/g," ");if("iso-8859-1"===r)return n.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(n)}catch(i){return n}},encode:function(t,r,n,i,a){if(0===t.length)return t;var s=t;if("symbol"===_(t)?s=Symbol.prototype.toString.call(t):"string"!=typeof t&&(s=String(t)),"iso-8859-1"===n)return escape(s).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});for(var o="",l=0;l<s.length;l+=f){var u=s.length>=f?s.slice(l,l+f):s;if(l+f<s.length){var d=u.charCodeAt(u.length-1);d>=55296&&d<=56319&&(u=u.slice(0,-1),l-=1)}for(var h=[],v=0;v<u.length;++v){var g=u.charCodeAt(v);45===g||46===g||95===g||126===g||g>=48&&g<=57||g>=65&&g<=90||g>=97&&g<=122||a===e.RFC1738&&(40===g||41===g)?h[h.length]=u.charAt(v):g<128?h[h.length]=c[g]:g<2048?h[h.length]=c[192|g>>6]+c[128|63&g]:g<55296||g>=57344?h[h.length]=c[224|g>>12]+c[128|g>>6&63]+c[128|63&g]:(v+=1,g=65536+((1023&g)<<10|1023&u.charCodeAt(v)),h[h.length]=c[240|g>>18]+c[128|g>>12&63]+c[128|g>>6&63]+c[128|63&g])}o+=h.join("")}return o},isBuffer:function(e){return!(!e||"object"!==_(e))&&!(!e.constructor||"function"!=typeof e.constructor.isBuffer||!e.constructor.isBuffer(e))},isOverflow:o,isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},markOverflow:s,maybeMap:function(e,t){if(i(e)){for(var r=[],n=0;n<e.length;n+=1)r[r.length]=t(e[n]);return r}return t(e)},merge:function e(t,r,a){if(!r)return t;if("object"!==_(r)&&"function"!=typeof r){if(i(t)){var c=t.length;if(a&&"number"==typeof a.arrayLimit&&c>=a.arrayLimit){if(a.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+a.arrayLimit+" element"+(1===a.arrayLimit?"":"s")+" allowed in an array.");return s(d(t.concat(r),a),c)}t[c]=r}else{if(!t||"object"!==_(t))return[t,r];if(o(t)){var f=l(t)+1;t[f]=r,u(t,f)}else{if(a&&a.strictMerge)return[t,r];(a&&(a.plainObjects||a.allowPrototypes)||!n.call(Object.prototype,r))&&(t[r]=!0)}}return t}if(!t||"object"!==_(t)){if(o(r)){for(var v=Object.keys(r),g=a&&a.plainObjects?{__proto__:null,0:t}:{0:t},p=0;p<v.length;p++){g[parseInt(v[p],10)+1]=r[v[p]]}return s(g,l(r)+1)}var y=[t].concat(r);if(a&&"number"==typeof a.arrayLimit&&y.length>a.arrayLimit){if(a.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+a.arrayLimit+" element"+(1===a.arrayLimit?"":"s")+" allowed in an array.");return s(d(y,a),y.length-1)}return y}var m=t;if(i(t)&&!i(r)&&(m=d(t,a)),i(t)&&i(r)){if(r.forEach(function(r,i){if(n.call(t,i)){var s=t[i];s&&"object"===_(s)&&r&&"object"===_(r)?t[i]=e(s,r,a):t[t.length]=r}else t[i]=r}),a&&"number"==typeof a.arrayLimit&&t.length>a.arrayLimit){if(a.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+a.arrayLimit+" element"+(1===a.arrayLimit?"":"s")+" allowed in an array.");return s(d(t,a),t.length-1)}return t}return Object.keys(r).reduce(function(t,i){var c=r[i];if(n.call(t,i)?h(t,i,e(t[i],c,a)):h(t,i,c),o(r)&&!o(t)&&s(t,l(r)),o(t)){var d=parseInt(i,10);String(d)===i&&d>=0&&d>l(t)&&u(t,d)}return t},m)}},Tf}function gv(){if(Lf)return Af;Lf=1;var e=hv(),t=vv(),r=fv(),n=Object.prototype.hasOwnProperty,i={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},a=Array.isArray,s=Array.prototype.push,o=function(e,t){s.apply(e,a(t)?t:[t])},l=Date.prototype.toISOString,u=r.default,c={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",depth:1/0,encode:!0,encodeDotInKeys:!1,encoder:t.encode,encodeValuesOnly:!1,filter:void 0,format:u,formatter:r.formatters[u],indices:!1,serializeDate:function(e){return l.call(e)},skipNulls:!1,strictNullHandling:!1},d={},h=function r(n,i,s,l,u,h,f,v,g,p,y,m,E,k,S,T,b,A,L,R){var I=n;if(R>L)throw new RangeError("Input depth exceeded depth option of "+L);for(var w,P=A,D=0,C=!1;void 0!==(P=P.get(d))&&!C;){var O=P.get(n);if(D+=1,void 0!==O){if(O===D)throw new RangeError("Cyclic object value");C=!0}void 0===P.get(d)&&(D=0)}if((I="function"==typeof p?p(i,I):I)instanceof Date?I=E(I):"comma"===s&&a(I)&&(I=t.maybeMap(I,function(e){return e instanceof Date?E(e):e})),null===I){if(h)return S(g&&!T?g(i,c.encoder,b,"key",k):i);I=""}if("string"==typeof(w=I)||"number"==typeof w||"boolean"==typeof w||"symbol"===_(w)||"bigint"==typeof w||t.isBuffer(I))return g?[S(T?i:g(i,c.encoder,b,"key",k))+"="+S(g(I,c.encoder,b,"value",k))]:[S(i)+"="+S(String(I))];var x,M=[];if(void 0===I)return M;if("comma"===s&&a(I))T&&g&&(I=t.maybeMap(I,function(e){return null==e?e:g(e)})),x=[{value:I.length>0?I.join(",")||null:void 0}];else if(a(p))x=p;else{var F=Object.keys(I);x=y?F.sort(y):F}var N=v?String(i).replace(/\./g,"%2E"):String(i),U=l&&a(I)&&1===I.length?N+"[]":N;if(u&&a(I)&&0===I.length&&0===Object.keys(I).length)return U+"[]";for(var B=0;B<x.length;++B){var G=x[B],j="object"===_(G)&&G&&void 0!==G.value?G.value:I[G];if(!f||null!==j){var K=m&&v?String(G).replace(/\./g,"%2E"):String(G),H=a(I)?"function"==typeof s?s(U,K):U:U+(m?"."+K:"["+K+"]");A.set(n,D);var V=e();V.set(d,A),o(M,r(j,H,s,l,u,h,f,v,"comma"===s&&T&&a(I)?null:g,p,y,m,E,k,S,T,b,V,L,R+1))}}return M};return Af=function(t,s){var l,u=t,d=function(e){if(!e)return c;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||c.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var s=r.default;if(void 0!==e.format){if(!n.call(r.formatters,e.format))throw new TypeError("Unknown format option provided.");s=e.format}var o,l=r.formatters[s],u=c.filter;if(("function"==typeof e.filter||a(e.filter))&&(u=e.filter),o=e.arrayFormat in i?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":c.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var d=void 0===e.allowDots?!0===e.encodeDotInKeys||c.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:c.addQueryPrefix,allowDots:d,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:c.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:c.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?c.delimiter:e.delimiter,depth:"number"==typeof e.depth?e.depth:c.depth,encode:"boolean"==typeof e.encode?e.encode:c.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:c.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:c.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:c.encodeValuesOnly,filter:u,format:s,formatter:l,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:c.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:c.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:c.strictNullHandling}}(s);"function"==typeof d.filter?u=(0,d.filter)("",u):a(d.filter)&&(l=d.filter);var f=[];if("object"!==_(u)||null===u)return"";var v=i[d.arrayFormat],g="comma"===v&&d.commaRoundTrip;l||(l=Object.keys(u)),d.sort&&l.sort(d.sort);for(var p=e(),y=0;y<l.length;++y){var m=l[y];if(null!=m){var E=u[m];if(!d.skipNulls||null!==E){var k=d.encodeDotInKeys?String(m).replace(/\./g,"%2E"):String(m);o(f,h(E,k,v,g,d.allowEmptyArrays,d.strictNullHandling,d.skipNulls,d.encodeDotInKeys,d.encode?d.encoder:null,d.filter,d.sort,d.allowDots,d.serializeDate,d.format,d.formatter,d.encodeValuesOnly,d.charset,p,d.depth,0))}}}var S=f.join(d.delimiter),T=!0===d.addQueryPrefix?"?":"";return d.charsetSentinel&&("iso-8859-1"===d.charset?T+="utf8=%26%2310003%3B"+d.delimiter:T+="utf8=%E2%9C%93"+d.delimiter),S.length>0?T+S:""},Af}function pv(){if(If)return Rf;If=1;var e=vv(),t=Object.prototype.hasOwnProperty,r=Array.isArray,n={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:e.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictMerge:!0,strictNullHandling:!1,throwOnLimitExceeded:!1},i=function(e){return e.replace(/&#(\d+);/g,function(e,t){return String.fromCharCode(parseInt(t,10))})},a=function(e,t,r){if(e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1){if(t.throwOnLimitExceeded)for(var n=0,i=e.indexOf(",");i>-1;){if((n+=1)>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");i=e.indexOf(",",i+1)}return e.split(",")}if(t.throwOnLimitExceeded&&r>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return e},s=function(r,n,i,s){if(r){var o=function(e,r){var n=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e;if(r.depth<=0){if(!r.plainObjects&&t.call(Object.prototype,n)&&!r.allowPrototypes)return;return[n]}var i=[],a=n.indexOf("["),s=a>=0?n.slice(0,a):n;if(s){if(!r.plainObjects&&t.call(Object.prototype,s)&&!r.allowPrototypes)return;i[i.length]=s}for(var o=n.length,l=a,u=0;l>=0&&u<r.depth;){for(var c=1,d=l+1,h=-1;d<o&&h<0;){var f=n.charCodeAt(d);91===f?c+=1:93===f&&0==(c-=1)&&(h=d),d+=1}if(h<0)return i[i.length]="["+n.slice(l)+"]",i;var v=n.slice(l,h+1),g=v.slice(1,-1);if(!r.plainObjects&&t.call(Object.prototype,g)&&!r.allowPrototypes)return;i[i.length]=v,u+=1,l=n.indexOf("[",h+1)}if(l>=0){if(!0===r.strictDepth)throw new RangeError("Input depth exceeded depth option of "+r.depth+" and strictDepth is true");i[i.length]="["+n.slice(l)+"]"}return i}(r,i);if(o)return function(t,r,n,i){var s=0;if(t.length>0&&"[]"===t[t.length-1]){var o=t.slice(0,-1).join("");s=Array.isArray(r)&&r[o]?r[o].length:0}for(var l=i?r:a(r,n,s),u=t.length-1;u>=0;--u){var c,d=t[u];if("[]"===d&&n.parseArrays)c=e.isOverflow(l)?l:n.allowEmptyArrays&&(""===l||n.strictNullHandling&&null===l)?[]:e.combine([],l,n.arrayLimit,n.plainObjects,n.throwOnLimitExceeded);else{c=n.plainObjects?{__proto__:null}:{};var h="["===d.charAt(0)&&"]"===d.charAt(d.length-1)?d.slice(1,-1):d,f=n.decodeDotInKeys?h.replace(/%2E/g,"."):h,v=parseInt(f,10),g=!isNaN(v)&&d!==f&&String(v)===f&&v>=0&&n.parseArrays;if(n.parseArrays||""!==f)if(g&&v<n.arrayLimit)(c=[])[v]=l;else{if(g&&n.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+n.arrayLimit+" element"+(1===n.arrayLimit?"":"s")+" allowed in an array.");g?(c[v]=l,e.markOverflow(c,v)):"__proto__"!==f&&(c[f]=l)}else c={0:l}}l=c}return l}(o,n,i,s)}};return Rf=function(o,l){var u=function(t){if(!t)return n;if(void 0!==t.allowEmptyArrays&&"boolean"!=typeof t.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==t.decodeDotInKeys&&"boolean"!=typeof t.decodeDotInKeys)throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==t.decoder&&void 0!==t.decoder&&"function"!=typeof t.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==t.charset&&"utf-8"!==t.charset&&"iso-8859-1"!==t.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(void 0!==t.throwOnLimitExceeded&&"boolean"!=typeof t.throwOnLimitExceeded)throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var r=void 0===t.charset?n.charset:t.charset,i=void 0===t.duplicates?n.duplicates:t.duplicates;if("combine"!==i&&"first"!==i&&"last"!==i)throw new TypeError("The duplicates option must be either combine, first, or last");return{allowDots:void 0===t.allowDots?!0===t.decodeDotInKeys||n.allowDots:!!t.allowDots,allowEmptyArrays:"boolean"==typeof t.allowEmptyArrays?!!t.allowEmptyArrays:n.allowEmptyArrays,allowPrototypes:"boolean"==typeof t.allowPrototypes?t.allowPrototypes:n.allowPrototypes,allowSparse:"boolean"==typeof t.allowSparse?t.allowSparse:n.allowSparse,arrayLimit:"number"==typeof t.arrayLimit?t.arrayLimit:n.arrayLimit,charset:r,charsetSentinel:"boolean"==typeof t.charsetSentinel?t.charsetSentinel:n.charsetSentinel,comma:"boolean"==typeof t.comma?t.comma:n.comma,decodeDotInKeys:"boolean"==typeof t.decodeDotInKeys?t.decodeDotInKeys:n.decodeDotInKeys,decoder:"function"==typeof t.decoder?t.decoder:n.decoder,delimiter:"string"==typeof t.delimiter||e.isRegExp(t.delimiter)?t.delimiter:n.delimiter,depth:"number"==typeof t.depth||!1===t.depth?+t.depth:n.depth,duplicates:i,ignoreQueryPrefix:!0===t.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof t.interpretNumericEntities?t.interpretNumericEntities:n.interpretNumericEntities,parameterLimit:"number"==typeof t.parameterLimit?t.parameterLimit:n.parameterLimit,parseArrays:!1!==t.parseArrays,plainObjects:"boolean"==typeof t.plainObjects?t.plainObjects:n.plainObjects,strictDepth:"boolean"==typeof t.strictDepth?!!t.strictDepth:n.strictDepth,strictMerge:"boolean"==typeof t.strictMerge?!!t.strictMerge:n.strictMerge,strictNullHandling:"boolean"==typeof t.strictNullHandling?t.strictNullHandling:n.strictNullHandling,throwOnLimitExceeded:"boolean"==typeof t.throwOnLimitExceeded&&t.throwOnLimitExceeded}}(l);if(""===o||null==o)return u.plainObjects?{__proto__:null}:{};for(var c="string"==typeof o?function(s,o){var l={__proto__:null},u=o.ignoreQueryPrefix?s.replace(/^\?/,""):s;u=u.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var c=o.parameterLimit===1/0?void 0:o.parameterLimit,d=u.split(o.delimiter,o.throwOnLimitExceeded&&void 0!==c?c+1:c);if(o.throwOnLimitExceeded&&void 0!==c&&d.length>c)throw new RangeError("Parameter limit exceeded. Only "+c+" parameter"+(1===c?"":"s")+" allowed.");var h,f=-1,v=o.charset;if(o.charsetSentinel)for(h=0;h<d.length;++h)0===d[h].indexOf("utf8=")&&("utf8=%E2%9C%93"===d[h]?v="utf-8":"utf8=%26%2310003%3B"===d[h]&&(v="iso-8859-1"),f=h,h=d.length);for(h=0;h<d.length;++h)if(h!==f){var g,p,y=d[h],m=y.indexOf("]="),E=-1===m?y.indexOf("="):m+1;if(-1===E?(g=o.decoder(y,n.decoder,v,"key"),p=o.strictNullHandling?null:""):null!==(g=o.decoder(y.slice(0,E),n.decoder,v,"key"))&&(p=e.maybeMap(a(y.slice(E+1),o,r(l[g])?l[g].length:0),function(e){return o.decoder(e,n.decoder,v,"value")})),p&&o.interpretNumericEntities&&"iso-8859-1"===v&&(p=i(String(p))),y.indexOf("[]=")>-1&&(p=r(p)?[p]:p),o.comma&&r(p)&&p.length>o.arrayLimit&&(p=e.combine([],p,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded)),null!==g){var k=t.call(l,g);k&&("combine"===o.duplicates||y.indexOf("[]=")>-1)?l[g]=e.combine(l[g],p,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded):k&&"last"!==o.duplicates||(l[g]=p)}}return l}(o,u):o,d=u.plainObjects?{__proto__:null}:{},h=Object.keys(c),f=0;f<h.length;++f){var v=h[f],g=s(v,c[v],u,"string"==typeof o);d=e.merge(d,g,u)}return!0===u.allowSparse?d:e.compact(d)}}function yv(){if(_f)return wf;_f=1;var e=gv(),t=pv();return wf={formats:fv(),parse:t,stringify:e}}var mv=Wd(yv());function Ev(e,t){return function(){return e.apply(t,arguments)}}var kv,Sv=Object.prototype.toString,Tv=Object.getPrototypeOf,bv=Symbol.iterator,Av=Symbol.toStringTag,Lv=function(){var e=Object.prototype.hasOwnProperty;return function(t,r){return e.call(t,r)}}(),Rv=function(e){return"string"==typeof e&&("__proto__"===e||"constructor"===e||"prototype"===e)},Iv=function(e,t,r){return e===Object.prototype||!r&&null===t},wv=function(e,t){for(var r=e,n=[];null!=r;){if(-1!==n.indexOf(r))return!1;n.push(r);var i=Tv(r);if(Iv(r,i,r===e))return!1;if(Lv(r,t))return!0;r=i}return!1},_v=(kv=Object.create(null),function(e){var t=Sv.call(e);return kv[t]||(kv[t]=t.slice(8,-1).toLowerCase())}),Pv=function(e){return e=e.toLowerCase(),function(t){return _v(t)===e}},Dv=function(e){return function(t){return _(t)===e}},Cv=Array.isArray,Ov=Dv("undefined");function xv(e){return null!==e&&!Ov(e)&&null!==e.constructor&&!Ov(e.constructor)&&Nv(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Mv=Pv("ArrayBuffer");var Fv=Dv("string"),Nv=Dv("function"),Uv=Dv("number"),Bv=function(e){return null!==e&&"object"===_(e)},Gv=function(e){if(!Bv(e))return!1;var t=Tv(e);return!(null!==t&&t!==Object.prototype&&null!==Tv(t)||wv(e,Av)||wv(e,bv))},jv=Pv("Date"),Kv=Pv("File"),Hv=Pv("Blob"),Vv=Pv("FileList"),qv=Pv("Set");var Wv="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Yv=void 0!==Wv.FormData?Wv.FormData:void 0,zv=Pv("URLSearchParams"),Xv=L(["ReadableStream","Request","Response","Headers"].map(Pv),4),Qv=Xv[0],$v=Xv[1],Jv=Xv[2],Zv=Xv[3];function eg(e,t){var r,n,i=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).allOwnKeys,a=void 0!==i&&i;if(null!=e)if("object"!==_(e)&&(e=[e]),Cv(e))for(r=0,n=e.length;r<n;r++)t.call(null,e[r],r,e);else{if(xv(e))return;var s,o=a?Object.getOwnPropertyNames(e):Object.keys(e),l=o.length;for(r=0;r<l;r++)s=o[r],t.call(null,e[s],s,e)}}function tg(e,t){if(xv(e))return null;t=t.toLowerCase();for(var r,n=Object.keys(e),i=n.length;i-- >0;)if(t===(r=n[i]).toLowerCase())return r;return null}var rg="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,ng=function(e){return!Ov(e)&&e!==rg};var ig,ag=(ig="undefined"!=typeof Uint8Array&&Tv(Uint8Array),function(e){return ig&&e instanceof ig}),sg=Pv("HTMLFormElement"),og=Object.prototype.propertyIsEnumerable,lg=Pv("RegExp"),ug=function(e,t){var r=Object.getOwnPropertyDescriptors(e),n={};eg(r,function(r,i){var a;!1!==(a=t(r,i,e))&&(n[i]=a||r)}),Object.defineProperties(e,n)};var cg,dg,hg,fg,vg=Pv("AsyncFunction"),gg=(cg="function"==typeof setImmediate,dg=Nv(rg.postMessage),cg?setImmediate:dg?(hg="axios@".concat(Math.random()),fg=[],rg.addEventListener("message",function(e){var t=e.source,r=e.data;t===rg&&r===hg&&fg.length&&fg.shift()()},!1),function(e){fg.push(e),rg.postMessage(hg,"*")}):function(e){return setTimeout(e)}),pg="undefined"!=typeof queueMicrotask?queueMicrotask.bind(rg):"undefined"!=typeof process&&process.nextTick||gg,yg=function(e){return null!=e&&Nv(e[bv])},mg={isArray:Cv,isArrayBuffer:Mv,isBuffer:xv,isFormData:function(e){if(!e)return!1;if(Yv&&e instanceof Yv)return!0;var t=Tv(e);if(!t||t===Object.prototype)return!1;if(!Nv(e.append))return!1;var r=_v(e);return"formdata"===r||"object"===r&&Nv(e.toString)&&"[object FormData]"===e.toString()},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Mv(e.buffer)},isString:Fv,isNumber:Uv,isBoolean:function(e){return!0===e||!1===e},isObject:Bv,isPlainObject:Gv,isEmptyObject:function(e){if(!Bv(e)||xv(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:Qv,isRequest:$v,isResponse:Jv,isHeaders:Zv,isUndefined:Ov,isDate:jv,isFile:Kv,isReactNativeBlob:function(e){return!(!e||void 0===e.uri)},isReactNative:function(e){return e&&void 0!==e.getParts},isBlob:Hv,isRegExp:lg,isFunction:Nv,isStream:function(e){return Bv(e)&&Nv(e.pipe)},isURLSearchParams:zv,isTypedArray:ag,isFileList:Vv,forEach:eg,merge:function e(){for(var t=ng(this)&&this||{},r=t.caseless,n=t.skipUndefined,i={},a=function(t,a){if("__proto__"!==a&&"constructor"!==a&&"prototype"!==a){var s=r&&"string"==typeof a&&tg(i,a)||a,o=Lv(i,s)?i[s]:void 0;Gv(o)&&Gv(t)?i[s]=e(o,t):Gv(t)?i[s]=e({},t):Cv(t)?i[s]=t.slice():n&&Ov(t)||(i[s]=t)}},s=0,o=arguments.length;s<o;s++){var l=s<0||arguments.length<=s?void 0:arguments[s];if(l&&!xv(l)&&(eg(l,a),"object"===_(l)&&!Cv(l)))for(var u=Object.getOwnPropertySymbols(l),c=0;c<u.length;c++){var d=u[c];og.call(l,d)&&a(l[d],d)}}return i},extend:function(e,t,r){return eg(t,function(t,n){r&&Nv(t)?Object.defineProperty(e,n,{__proto__:null,value:Ev(t,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{__proto__:null,value:t,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:(arguments.length>3&&void 0!==arguments[3]?arguments[3]:{}).allOwnKeys}),e},trim:function(e){return e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,r,n){e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:function(e,t,r,n){var i,a,s,o={};if(t=t||{},null==e)return t;do{for(a=(i=Object.getOwnPropertyNames(e)).length;a-- >0;)s=i[a],n&&!n(s,e,t)||o[s]||(t[s]=e[s],o[s]=!0);e=!1!==r&&Tv(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:_v,kindOfTest:Pv,endsWith:function(e,t,r){e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;var n=e.indexOf(t,r);return-1!==n&&n===r},toArray:function(e){if(!e)return null;if(Cv(e))return e;var t=e.length;if(!Uv(t))return null;for(var r=new Array(t);t-- >0;)r[t]=e[t];return r},forEachEntry:function(e,t){for(var r,n=(e&&e[bv]).call(e);(r=n.next())&&!r.done;){var i=r.value;t.call(e,i[0],i[1])}},matchAll:function(e,t){for(var r,n=[];null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:sg,hasOwnProperty:Lv,hasOwnProp:Lv,hasOwnInPrototypeChain:wv,getSafeProp:function(e,t){return null!=e&&wv(e,t)?e[t]:void 0},toSafeFlatObject:function(e){if(null==e||"object"!==_(e)&&"function"!=typeof e)return e;var t=Tv(e);if(null===t&&function(e){if(!Object.isExtensible(e))return!1;var t=Object.getOwnPropertyNames(e);return Object.getOwnPropertySymbols&&t.push.apply(t,I(Object.getOwnPropertySymbols(e))),t.every(function(t){if(Rv(t))return!1;var r=Object.getOwnPropertyDescriptor(e,t);return!!r&&r.configurable&&!0===r.writable})}(e))return e;for(var r=Object.create(null),n=Object.create(null),i=[],a=e;null!=a&&-1===i.indexOf(a);){i.push(a);var s=a===e?t:Tv(a);if(Iv(a,s,a===e))break;var o=Object.getOwnPropertyNames(a);Object.getOwnPropertySymbols&&o.push.apply(o,I(Object.getOwnPropertySymbols(a)));var l,u=f(o);try{for(u.s();!(l=u.n()).done;){var c=l.value;Rv(c)||(Lv(n,c)||(r[c]=e[c],n[c]=!0))}}catch(Ry){u.e(Ry)}finally{u.f()}a=s}return r},reduceDescriptors:ug,freezeMethods:function(e){ug(e,function(t,r){if(Nv(e)&&["arguments","caller","callee"].includes(r))return!1;var n=e[r];Nv(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=function(){throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:function(e,t){var r={},n=function(e){e.forEach(function(e){r[e]=!0})};return Cv(e)?n(e):n(String(e).split(t)),r},toCamelCase:function(e){return e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r})},noop:function(){},toFiniteNumber:function(e,t){return null!=e&&Number.isFinite(e=+e)?e:t},findKey:tg,global:rg,isContextDefined:ng,isSpecCompliantForm:function(e){return!!(e&&Nv(e.append)&&"FormData"===e[Av]&&e[bv])},toJSONObject:function(e){var t=new WeakSet,r=function(e){if(Bv(e)){if(t.has(e))return;if(xv(e))return e;if(!("toJSON"in e)){var n;if(t.add(e),qv(e)){n=[];var i,a=f(e);try{for(a.s();!(i=a.n()).done;){var s=i.value,o=r(s);!Ov(o)&&n.push(o)}}catch(Ry){a.e(Ry)}finally{a.f()}}else n=Cv(e)?[]:{},eg(e,function(e,t){var i=r(e);!Ov(i)&&(n[t]=i)});return t.delete(e),n}}return e};return r(e)},isAsyncFn:vg,isThenable:function(e){return e&&(Bv(e)||Nv(e))&&Nv(e.then)&&Nv(e.catch)},setImmediate:gg,asap:pg,isIterable:yg,isSafeIterable:function(e){return null!=e&&wv(e,bv)&&yg(e)}},Eg=mg.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);var kg=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),Sg=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function Tg(e,t){return mg.isArray(e)?e.map(function(e){return Tg(e,t)}):function(e){for(var t=0,r=e.length;t<r;){var n=e.charCodeAt(t);if(9!==n&&32!==n)break;t+=1}for(;r>t;){var i=e.charCodeAt(r-1);if(9!==i&&32!==i)break;r-=1}return 0===t&&r===e.length?e:e.slice(t,r)}(String(e).replace(t,""))}function bg(e){var t=Object.create(null);return mg.forEach(e.toJSON(),function(e,r){t[r]=function(e){return Tg(e,Sg)}(e)}),t}var Ag=Symbol("internals");function Lg(e){return e&&String(e).trim().toLowerCase()}function Rg(e){return!1===e||null==e?e:mg.isArray(e)?e.map(Rg):function(e){return Tg(e,kg)}(String(e))}var Ig=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function wg(e){for(var t=0,r=e.length;t<r;){var n=e.charCodeAt(t);if(9!==n&&32!==n)break;t+=1}for(;r>t;){var i=e.charCodeAt(r-1);if(9!==i&&32!==i)break;r-=1}return 0===t&&r===e.length?e:e.slice(t,r)}function _g(e,t,r,n,i){return mg.isFunction(n)?n.call(this,t,r):(i&&(t=r),mg.isString(t)?mg.isString(n)?-1!==t.indexOf(n):mg.isRegExp(n)?n.test(t):void 0:void 0)}var Pg=function(){return h(function e(t){c(this,e),t&&this.set(t)},[{key:"set",value:function(e,t,r){var n=this;function i(e,t,r){var i=Lg(t);if(i){var a=mg.findKey(n,i);(!a||void 0===n[a]||!0===r||void 0===r&&!1!==n[a])&&(n[a||t]=Rg(e))}}var a=function(e,t){return mg.forEach(e,function(e,r){return i(e,r,t)})};if(mg.isPlainObject(e)||e instanceof this.constructor)a(e,t);else if(mg.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))a(function(e){var t,r,n,i={};return e&&e.split("\n").forEach(function(e){n=e.indexOf(":"),t=e.substring(0,n).trim().toLowerCase(),r=e.substring(n+1).trim();var a=mg.hasOwnProp(i,t);!t||a&&mg.hasOwnProp(Eg,t)||("set-cookie"===t?a?i[t].push(r):i[t]=[r]:i[t]=a?i[t]+", "+r:r)}),i}(e),t);else if(mg.isObject(e)&&mg.isSafeIterable(e)){var s,o,l,u=Object.create(null),c=f(e);try{for(c.s();!(l=c.n()).done;){var d=l.value;if(!mg.isArray(d))throw new TypeError("Object iterator must return a key-value pair");o=d[0],mg.hasOwnProp(u,o)?(s=u[o],u[o]=mg.isArray(s)?[].concat(I(s),[d[1]]):[s,d[1]]):u[o]=d[1]}}catch(Ry){c.e(Ry)}finally{c.f()}a(u,t)}else null!=e&&i(t,e,r);return this}},{key:"get",value:function(e,t){if(e=Lg(e)){var r=mg.findKey(this,e);if(r){var n=this[r];if(!t)return n;if(!0===t)return function(e){for(var t,r=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;t=n.exec(e);)r[t[1]]=t[2];return r}(n);if(mg.isFunction(t))return t.call(this,n,r);if(mg.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}},{key:"has",value:function(e,t){if(e=Lg(e)){var r=mg.findKey(this,e);return!(!r||void 0===this[r]||t&&!_g(0,this[r],r,t))}return!1}},{key:"delete",value:function(e,t){var r=this,n=!1;function i(e){if(e=Lg(e)){var i=mg.findKey(r,e);!i||t&&!_g(0,r[i],i,t)||(delete r[i],n=!0)}}return mg.isArray(e)?e.forEach(i):i(e),n}},{key:"clear",value:function(e){for(var t=Object.keys(this),r=t.length,n=!1;r--;){var i=t[r];e&&!_g(0,this[i],i,e,!0)||(delete this[i],n=!0)}return n}},{key:"normalize",value:function(e){var t=this,r={};return mg.forEach(this,function(n,i){var a=mg.findKey(r,i);if(a)return t[a]=Rg(n),void delete t[i];var s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r})}(i):String(i).trim();s!==i&&delete t[i],t[s]=Rg(n),r[s]=!0}),this}},{key:"concat",value:function(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(e=this.constructor).concat.apply(e,[this].concat(r))}},{key:"toJSON",value:function(e){var t=Object.create(null);return mg.forEach(this,function(r,n){null!=r&&!1!==r&&(t[n]=e&&mg.isArray(r)?r.join(", "):r)}),t}},{key:Symbol.iterator,value:function(){return Object.entries(this.toJSON())[Symbol.iterator]()}},{key:"toString",value:function(){return Object.entries(this.toJSON()).map(function(e){var t=L(e,2);return t[0]+": "+t[1]}).join("\n")}},{key:"getSetCookie",value:function(){var e=this.get("set-cookie");return mg.isArray(e)?e:null==e||!1===e?[]:[e]}},{key:Symbol.toStringTag,get:function(){return"AxiosHeaders"}}],[{key:"from",value:function(e){return e instanceof this?e:new this(e)}},{key:"parseParameters",value:function(e){return function(e){var t=Object.create(null),r=String(e),n=0,i=!1,a=!1;function s(e){var i=wg(r.slice(n,e)),a=i.indexOf("=");if(!(a<1)){var s=wg(i.slice(0,a));if(Ig.test(s)){var o=s.toLowerCase();if("__proto__"!==o&&"constructor"!==o&&"prototype"!==o){var l=wg(i.slice(a+1));t[o]=function(e){var t=e.length-1;if(t<1||34!==e.charCodeAt(0)||34!==e.charCodeAt(t))return e;for(var r="",n=1;n<t;n++){var i=e.charCodeAt(n);if(34===i)return e;if(92===i&&(n+=1)>=t)return e;r+=e[n]}return r}(l)}}}}for(var o=0;o<r.length;o++){var l=r.charCodeAt(o);i?a?a=!1:92===l?a=!0:34===l&&(i=!1):34===l?i=!0:44!==l&&59!==l||(s(o),n=o+1)}return s(r.length),t}(e)}},{key:"concat",value:function(e){for(var t=new this(e),r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return n.forEach(function(e){return t.set(e)}),t}},{key:"accessor",value:function(e){var t=(this[Ag]=this[Ag]={accessors:{}}).accessors,r=this.prototype;function n(e){var n=Lg(e);t[n]||(!function(e,t){var r=mg.toCamelCase(" "+t);["get","set","has"].forEach(function(n){Object.defineProperty(e,n+r,{__proto__:null,value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})})}(r,e),t[n]=!0)}return mg.isArray(e)?e.forEach(n):n(e),this}}])}();Pg.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),mg.reduceDescriptors(Pg.prototype,function(e,t){var r=e.value,n=t[0].toUpperCase()+t.slice(1);return{get:function(){return r},set:function(e){this[n]=e}}}),mg.freezeMethods(Pg);var Dg="[REDACTED ****]";function Cg(e,t){var r=new Set(t.map(function(e){return String(e).toLowerCase()})),n=[],i=function(e){if(null===e||"object"!==_(e))return e;if(mg.isBuffer(e))return e;if(-1===n.indexOf(e)){var t;if(e instanceof Pg&&(e=e.toJSON()),n.push(e),mg.isArray(e))t=[],e.forEach(function(e,r){var n=i(e);mg.isUndefined(n)||(t[r]=n)});else{if(!mg.isPlainObject(e)&&function(e){if(mg.hasOwnProp(e,"toJSON"))return!0;for(var t=Object.getPrototypeOf(e);t&&t!==Object.prototype;){if(mg.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}(e))return n.pop(),e;t=Object.create(null);for(var a=0,s=Object.entries(e);a<s.length;a++){var o=L(s[a],2),l=o[0],u=o[1],c=r.has(l.toLowerCase())?Dg:i(u);mg.isUndefined(c)||(t[l]=c)}}return n.pop(),t}};return i(e)}function Og(e){try{return String(e)}catch(Ry){return""}}var xg=function(e){function t(e,r,n,i,a){var s;return c(this,t),s=u(this,t,[e]),Object.defineProperty(s,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),s.name="AxiosError",s.isAxiosError=!0,r&&(s.code=r),n&&(s.config=n),i&&(s.request=i),a&&(s.response=a,s.status=a.status),s}return y(t,e),h(t,[{key:"toJSON",value:function(){var e=this.config,t=e&&mg.hasOwnProp(e,"redact")?e.redact:void 0,r=mg.isArray(t)&&t.length>0?Cg(e,t):mg.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:r,code:this.code,status:this.status}}}],[{key:"from",value:function(e,r,n,i,a,s){var o=e.message;!o&&mg.isArray(e.errors)&&e.errors.length&&(o=function(e){return e.errors.map(function(e){try{return e&&e.message?Og(e.message):Og(e)}catch(Ry){return""}}).filter(Boolean).join("; ")||e.name||"AggregateError"}(e));var l=new t(o,r||e.code,n,i,a);return Object.defineProperty(l,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),l.name=e.name,null!=e.status&&null==l.status&&(l.status=e.status),s&&Object.assign(l,s),l}}])}(O(Error));xg.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",xg.ERR_BAD_OPTION="ERR_BAD_OPTION",xg.ECONNABORTED="ECONNABORTED",xg.ETIMEDOUT="ETIMEDOUT",xg.ECONNREFUSED="ECONNREFUSED",xg.ERR_NETWORK="ERR_NETWORK",xg.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",xg.ERR_DEPRECATED="ERR_DEPRECATED",xg.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",xg.ERR_BAD_REQUEST="ERR_BAD_REQUEST",xg.ERR_CANCELED="ERR_CANCELED",xg.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",xg.ERR_INVALID_URL="ERR_INVALID_URL",xg.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";function Mg(e){return mg.isPlainObject(e)||mg.isArray(e)}function Fg(e){return mg.endsWith(e,"[]")?e.slice(0,-2):e}function Ng(e,t,r){return e?e.concat(t).map(function(e,t){return e=Fg(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}var Ug=mg.toFlatObject(mg,{},null,function(e){return/^is[A-Z]/.test(e)});function Bg(e,t,r){if(!mg.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;var n=function(e,t){var n=mg.getSafeProp(r,e);return mg.isUndefined(n)?t:n},i=n("metaTokens",!0),a=n("visitor")||v,s=n("dots",!1),o=n("indexes",!1),l=n("Blob")||"undefined"!=typeof Blob&&Blob,u=n("maxDepth",100),c=l&&mg.isSpecCompliantForm(t),d=[];if(!mg.isFunction(a))throw new TypeError("visitor must be a function");function h(e){if(null===e)return"";if(mg.isDate(e))return e.toISOString();if(mg.isBoolean(e))return e.toString();if(!c&&mg.isBlob(e))throw new xg("Blob is not supported. Use a Buffer instead.");if(mg.isArrayBuffer(e)||mg.isTypedArray(e)){if(c&&"function"==typeof l)return new l([e]);throw new xg("Blob is not supported. Use a Buffer instead.",xg.ERR_NOT_SUPPORT)}return e}function f(e){if(e>u)throw new xg("Object is too deeply nested ("+e+" levels). Max depth: "+u,xg.ERR_FORM_DATA_DEPTH_EXCEEDED)}function v(e,r,n){var a=e;if(mg.isReactNative(t)&&mg.isReactNativeBlob(e))return t.append(Ng(n,r,s),h(e)),!1;if(e&&!n&&"object"===_(e))if(mg.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=function(e,t){if(u===1/0)return JSON.stringify(e);var r=[];return JSON.stringify(e,function(e,n){if(!mg.isObject(n))return n;for(;r.length&&r[r.length-1]!==this;)r.pop();return r.push(n),f(t+r.length-1),n})}(e,1);else if(mg.isArray(e)&&function(e){return mg.isArray(e)&&!e.some(Mg)}(e)||(mg.isFileList(e)||mg.endsWith(r,"[]"))&&(a=mg.toArray(e)))return r=Fg(r),a.forEach(function(e,n){!mg.isUndefined(e)&&null!==e&&t.append(!0===o?Ng([r],n,s):null===o?r:r+"[]",h(e))}),!1;return!!Mg(e)||(t.append(Ng(n,r,s),h(e)),!1)}var g=Object.assign(Ug,{defaultVisitor:v,convertValue:h,isVisitable:Mg});if(!mg.isObject(e))throw new TypeError("data must be an object");return function e(r,n){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(!mg.isUndefined(r)){if(f(i),-1!==d.indexOf(r))throw new Error("Circular reference detected in "+n.join("."));d.push(r),mg.forEach(r,function(r,s){!0===(!(mg.isUndefined(r)||null===r)&&a.call(t,r,mg.isString(s)?s.trim():s,n,g))&&e(r,n?n.concat(s):[s],i+1)}),d.pop()}}(e),t}function Gg(e){var t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(e){return t[e]})}function jg(e,t){this._pairs=[],e&&Bg(e,this,t)}var Kg=jg.prototype;function Hg(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Vg(e,t,r){if(!t)return e;e=e||"";var n,i=mg.isFunction(r)?{serialize:r}:r,a=mg.getSafeProp(i,"encode")||Hg,s=mg.getSafeProp(i,"serialize");if(n=s?s(t,i):mg.isURLSearchParams(t)?t.toString():new jg(t,i).toString(a)){var o=e.indexOf("#");-1!==o&&(e=e.slice(0,o)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e}Kg.append=function(e,t){this._pairs.push([e,t])},Kg.toString=function(e){var t=this,r=e?function(r){return e.call(t,r,Gg)}:Gg;return this._pairs.map(function(e){return r(e[0])+"="+r(e[1])},"").join("&")};var qg=Symbol("internals");function Wg(e){return e?e.length:0}function Yg(e){if(e)for(;e.length&&null===e[e.length-1];)e.pop()}function zg(e,t){var r=e.handlers,n=Wg(r);r!==t.handlersRef?(t.handlersRef=r,t.handlerEntries.clear()):n!==t.handlersLength&&(n?t.handlerEntries.forEach(function(e,n){r[e.index]!==e.handler&&t.handlerEntries.delete(n)}):t.handlerEntries.clear()),t.handlersLength=n}var Xg=function(){return h(function e(){c(this,e),this.handlers=[],this[qg]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}},[{key:"use",value:function(e,t,r){var n={fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null},i=this[qg];null==this.handlers&&(this.handlers=[]),zg(this,i);var a=i.nextId++;return this.handlers.push(n),i.handlerEntries.set(a,{handler:n,index:this.handlers.length-1}),i.handlersLength=this.handlers.length,a}},{key:"eject",value:function(e){var t=this[qg];zg(this,t);var r=t.handlerEntries.get(e);if(r){if(t.handlerEntries.delete(e),this.handlers[r.index]!==r.handler)return;this.handlers[r.index]=null,t.iterationDepth||(Yg(this.handlers),t.handlersLength=this.handlers.length)}}},{key:"clear",value:function(){this.handlers&&(this.handlers=[],zg(this,this[qg]))}},{key:"forEach",value:function(e){var t=this[qg];zg(this,t),t.iterationDepth++;try{mg.forEach(this.handlers,function(t){null!==t&&e(t)})}finally{--t.iterationDepth||(zg(this,t),Yg(this.handlers),t.handlersLength=Wg(this.handlers))}}}])}(),Qg={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},$g={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:jg,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Jg="undefined"!=typeof window&&"undefined"!=typeof document,Zg="object"===("undefined"==typeof navigator?"undefined":_(navigator))&&navigator||void 0,ep=Jg&&(!Zg||["ReactNative","NativeScript","NS"].indexOf(Zg.product)<0),tp="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,rp=Jg&&window.location.href||"http://localhost",np=k(k({},Object.freeze({__proto__:null,hasBrowserEnv:Jg,hasStandardBrowserEnv:ep,hasStandardBrowserWebWorkerEnv:tp,navigator:Zg,origin:rp})),$g);function ip(e){if(e>100)throw new xg("FormData field is too deeply nested ("+e+" levels). Max depth: 100",xg.ERR_FORM_DATA_DEPTH_EXCEEDED)}function ap(e){function t(e,r,n,i){ip(i);var a=e[i++];if("__proto__"===a)return!0;var s=Number.isFinite(+a),o=i>=e.length;return a=!a&&mg.isArray(n)?n.length:a,o?(mg.hasOwnProp(n,a)?n[a]=mg.isArray(n[a])?n[a].concat(r):[n[a],r]:n[a]=r,!s):(mg.hasOwnProp(n,a)&&mg.isObject(n[a])||(n[a]=[]),t(e,r,n[a],i)&&mg.isArray(n[a])&&(n[a]=function(e){var t,r,n={},i=Object.keys(e),a=i.length;for(t=0;t<a;t++)n[r=i[t]]=e[r];return n}(n[a])),!s)}if(mg.isFormData(e)&&mg.isFunction(e.entries)){var r={};return mg.forEachEntry(e,function(e,n){t(function(e){for(var t,r=[],n=/[^.[\]]+|\[([^.[\]]*)]/g;null!==(t=n.exec(e));)ip(r.length),r.push("[]"===t[0]?"":t[1]||t[0]);return r}(e),n,r,0)}),r}return null}var sp=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),op=function(e,t){return null!=e&&mg.hasOwnProp(e,t)?e[t]:void 0};var lp={transitional:Qg,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){var r,n=t.getContentType()||"",i=n.indexOf("application/json")>-1,a=mg.isObject(e);if(a&&mg.isHTMLForm(e)&&(e=new FormData(e)),mg.isFormData(e))return i?JSON.stringify(ap(e)):e;if(mg.isArrayBuffer(e)||mg.isBuffer(e)||mg.isStream(e)||mg.isFile(e)||mg.isBlob(e)||mg.isReadableStream(e))return e;if(mg.isArrayBufferView(e))return e.buffer;if(mg.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(a){var s=op(this,"formSerializer");if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Bg(e,new np.classes.URLSearchParams,k({visitor:function(e,t,r,n){return np.isNode&&mg.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,s).toString();if((r=mg.isFileList(e))||n.indexOf("multipart/form-data")>-1){var o=op(this,"env"),l=o&&o.FormData;return Bg(r?{"files[]":e}:e,l&&new l,s)}}return a||i?(t.setContentType("application/json",!1),function(e,t,r){if(mg.isString(e))try{return(t||JSON.parse)(e),mg.trim(e)}catch(n){if("SyntaxError"!==n.name)throw n}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=op(this,"transitional")||lp.transitional,r=t&&t.forcedJSONParsing,n=op(this,"responseType"),i="json"===n;if(mg.isResponse(e)||mg.isReadableStream(e))return e;if(e&&mg.isString(e)&&(r&&!n||i)){var a=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,op(this,"parseReviver"))}catch(s){if(a){if("SyntaxError"===s.name)throw xg.from(s,xg.ERR_BAD_RESPONSE,this,null,op(this,"response"));throw s}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:np.classes.FormData,Blob:np.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};function up(e,t){var r=this||lp,n=t||r,i=Pg.from(n.headers),a=n.data;return mg.forEach(e,function(e){a=e.call(r,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function cp(e){return!(!e||!e.__CANCEL__)}mg.forEach(sp,function(e){lp.headers[e]={}});var dp=function(e){function t(e,r,n){var i;return c(this,t),(i=u(this,t,[null==e?"canceled":e,xg.ERR_CANCELED,r,n])).name="CanceledError",i.__CANCEL__=!0,i}return y(t,e),h(t)}(xg);function hp(e,t,r){var n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new xg("Request failed with status code "+r.status,r.status>=400&&r.status<500?xg.ERR_BAD_REQUEST:xg.ERR_BAD_RESPONSE,r.config,r.request,r)):e(r)}var fp=/[\t\n\r]/g;function vp(e){if("string"!=typeof e)return e;for(var t=0;t<e.length&&e.charCodeAt(t)<=32;)t++;return e.slice(t).replace(fp,"")}function gp(e){var t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}var pp=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,n=0,i=function(e,t){e=e||10;var r,n=new Array(e),i=new Array(e),a=0,s=0;return t=void 0!==t?t:1e3,function(o){var l=Date.now(),u=i[s];r||(r=l),n[a]=o,i[a]=l;for(var c=s,d=0;c!==a;)d+=n[c++],c%=e;if((a=(a+1)%e)===s&&(s=(s+1)%e),!(l-r<t)){var h=u&&l-u;return h?Math.round(1e3*d/h):void 0}}}(50,250);return function(e,t){var r,n,i=0,a=1e3/t,s=function(t){var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();i=a,r=null,n&&(clearTimeout(n),n=null),e.apply(void 0,I(t))};return[function(){for(var e=Date.now(),t=e-i,o=arguments.length,l=new Array(o),u=0;u<o;u++)l[u]=arguments[u];t>=a?s(l,e):(r=l,n||(n=setTimeout(function(){n=null,s(r)},a-t)))},function(){return r&&s(r)},function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return s(t)}]}(function(r){if(r&&mg.isNumber(r.loaded)){var a=r.loaded,s=r.lengthComputable?r.total:void 0,o=Math.max(0,null!=s?Math.min(a,s):a),l=Math.max(0,o-n),u=i(l);n=Math.max(n,o);var c=v({loaded:o,total:s,progress:s?o/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s?(s-o)/u:void 0,event:r,lengthComputable:null!=s},t?"download":"upload",!0);e(c)}},r)},yp=function(e,t){var r=null!=e;return[function(n){return t[0]({lengthComputable:r,total:e,loaded:n})},t[1]]},mp=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mg.asap;return function(){for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return t(function(){return e.apply(void 0,n)})}},Ep=np.hasStandardBrowserEnv?function(e,t){return function(r){return r=new URL(r,np.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)}}(new URL(np.origin),np.navigator&&/(msie|trident)/i.test(np.navigator.userAgent)):function(){return!0},kp=np.hasStandardBrowserEnv?{write:function(e,t,r,n,i,a,s){if("undefined"!=typeof document){var o=["".concat(e,"=").concat(encodeURIComponent(t))];mg.isNumber(r)&&o.push("expires=".concat(new Date(r).toUTCString())),mg.isString(n)&&o.push("path=".concat(n)),mg.isString(i)&&o.push("domain=".concat(i)),!0===a&&o.push("secure"),mg.isString(s)&&o.push("SameSite=".concat(s)),document.cookie=o.join("; ")}},read:function(e){if("undefined"==typeof document)return null;for(var t=document.cookie.split(";"),r=0;r<t.length;r++){var n=t[r].replace(/^\s+/,""),i=n.indexOf("=");if(-1!==i&&n.slice(0,i)===e)try{return decodeURIComponent(n.slice(i+1))}catch(a){return n.slice(i+1)}}return null},remove:function(e){this.write(e,"",Date.now()-864e5,"/")}}:{write:function(){},read:function(){return null},remove:function(){}};var Sp=/^https?:(?!\/\/)/i;function Tp(e){var t,r=e.replace(/^(https?:\/{0,2})[^/?#]*@/i,"$1".concat(Dg,"@")),n=r.indexOf("#"),i=(-1===n?r:r.slice(0,n)).replace(/([?&][^=&#]*=)[^&#]*/g,"$1".concat(Dg));return-1===n?i:"".concat(i,"#").concat((t=r.slice(n+1))?t.replace(/(^|&)([^=&]*=)?[^&]+/g,function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return"".concat(t).concat(r).concat(Dg)}):t)}function bp(e,t){if("string"==typeof e){var r=vp(e);if(Sp.test(r))throw new xg("Invalid URL ".concat(JSON.stringify(Tp(r)),': missing "//" after protocol'),xg.ERR_INVALID_URL,t)}}function Ap(e,t,r,n){bp(t,n);var i,a=!("string"==typeof(i=t)&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(i));return e&&(a||!1===r)?(bp(e,n),function(e,t){if(!t)return e;for(var r=e.length;r>0&&47===e.charCodeAt(r-1);)r--;return e.slice(0,r)+"/"+t.replace(/^\/+/,"")}(e,t)):t}var Lp=function(e){return e instanceof Pg?k({},e):e};function Rp(e,t){e=e||{},t=t||{};var r=Object.create(null);function n(e,t,r,n){return mg.isPlainObject(e)&&mg.isPlainObject(t)?mg.merge.call({caseless:n},e,t):mg.isPlainObject(t)?mg.merge({},t):mg.isArray(t)?t.slice():t}function i(e,t,r,i){return mg.isUndefined(t)?mg.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function a(e,t){if(!mg.isUndefined(t))return n(void 0,t)}function s(e,t){return mg.isUndefined(t)?mg.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function o(r,i,a){return mg.hasOwnProp(t,a)?n(r,i):mg.hasOwnProp(e,a)?n(void 0,r):void 0}Object.defineProperty(r,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});var l,u={url:a,method:a,data:a,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutErrorMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,allowedSocketPaths:s,responseEncoding:s,validateStatus:o,headers:function(e,t,r){return i(Lp(e),Lp(t),0,!0)}};return mg.forEach((l=k(k({},e),t),Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(l).concat(Object.getOwnPropertySymbols(l).filter(function(e){return Object.getOwnPropertyDescriptor(l,e).enumerable})):Object.keys(l)),function(n){if("__proto__"!==n&&"constructor"!==n&&"prototype"!==n){var a=mg.hasOwnProp(u,n)?u[n]:i,s=a(mg.hasOwnProp(e,n)?e[n]:void 0,mg.hasOwnProp(t,n)?t[n]:void 0,n);mg.isUndefined(s)&&a!==o||(r[n]=s)}}),mg.hasOwnProp(t,"validateStatus")&&mg.isUndefined(t.validateStatus)&&!1===function(r){var n=mg.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!mg.isUndefined(n)){if(!mg.isPlainObject(n))return;if(mg.hasOwnProp(n,r))return n[r]}var i=mg.hasOwnProp(e,"transitional")?e.transitional:void 0;if(mg.isPlainObject(i)&&mg.hasOwnProp(i,r))return i[r]}("validateStatusUndefinedResolves")&&(mg.hasOwnProp(e,"validateStatus")?r.validateStatus=n(void 0,e.validateStatus):delete r.validateStatus),r}var Ip=["content-type","content-length"];function wp(e){var t=Rp({},e),r=function(e){return mg.hasOwnProp(t,e)?t[e]:void 0},n=r("data"),i=r("withXSRFToken"),a=r("xsrfHeaderName"),s=r("xsrfCookieName"),o=r("headers"),l=r("auth"),u=r("baseURL"),c=r("allowAbsoluteUrls"),d=r("url");if(t.headers=o=Pg.from(o),t.url=Vg(Ap(u,d,c,t),r("params"),r("paramsSerializer")),l){var h=mg.getSafeProp(l,"username")||"",f=mg.getSafeProp(l,"password")||"";try{o.set("Authorization","Basic "+btoa(h+":"+(f?encodeURIComponent(f).replace(/%([0-9A-F]{2})/gi,function(e,t){return String.fromCharCode(parseInt(t,16))}):"")))}catch(p){throw xg.from(p,xg.ERR_BAD_OPTION_VALUE,e)}}if(mg.isFormData(n)){var v=mg.getSafeProp(n,"getHeaders");np.hasStandardBrowserEnv||np.hasStandardBrowserWebWorkerEnv||mg.isReactNative(n)?o.setContentType(void 0):mg.isFunction(v)&&function(e,t,r){"content-only"===r?Object.entries(t||{}).forEach(function(t){var r=L(t,2),n=r[0],i=r[1];Ip.includes(n.toLowerCase())&&e.set(n,i)}):e.set(t)}(o,v.call(n),r("formDataHeaderPolicy"))}if(np.hasStandardBrowserEnv&&(mg.isFunction(i)&&(i=i(t)),!0===i||null==i&&Ep(t.url))){var g=a&&s&&kp.read(s);g&&o.set(a,g)}return t}var _p="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){var n,i,a,s,o,l,u=wp(e),c=u.data,d=Pg.from(u.headers).normalize(),h=u.responseType,f=u.onUploadProgress,v=u.onDownloadProgress;function g(){s&&s(),o&&o(),u.cancelToken&&u.cancelToken.unsubscribe(n),u.signal&&u.signal.removeEventListener("abort",n)}var p=new XMLHttpRequest;function y(n){if(p){if(!(0!==p.status||"file"===(gp(vp(u.url))||gp(np.origin))||p.responseURL&&p.responseURL.startsWith("file:")))return r(new xg("Request aborted",xg.ECONNABORTED,e,p)),g(),void(p=null);try{n?l&&l(n):o&&o()}catch(Ry){setTimeout(function(){throw Ry})}if(p){var i=Pg.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders());hp(function(e){t(e),g()},function(e){r(e),g()},{data:h&&"text"!==h&&"json"!==h?p.response:p.responseText,status:p.status,statusText:p.statusText,headers:i,config:e,request:p}),p=null}}}if(p.open(u.method.toUpperCase(),u.url,!0),p.timeout=u.timeout,"onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){p&&4===p.readyState&&(0!==p.status||p.responseURL&&p.responseURL.startsWith("file:"))&&setTimeout(y)},p.onabort=function(){p&&(r(new xg("Request aborted",xg.ECONNABORTED,e,p)),g(),p=null)},p.onerror=function(t){var n=t&&t.message?t.message:"Network Error",i=new xg(n,xg.ERR_NETWORK,e,p);i.event=t||null,r(i),g(),p=null},p.ontimeout=function(){var t=u.timeout?"timeout of "+u.timeout+"ms exceeded":"timeout exceeded",n=u.transitional||Qg;u.timeoutErrorMessage&&(t=u.timeoutErrorMessage),r(new xg(t,n.clarifyTimeoutError?xg.ETIMEDOUT:xg.ECONNABORTED,e,p)),g(),p=null},void 0===c&&d.setContentType(null),"setRequestHeader"in p&&mg.forEach(bg(d),function(e,t){p.setRequestHeader(t,e)}),mg.isUndefined(u.withCredentials)||(p.withCredentials=!!u.withCredentials),h&&"json"!==h&&(p.responseType=u.responseType),v){var m=L(pp(v,!0),3);a=m[0],o=m[1],l=m[2],p.addEventListener("progress",a)}if(f&&p.upload){var E=L(pp(f),2);i=E[0],s=E[1],p.upload.addEventListener("progress",i),p.upload.addEventListener("loadend",s)}(u.cancelToken||u.signal)&&(n=function(t){p&&(r(!t||t.type?new dp(null,e,p):t),p.abort(),g(),p=null)},u.cancelToken&&u.cancelToken.subscribe(n),u.signal&&(u.signal.aborted?n():u.signal.addEventListener("abort",n)));var k=gp(u.url);if(k&&!np.protocols.includes(k))return r(new xg("Unsupported protocol "+k+":",xg.ERR_BAD_REQUEST,e)),void g();p.send(c||null)})},Pp=function(e,t){if(e=e?e.filter(Boolean):[],t||e.length){var r=new AbortController,n=!1,i=function(e){if(!n){n=!0,s();var t=e instanceof Error?e:this.reason;r.abort(t instanceof xg?t:new dp(t instanceof Error?t.message:t))}},a=t&&setTimeout(function(){a=null,i(new xg("timeout of ".concat(t,"ms exceeded"),xg.ETIMEDOUT))},t),s=function(){e&&(a&&clearTimeout(a),a=null,e.forEach(function(e){e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(function(e){n||(e.aborted?i.call(e):e.addEventListener("abort",i,{once:!0}))});var o=r.signal;return o.unsubscribe=function(){return mg.asap(s)},o}},Dp=S().m(function e(t,r){var n,i,a;return S().w(function(e){for(;;)switch(e.n){case 0:if(n=t.byteLength,r&&!(n<r)){e.n=2;break}return e.n=1,t;case 1:return e.a(2);case 2:i=0;case 3:if(!(i<n)){e.n=5;break}return a=i+r,e.n=4,t.slice(i,a);case 4:i=a,e.n=3;break;case 5:return e.a(2)}},e)}),Cp=function(){var e=D(S().m(function e(t,r){var a,s,o,u,c,d,h;return S().w(function(e){for(;;)switch(e.p=e.n){case 0:a=!1,s=!1,e.p=1,u=i(Op(t));case 2:return e.n=3,l(u.next());case 3:if(!(a=!(c=e.v).done)){e.n=5;break}return d=c.value,e.d(b(n(i(Dp(d,r)))),4);case 4:a=!1,e.n=2;break;case 5:e.n=7;break;case 6:e.p=6,h=e.v,s=!0,o=h;case 7:if(e.p=7,e.p=8,!a||null==u.return){e.n=9;break}return e.n=9,l(u.return());case 9:if(e.p=9,!s){e.n=10;break}throw o;case 10:return e.f(9);case 11:return e.f(7);case 12:return e.a(2)}},e,null,[[8,,9,11],[1,6,7,12]])}));return function(t,r){return e.apply(this,arguments)}}(),Op=function(){var e=D(S().m(function e(t){var r,a,s,o;return S().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!t[Symbol.asyncIterator]){e.n=2;break}return e.d(b(n(i(t))),1);case 1:return e.a(2);case 2:r=t.getReader(),e.p=3;case 4:return e.n=5,l(r.read());case 5:if(a=e.v,s=a.done,o=a.value,!s){e.n=6;break}return e.a(3,8);case 6:return e.n=7,o;case 7:e.n=4;break;case 8:return e.p=8,e.n=9,l(r.cancel());case 9:return e.f(8);case 10:return e.a(2)}},e,null,[[3,,8,10]])}));return function(t){return e.apply(this,arguments)}}(),xp=function(e,t,r,n){var i,a=Cp(e,t),s=0,l=function(e){i||(i=!0,n&&n(e))};return new ReadableStream({pull:function(e){return o(S().m(function t(){var n,i,o,u,c,d;return S().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,t.n=1,a.next();case 1:if(n=t.v,i=n.done,o=n.value,!i){t.n=2;break}return l(),e.close(),t.a(2);case 2:u=o.byteLength,r&&(c=s+=u,r(c)),e.enqueue(new Uint8Array(o)),t.n=4;break;case 3:throw t.p=3,d=t.v,l(d),d;case 4:return t.a(2)}},t,null,[[0,3]])}))()},cancel:function(e){return l(e),a.return()}},{highWaterMark:2})},Mp=function(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102},Fp=function(e,t,r){return t+2<r&&Mp(e.charCodeAt(t+1))&&Mp(e.charCodeAt(t+2))},Np=function(e){return e<=57?e-48:(223&e)-55},Up=function(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||43===e||47===e||45===e||95===e},Bp=function(e){return 9===e||10===e||12===e||13===e||32===e},Gp=function(e){for(var t=e.length,r=0,n=0,i=!1,a=0;a<t;a++){var s=e.charCodeAt(a);37===s&&Fp(e,a,t)&&(s=16*Np(e.charCodeAt(a+1))+Np(e.charCodeAt(a+2)),a+=2),Bp(s)||(61!==s?!Up(s)||n>0?i=!0:r++:n++)}return i||n>2||n>0&&(r+n)%4!=0||r%4==1?function(e){var t=e.length,r=0;return t>0&&61===e.charCodeAt(t-1)&&(r++,t>1&&61===e.charCodeAt(t-2)&&r++),Math.floor(3*(t-r)/4)}(e):function(e){var t=e%4;return 3*Math.floor(e/4)+(2===t?1:3===t?2:0)}(r)};function jp(e){var t="string"==typeof e?e.indexOf("#"):-1;return function(e,t){if(!e||"string"!=typeof e)return 0;if(!e.startsWith("data:"))return 0;var r=e.indexOf(",");if(r<0)return 0;var n=e.slice(5,r),i=e.slice(r+1);if(/;base64/i.test(n))return t(i);for(var a=0,s=0,o=i.length;s<o;s++){var l=i.charCodeAt(s);if(37===l&&Fp(i,s,o))a+=1,s+=2;else if(l<128)a+=1;else if(l<2048)a+=2;else if(l>=55296&&l<=56319&&s+1<o){var u=i.charCodeAt(s+1);u>=56320&&u<=57343?(a+=4,s++):a+=3}else a+=3}return a}(-1===t?e:e.slice(0,t),Gp)}var Kp="1.20.0",Hp={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},Vp=mg.isFunction,qp=function(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,function(e,t){return String.fromCharCode(parseInt(t,16))})},Wp=function(e){if(!mg.isString(e))return e;try{return decodeURIComponent(e)}catch(t){return e}},Yp=function(e){try{for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return!!e.apply(void 0,r)}catch(i){return!1}},zp=function(e){var t=e.indexOf("://"),r=e;return-1!==t&&(r=r.slice(t+3)),r.includes("@")||r.includes(":")},Xp=function(e){var t=void 0!==mg.global&&null!==mg.global?mg.global:globalThis,r=t.ReadableStream,n=t.TextEncoder,i=e=mg.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e),a=i.fetch,s=i.Request,l=i.Response,u=a?Vp(a):"function"==typeof fetch,c=Vp(s),d=Vp(l);if(!u)return!1;var h,f=u&&Vp(r),v=u&&("function"==typeof n?(h=new n,function(e){return h.encode(e)}):function(){var e=o(S().m(function e(t){var r,n;return S().w(function(e){for(;;)switch(e.n){case 0:return r=Uint8Array,e.n=1,new s(t).arrayBuffer();case 1:return n=e.v,e.a(2,new r(n))}},e)}));return function(t){return e.apply(this,arguments)}}()),g=c&&f&&Yp(function(){var e=!1,t=new s(np.origin,{body:new r,method:"POST",get duplex(){return e=!0,"half"}}),n=t.headers.has("Content-Type");return null!=t.body&&t.body.cancel(),e&&!n}),p=d&&f&&Yp(function(){return mg.isReadableStream(new l("").body)}),y={stream:p&&function(e){return e.body}};u&&["text","arrayBuffer","blob","formData","stream"].forEach(function(e){!y[e]&&(y[e]=function(t,r){var n=t&&t[e];if(n)return n.call(t);throw new xg("Response type '".concat(e,"' is not supported"),xg.ERR_NOT_SUPPORT,r)})});var m=function(){var e=o(S().m(function e(t){var r;return S().w(function(e){for(;;)switch(e.n){case 0:if(null!=t){e.n=1;break}return e.a(2,0);case 1:if(!mg.isBlob(t)){e.n=2;break}return e.a(2,t.size);case 2:if(!mg.isSpecCompliantForm(t)){e.n=4;break}return r=new s(np.origin,{method:"POST",body:t}),e.n=3,r.arrayBuffer();case 3:case 6:return e.a(2,e.v.byteLength);case 4:if(!mg.isArrayBufferView(t)&&!mg.isArrayBuffer(t)){e.n=5;break}return e.a(2,t.byteLength);case 5:if(mg.isURLSearchParams(t)&&(t+=""),!mg.isString(t)){e.n=7;break}return e.n=6,v(t);case 7:return e.a(2)}},e)}));return function(t){return e.apply(this,arguments)}}(),E=function(){var e=o(S().m(function e(t,r){var n;return S().w(function(e){for(;;)if(0===e.n)return n=mg.toFiniteNumber(t.getContentLength()),e.a(2,null==n?m(r):n)},e)}));return function(t,r){return e.apply(this,arguments)}}();return function(){var e=o(S().m(function e(t){var r,i,o,u,d,h,v,k,T,b,A,R,I,w,_,P,D,C,O,x,M,F,N,U,B,G,j,K,H,V,q,W,Y,z,X,Q,$,J,Z,ee,te,re,ne,ie,ae,se,oe,le,ue,ce,de,he,fe,ve,ge,pe,ye,me,Ee,ke,Se,Te,be,Ae;return S().w(function(e){for(;;)switch(e.p=e.n){case 0:if(r=wp(t),i=r.url,o=r.method,u=r.data,d=r.signal,h=r.cancelToken,v=r.timeout,k=r.onDownloadProgress,T=r.onUploadProgress,b=r.responseType,A=r.headers,R=r.withCredentials,I=void 0===R?"same-origin":R,w=r.fetchOptions,_=r.maxContentLength,P=r.maxBodyLength,D=r.maxRedirects,C=mg.isNumber(_)&&_>-1,O=mg.isNumber(P)&&P>-1,x=function(e){return mg.hasOwnProp(t,e)?t[e]:void 0},M=a||fetch,b=b?(b+"").toLowerCase():"text",F=Pp([d,h&&h.toAbortSignal()],v),N=null,U=F&&F.unsubscribe&&function(){F.unsubscribe()},G=null,j=function(){return new xg("Request body larger than maxBodyLength limit",xg.ERR_BAD_REQUEST,t,N)},e.p=1,K=void 0,(H=x("auth"))&&(V=mg.getSafeProp(H,"username")||"",q=mg.getSafeProp(H,"password")||"",K={username:V,password:q}),zp(i)&&(W=new URL(i,np.origin),K||!W.username&&!W.password||(Y=Wp(W.username),z=Wp(W.password),K={username:Y,password:z}),(W.username||W.password)&&(W.username="",W.password="",i=W.href)),K&&(A.delete("authorization"),A.set("Authorization","Basic "+btoa(qp((K.username||"")+":"+(K.password||""))))),!C||"string"!=typeof i||!i.startsWith("data:")){e.n=2;break}if(!(jp(i)>_)){e.n=2;break}throw new xg("maxContentLength size of "+_+" exceeded",xg.ERR_BAD_RESPONSE,t,N);case 2:if(!O||"get"===o||"head"===o){e.n=4;break}return e.n=3,m(u);case 3:if("number"!=typeof(X=e.v)||!isFinite(X)){e.n=4;break}if(B=X,!(X>P)){e.n=4;break}throw j();case 4:if(Q=O&&(mg.isReadableStream(u)||mg.isStream(u)),$=function(e,t,r){return xp(e,65536,function(e){if(O&&e>P)throw G=j();t&&t(e)},r)},!g||"get"===o||"head"===o||!T&&!Q){e.n=8;break}if(null!=B){e.n=6;break}return e.n=5,E(A,u);case 5:be=e.v,e.n=7;break;case 6:be=B;case 7:(0!==(B=be)||Q)&&(J=new s(i,{method:"POST",body:u,duplex:"half"}),mg.isFormData(u)&&(Z=J.headers.get("content-type"))&&A.setContentType(Z),J.body&&(ee=T&&yp(B,pp(mp(T)))||[],te=L(ee,2),re=te[0],ne=te[1],u=$(J.body,re,ne))),e.n=10;break;case 8:if(!Q||c||!f||"get"===o||"head"===o){e.n=9;break}u=$(u),e.n=10;break;case 9:if(!Q||!c||g||"get"===o||"head"===o){e.n=10;break}throw new xg("Stream request bodies are not supported by the current fetch implementation",xg.ERR_NOT_SUPPORT,t,N);case 10:return mg.isString(I)||(I=I?"include":"omit"),ie=c&&"credentials"in s.prototype,mg.isFormData(u)&&(ae=A.getContentType())&&/^multipart\/form-data/i.test(ae)&&!/boundary=/i.test(ae)&&A.delete("content-type"),A.set("User-Agent","axios/"+Kp,!1),(se=null==w?w:Object.assign(Object.create(null),w))&&(delete se.body,delete se.headers,delete se.method,delete se.signal,delete se.duplex,delete se.credentials),oe=Object.assign(Object.create(null),se,{signal:F,method:o.toUpperCase(),headers:bg(A.normalize()),body:u,duplex:"half",credentials:ie?I:void 0}),c&&(mg.forEach(Hp,function(e,t){void 0===oe[t]&&(oe[t]=e)}),void 0===oe.signal&&(oe.signal=null),void 0===oe.body&&(oe.body=null)),0===D&&(oe.redirect="manual",se&&(se.redirect="manual")),N=c&&new s(i,oe),e.n=11,c?M(N,se):M(i,oe);case 11:if(le=e.v,ue=Pg.from(le.headers),!C){e.n=12;break}if(!(null!=(ce=mg.toFiniteNumber(ue.getContentLength()))&&ce>_)){e.n=12;break}throw new xg("maxContentLength size of "+_+" exceeded",xg.ERR_BAD_RESPONSE,t,N);case 12:return de=p&&("stream"===b||"response"===b),p&&le.body&&(k||C||de&&U)&&(he={},["status","statusText","headers"].forEach(function(e){he[e]=le[e]}),fe=mg.toFiniteNumber(ue.getContentLength()),ve=k&&yp(fe,pp(mp(k),!0))||[],ge=L(ve,2),pe=ge[0],ye=ge[1],me=function(e){if(C&&e>_)throw new xg("maxContentLength size of "+_+" exceeded",xg.ERR_BAD_RESPONSE,t,N);pe&&pe(e)},le=new l(xp(le.body,65536,me,function(){ye&&ye(),U&&U()}),he)),b=b||"text",e.n=13,y[mg.findKey(y,b)||"text"](le,t);case 13:if(Ee=e.v,!C||p||de){e.n=14;break}if(null!=Ee&&("number"==typeof Ee.byteLength?ke=Ee.byteLength:"number"==typeof Ee.size?ke=Ee.size:"string"==typeof Ee&&(ke="function"==typeof n?(new n).encode(Ee).byteLength:Ee.length)),!("number"==typeof ke&&ke>_)){e.n=14;break}throw new xg("maxContentLength size of "+_+" exceeded",xg.ERR_BAD_RESPONSE,t,N);case 14:return!de&&U&&U(),e.n=15,new Promise(function(e,r){hp(e,r,{data:Ee,headers:Pg.from(le.headers),status:le.status,statusText:le.statusText,config:t,request:N})});case 15:return e.a(2,e.v);case 16:if(e.p=16,Ae=e.v,U&&U(),!(F&&F.aborted&&F.reason instanceof xg)){e.n=17;break}throw(Se=F.reason).config=t,N&&(Se.request=N),Ae!==Se&&Object.defineProperty(Se,"cause",{__proto__:null,value:Ae,writable:!0,enumerable:!1,configurable:!0}),Se;case 17:if(!G){e.n=18;break}throw N&&!G.request&&(G.request=N),G;case 18:if(!(Ae instanceof xg)){e.n=19;break}throw N&&!Ae.request&&(Ae.request=N),Ae;case 19:if(!Ae||"TypeError"!==Ae.name||!/Load failed|fetch/i.test(Ae.message)){e.n=20;break}throw Te=new xg("Network Error",xg.ERR_NETWORK,t,N,Ae&&Ae.response),Object.defineProperty(Te,"cause",{__proto__:null,value:Ae.cause||Ae,writable:!0,enumerable:!1,configurable:!0}),Te;case 20:throw xg.from(Ae,Ae&&Ae.code,t,N,Ae&&Ae.response);case 21:return e.a(2)}},e,null,[[1,16]])}));return function(t){return e.apply(this,arguments)}}()},Qp=new Map,$p=function(e){for(var t,r,n=e&&e.env||{},i=n.fetch,a=[n.Request,n.Response,i],s=a.length,o=Qp;s--;)t=a[s],void 0===(r=o.get(t))&&o.set(t,r=s?new Map:Xp(n)),o=r;return r};$p();var Jp={http:null,xhr:_p,fetch:{get:$p}};mg.forEach(Jp,function(e,t){if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch(r){}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}});var Zp=function(e){return"- ".concat(e)},ey=function(e){return mg.isFunction(e)||null===e||!1===e};var ty={getAdapter:function(e,t){for(var r,n,i=(e=mg.isArray(e)?e:[e]).length,a={},s=0;s<i;s++){var o=void 0;if(n=r=e[s],!ey(r)&&void 0===(n=Jp[(o=String(r)).toLowerCase()]))throw new xg("Unknown adapter '".concat(o,"'"));if(n&&(mg.isFunction(n)||(n=n.get(t))))break;a[o||"#"+s]=n}if(!n){var l=Object.entries(a).map(function(e){var t=L(e,2),r=t[0],n=t[1];return"adapter ".concat(r," ")+(!1===n?"is not supported by the environment":"is not available in the build")}),u=i?l.length>1?"since :\n"+l.map(Zp).join("\n"):" "+Zp(l[0]):"as no adapter specified";throw new xg("There is no suitable adapter to dispatch the request "+u,xg.ERR_NOT_SUPPORT)}return n},adapters:Jp};function ry(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new dp(null,e)}function ny(e){var t=mg.toSafeFlatObject(e);return ry(t),t.headers=Pg.from(mg.getSafeProp(t,"headers")),t.data=up.call(t,t.transformRequest),-1!==["post","put","patch"].indexOf(t.method)&&t.headers.setContentType("application/x-www-form-urlencoded",!1),ty.getAdapter(t.adapter||lp.adapter,t)(t).then(function(e){ry(t),t.response=e;try{e.data=up.call(t,t.transformResponse,e)}finally{delete t.response}return e.headers=Pg.from(e.headers),e},function(e){if(!cp(e)&&(ry(t),e&&e.response)){t.response=e.response;try{e.response.data=up.call(t,t.transformResponse,e.response)}finally{delete t.response}e.response.headers=Pg.from(e.response.headers)}return Promise.reject(e)})}var iy={};["object","boolean","number","function","string","symbol"].forEach(function(e,t){iy[e]=function(r){return _(r)===e||"a"+(t<1?"n ":" ")+e}});var ay={};iy.transitional=function(e,t,r){function n(e,t){return"[Axios v"+Kp+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,i,a){if(!1===e)throw new xg(n(i," has been removed"+(t?" in "+t:"")),xg.ERR_DEPRECATED);return t&&!ay[i]&&(ay[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,a)}},iy.spelling=function(e){return function(t,r){return console.warn("".concat(r," is likely a misspelling of ").concat(e)),!0}};var sy={assertOptions:function(e,t,r){if("object"!==_(e)||null===e)throw new xg("options must be an object",xg.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(e),i=n.length;i-- >0;){var a=n[i],s=Object.prototype.hasOwnProperty.call(t,a)?t[a]:void 0;if(s){var o=e[a],l=void 0===o||s(o,a,e);if(!0!==l)throw new xg("option "+a+" must be "+l,xg.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new xg("Unknown option "+a,xg.ERR_BAD_OPTION)}},validators:iy},oy=sy.validators,ly=function(){return h(function e(t){c(this,e),this.defaults=t||{},this.interceptors={request:new Xg,response:new Xg}},[{key:"request",value:(e=o(S().m(function e(t,r){var n,i,a,s,o,l,u,c;return S().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this._request(t,r);case 1:return e.a(2,e.v);case 2:if(e.p=2,(c=e.v)instanceof Error)try{n={},Error.captureStackTrace?Error.captureStackTrace(n):n=new Error,i=n.stack,a="","string"==typeof i&&(s=i.indexOf("\n"),a=-1===s?"":i.slice(s+1)),c.stack?a&&(o=a.indexOf("\n"),l=-1===o?-1:a.indexOf("\n",o+1),u=-1===l?"":a.slice(l+1),String(c.stack).endsWith(u)||(c.stack+="\n"+a)):c.stack=a}catch(d){}throw c;case 3:return e.a(2)}},e,this,[[0,2]])})),function(t,r){return e.apply(this,arguments)})},{key:"_request",value:function(e,t){var r=this;"string"==typeof e?(t=t||{}).url=e:t=e||{};var n=t=Rp(this.defaults,t),i=n.transitional,a=n.paramsSerializer,s=n.headers;void 0!==i&&sy.assertOptions(i,{silentJSONParsing:oy.transitional(oy.boolean),forcedJSONParsing:oy.transitional(oy.boolean),clarifyTimeoutError:oy.transitional(oy.boolean),legacyInterceptorReqResOrdering:oy.transitional(oy.boolean),advertiseZstdAcceptEncoding:oy.transitional(oy.boolean),validateStatusUndefinedResolves:oy.transitional(oy.boolean)},!1),null!=a&&(mg.isFunction(a)?t.paramsSerializer={serialize:a}:sy.assertOptions(a,{encode:oy.function,serialize:oy.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),sy.assertOptions(t,{baseUrl:oy.spelling("baseURL"),withXsrfToken:oy.spelling("withXSRFToken")},!0),t.method=(mg.getSafeProp(t,"method")||mg.getSafeProp(this.defaults,"method")||"get").toLowerCase();var o=s&&mg.merge(s.common,s[t.method]);s&&mg.forEach(sp.concat("common"),function(e){delete s[e]}),t.headers=Pg.concat(o,s);var l=[],u=!0;this.interceptors.request.forEach(function(e){if("function"!=typeof e.runWhen||!1!==e.runWhen(t)){u=u&&e.synchronous;var r=t.transitional||Qg;r&&r.legacyInterceptorReqResOrdering?l.unshift(e.fulfilled,e.rejected):l.push(e.fulfilled,e.rejected)}});var c,d=[];this.interceptors.response.forEach(function(e){d.push(e.fulfilled,e.rejected)});var h,f=0;if(!u){var v=[ny.bind(this),void 0];for(v.unshift.apply(v,l),v.push.apply(v,d),h=v.length,c=Promise.resolve(t);f<h;)c=c.then(v[f++],v[f++]);return c}h=l.length;for(var g=t;f<h;){var p=l[f++],y=l[f++];try{g=p?p(g):g}catch(E){if(!y){c=Promise.reject(E);break}try{var m=y.call(this,E);mg.isThenable(m)&&(c=Promise.resolve(m).then(function(){return ny.call(r,g)}))}catch(k){c=Promise.reject(k)}break}}if(!c)try{c=ny.call(this,g)}catch(E){c=Promise.reject(E)}for(f=0,h=d.length;f<h;)c=c.then(d[f++],d[f++]);return c}},{key:"getUri",value:function(e){return Vg(Ap((e=Rp(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls,e),e.params,e.paramsSerializer)}}]);var e}();mg.forEach(["delete","get","head","options"],function(e){ly.prototype[e]=function(t,r){return this.request(Rp(r||{},{method:e,url:t,data:r&&mg.hasOwnProp(r,"data")?r.data:void 0}))}}),mg.forEach(["post","put","patch","query"],function(e){function t(t){return function(r,n,i){return this.request(Rp(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}ly.prototype[e]=t(),"query"!==e&&(ly.prototype[e+"Form"]=t(!0))});var uy=function(){function e(t){if(c(this,e),"function"!=typeof t)throw new TypeError("executor must be a function.");var r;this.promise=new Promise(function(e){r=e});var n=this;this.promise.then(function(e){if(n._listeners){for(var t=n._listeners.length;t-- >0;)n._listeners[t](e);n._listeners=null}}),this.promise.then=function(e){var t,r=new Promise(function(e){n.subscribe(e),t=e}).then(e);return r.cancel=function(){n.unsubscribe(t)},r},t(function(e,t,i){n.reason||(n.reason=new dp(e,t,i),r(n.reason))})}return h(e,[{key:"throwIfRequested",value:function(){if(this.reason)throw this.reason}},{key:"subscribe",value:function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}},{key:"unsubscribe",value:function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}}},{key:"toAbortSignal",value:function(){var e=this,t=new AbortController,r=function(e){t.abort(e)};return this.subscribe(r),t.signal.unsubscribe=function(){return e.unsubscribe(r)},t.signal}}],[{key:"source",value:function(){var t;return{token:new e(function(e){t=e}),cancel:t}}}])}();var cy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(cy).forEach(function(e){var t=L(e,2),r=t[0],n=t[1];void 0===cy[n]&&(cy[n]=r)});var dy=function e(t){var r=new ly(t),n=Ev(ly.prototype.request,r);return mg.extend(n,ly.prototype,r,{allOwnKeys:!0}),mg.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(Rp(t,r))},n}(lp);dy.Axios=ly,dy.CanceledError=dp,dy.CancelToken=uy,dy.isCancel=cp,dy.VERSION=Kp,dy.toFormData=Bg,dy.AxiosError=xg,dy.Cancel=dy.CanceledError,dy.all=function(e){return Promise.all(e)},dy.spread=function(e){return function(t){return e.apply(null,t)}},dy.isAxiosError=function(e){return mg.isObject(e)&&!0===e.isAxiosError},dy.mergeConfig=Rp,dy.AxiosHeaders=Pg,dy.formToJSON=function(e){return ap(mg.isHTMLForm(e)?new FormData(e):e)},dy.getAdapter=ty.getAdapter,dy.HttpStatusCode=cy,dy.default=dy,dy.Axios,dy.AxiosError,dy.CanceledError,dy.isCancel,dy.CancelToken,dy.VERSION,dy.all,dy.Cancel,dy.isAxiosError,dy.spread,dy.toFormData,dy.AxiosHeaders,dy.HttpStatusCode,dy.formToJSON,dy.getAdapter,dy.mergeConfig,dy.create;var hy=h(function e(t){var r=this;c(this,e),v(this,"get",function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return new Promise(function(i,a){r.instance(k({url:e,method:"GET",params:t},n)).then(function(e){i(e)}).catch(function(e){a(e)})})}),v(this,"post",function(e,t,n){return new Promise(function(i,a){var s={};n?s["Content-Type"]="json"===n?"application/json":"multipart/form-data":(t=mv.stringify(t),s["Content-Type"]="application/x-www-form-urlencoded"),r.instance({url:e,method:"POST",data:t,headers:s}).then(function(e){i(e)}).catch(function(e){a(e)})})}),this.instance=dy.create({baseURL:t||"",timeout:1e4}),this.instance.interceptors.request.use(function(e){return e}),this.instance.interceptors.response.use(function(e){var t=e.data,r=t.code,n=t.message;return r&&200===r?Promise.resolve(e.data):Promise.reject(n)},function(e){return console.log(e),Promise.reject(e)})}),fy=function(){return h(function e(){c(this,e)},null,[{key:"fetchUrls",value:function(e,t){return(new hy).get("".concat(e,"?appid=").concat(t,"&all_play_url=true"))}},{key:"sortUrls",value:function(e){return e.sort(function(e,t){return e.file_size-t.file_size})}},{key:"markSources",value:function(e){return e.map(function(e){var t,r,n=Number(null!==(t=e.source_type)&&void 0!==t?t:e.sourceType),i=Number(null!==(r=e.source_storage_id)&&void 0!==r?r:e.sourceStorageId);return k(k({},e),{},{source_type:n,source_storage_id:i,isLine2:8===n&&4===i})})}},{key:"findLine2Source",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(!e||!e.length)return null;var t=e.find(function(e){return e.isLine2&&e.url});return t||(e.find(function(e){var t,r;return 8===Number(null!==(t=e.source_type)&&void 0!==t?t:e.sourceType)&&4===Number(null!==(r=e.source_storage_id)&&void 0!==r?r:e.sourceStorageId)&&e.url})||null)}},{key:"probeSource",value:function(e){var t=performance.now();return fetch(e.url,{method:"GET",headers:{Accept:"application/vnd.apple.mpegurl, */*"}}).then(function(){var r=o(S().m(function r(n){var i,a;return S().w(function(r){for(;;)switch(r.n){case 0:return r.n=1,n.text();case 1:return i=r.v,a=n.ok&&/#EXTM3U/i.test(i),r.a(2,{ok:a,durationMs:Math.round(performance.now()-t),url:e.url,content:a?i:null,isLine2:!!e.isLine2,source:e})}},r)}));return function(e){return r.apply(this,arguments)}}()).catch(function(){return{ok:!1,durationMs:Math.round(performance.now()-t),url:e.url,content:null,isLine2:!!e.isLine2,source:e}})}},{key:"raceFastestSource",value:function(){var e=this,t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2?arguments[2]:void 0,n=((arguments.length>0&&void 0!==arguments[0]?arguments[0]:[])||[]).filter(function(e){return e&&e.url});if(!n.length)return Promise.resolve({winner:null,results:[]});if(1===n.length){var i=n[0],a={ok:!0,durationMs:0,url:i.url,skipped:!0,isLine2:!!i.isLine2,source:i};return"function"==typeof t&&t(i,a),Promise.resolve({winner:i,results:[a]})}var s=!1,o=n.map(function(n){return e.probeSource(n).then(function(e){return e.ok&&e.content&&r&&(r[e.url]=e.content),e.ok&&!s&&(s=!0,"function"==typeof t&&t(n,e)),e})});return Promise.all(o).then(function(e){var t=e.filter(function(e){return e.ok&&e.content}).sort(function(e,t){return e.durationMs-t.durationMs});return{winner:t.length?t[0].source:null,results:e}})}},{key:"putWinnerFirst",value:function(e,t){if(!t||!e||!e.length)return e||[];var r=e.filter(function(e){return e&&e.url!==t.url});return[t].concat(I(r))}},{key:"ableUrls",value:(e=o(S().m(function e(t){var r;return S().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.fetchUrls(t.sourceURL,t.appId);case 1:return r=e.v,e.a(2,this.markSources(this.sortUrls(r.data.play_urls||[])))}},e,this)})),function(t){return e.apply(this,arguments)})}]);var e}(),vy=function(){return h(function e(t,r){var n=this;c(this,e),this.video=t,this.container=r,this.canvas=document.createElement("canvas"),this.canvas.className="ylc-video-canvas-mirror",this.canvas.setAttribute("data-ylc","canvas-mirror"),this.ctx=this.canvas.getContext("2d",{alpha:!1}),this.running=!1,this.destroyed=!1,this.failed=!1,this.raf=0,this.vfc=0,this._onPlay=function(){return n.start()},this._onPause=function(){n.draw(),n.stop()},this._onFrame=function(){return n.draw()},this._onResize=function(){return n.resize()},this._onFs=function(){return n.exitNativeFullscreen()},this.hideVideo(),this.resize(),this.bind()},[{key:"hideVideo",value:function(){var e=this.video;e.setAttribute("t7-video-player-type","inline"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-video-player-fullscreen","false"),e.controls=!1,e.removeAttribute("controls"),e.style.cssText=["position:fixed","left:-9999px","top:0","width:16px","height:16px","opacity:0.01","pointer-events:none","z-index:-1","object-fit:contain"].join(";")}},{key:"restoreVideo",value:function(){this.video.style.cssText=["position:relative","z-index:0","width:100%","height:100%","background:#000","overflow:hidden","object-fit:contain","pointer-events:none"].join(";"),this.canvas&&this.canvas.parentNode&&(this.canvas.style.display="none")}},{key:"bind",value:function(){this.video.addEventListener("play",this._onPlay),this.video.addEventListener("playing",this._onPlay),this.video.addEventListener("pause",this._onPause),this.video.addEventListener("ended",this._onPause),this.video.addEventListener("seeked",this._onFrame),this.video.addEventListener("loadeddata",this._onFrame),window.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFs),document.addEventListener("webkitfullscreenchange",this._onFs),this.video.addEventListener("webkitbeginfullscreen",this._onFs),"undefined"!=typeof ResizeObserver&&(this.ro=new ResizeObserver(this._onResize),this.ro.observe(this.container))}},{key:"unbind",value:function(){this.video.removeEventListener("play",this._onPlay),this.video.removeEventListener("playing",this._onPlay),this.video.removeEventListener("pause",this._onPause),this.video.removeEventListener("ended",this._onPause),this.video.removeEventListener("seeked",this._onFrame),this.video.removeEventListener("loadeddata",this._onFrame),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFs),document.removeEventListener("webkitfullscreenchange",this._onFs),this.video.removeEventListener("webkitbeginfullscreen",this._onFs),this.ro&&(this.ro.disconnect(),this.ro=null)}},{key:"exitNativeFullscreen",value:function(e){e&&"function"==typeof e.preventDefault&&e.preventDefault();try{this.video.webkitExitFullScreen&&this.video.webkitExitFullScreen()}catch(Ry){}try{document.fullscreenElement&&document.exitFullscreen(),document.webkitFullscreenElement&&document.webkitExitFullscreen&&document.webkitExitFullscreen()}catch(Ry){}}},{key:"resize",value:function(){if(!this.destroyed&&this.container){var e=this.container.getBoundingClientRect(),t=Math.min(window.devicePixelRatio||1,2),r=Math.max(1,Math.floor(e.width*t)),n=Math.max(1,Math.floor(e.height*t));this.canvas.width===r&&this.canvas.height===n||(this.canvas.width=r,this.canvas.height=n,this.draw())}}},{key:"draw",value:function(){if(!this.destroyed&&!this.failed&&this.ctx){var e=this.canvas.width,t=this.canvas.height,r=this.video.videoWidth,n=this.video.videoHeight;if(this.ctx.fillStyle="#000",this.ctx.fillRect(0,0,e,t),r&&n){var i=Math.min(e/r,t/n),a=r*i,s=n*i,o=(e-a)/2,l=(t-s)/2;try{this.ctx.drawImage(this.video,o,l,a,s)}catch(Ry){this.failed=!0,this.stop(),this.restoreVideo()}}}}},{key:"start",value:function(){this.running||this.destroyed||this.failed||(this.running=!0,this.loop())}},{key:"loop",value:function(){var e=this;!this.running||this.destroyed||this.failed||(this.draw(),"function"==typeof this.video.requestVideoFrameCallback?this.vfc=this.video.requestVideoFrameCallback(function(){return e.loop()}):this.raf=requestAnimationFrame(function(){return e.loop()}))}},{key:"stop",value:function(){if(this.running=!1,this.vfc&&"function"==typeof this.video.cancelVideoFrameCallback)try{this.video.cancelVideoFrameCallback(this.vfc)}catch(e){}this.vfc=0,this.raf&&cancelAnimationFrame(this.raf),this.raf=0}},{key:"destroy",value:function(){this.destroyed=!0,this.stop(),this.unbind(),this.ctx=null,this.video=null,this.container=null,this.canvas=null}}])}(),gy=function(){return h(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(c(this,e),this.containerId=t,this.options=k({sourceURL:"",poster:"",autoplay:!1,controls:!0,muted:!1,loop:!1,preload:"metadata",width:"100%",height:"100%"},r),this.hlsInstance=null,this.playUrls=null,this.currentLine=1,this._destroyed=!1,this.controlBar=null,this._handleFullscreenChange=null,this._isSeeking=!1,this._seekTarget=null,this.containerId){var n=document.querySelector("#"+t);n||Ld.error("VideoPlayer日志-未查询到节点",{containerId:t,elTmp:n}),Ld.info("VideoPlayer日志-开始事件和节点初始化",{containerId:t,options:k(k({},this.options),{},{fullscreenElement:""})}),this.el=n,this.events=new Sd(this),this.clearPlayer(),this.init(),Ld.info("VideoPlayer日志-canVideoPlayHevcHls",{canVideoPlayHevcHls:ad(),browser:navigator.userAgent,options:this.options})}else Ld.error("VideoPlayer日志-未传节点id",{containerId:t})},[{key:"init",value:function(){this.createPlayerContainer(),this.setVideoSource(),this.bindEvents()}},{key:"createPlayerContainer",value:function(){if(this.el.innerHTML="",kd.mount(this),function(){if("undefined"==typeof navigator)return!1;var e=navigator.userAgent||"";return!!/MiuiBrowser|XiaoMi|Xiaomi|MiBrowser|XMSDK|Redmi|POCO|MIUI/i.test(e)||!("undefined"==typeof window||!window.miui&&!window.MIUI)}()||rd()){this.canvasMirror=new vy(this.videoElm,this.container);var e=this.touchMask;e?this.container.insertBefore(this.canvasMirror.canvas,e):this.container.appendChild(this.canvasMirror.canvas),Ld.info("VideoPlayer日志-启用canvas镜像防浏览器接管",{ua:navigator.userAgent})}if(this._bindTouchMask(),this.controlBar=Vd.mount(this),"function"==typeof this.options.customControlsMount)try{var t=this.options.customControlsMount({player:this,container:this.container,video:this.videoElm});t instanceof HTMLElement&&this.container.appendChild(t)}catch(r){Ld.error("VideoPlayer日志-挂载自定义控件失败",{e:r})}this.el.appendChild(this.container),Ld.info("VideoPlayer日志-节点初始化完成并加载")}},{key:"_bindTouchMask",value:function(){var e=this;if(this.touchMask){var t=function(e){e.stopPropagation()};this.touchMask.addEventListener("pointerdown",t),this.touchMask.addEventListener("touchstart",t,{passive:!0}),this.touchMask.addEventListener("click",function(t){t.preventDefault(),t.stopPropagation(),e.videoElm&&(e.videoElm.paused?e.play():e.pause())})}}},{key:"setVideoSource",value:(n=o(S().m(function e(){var t;return S().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.useHls()){e.n=6;break}return e.p=1,e.n=2,fy.ableUrls(this.options);case 2:t=e.v,e.n=4;break;case 3:e.p=3,e.v,t=null;case 4:if(!this._destroyed){e.n=5;break}return e.a(2);case 5:this._startHlsWithFastestSource(t),e.n=8;break;case 6:if(!this._destroyed){e.n=7;break}return e.a(2);case 7:this.videoElm.src=this.options.sourceURL;case 8:return e.a(2)}},e,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"bindEvents",value:function(){var e=this;this.videoElm.addEventListener("play",function(){e._applyPlayUi(),e.events.emit("play")}),this.videoElm.addEventListener("playing",function(){e._clearSeekHold(),e._hideLoading(),e.events.emit("playing")}),this.videoElm.addEventListener("pause",function(){e._applyPauseUi(),e.events.emit("pause")}),this.videoElm.addEventListener("ended",function(){e.events.emit("ended")}),this.videoElm.addEventListener("loadedmetadata",function(){Nd.updateDurationTime(e),e.events.emit("loadedmetadata")}),this.videoElm.addEventListener("loadeddata",function(){e.events.emit("loadeddata")}),this.videoElm.addEventListener("loadstart",function(){e.events.emit("loadstart")}),this.videoElm.addEventListener("canplay",function(){e.events.emit("autoPlay"),e.events.emit("canplay"),!e._shouldHoldSeekUi()&&e.videoElm.readyState>=3&&e._hideLoading()}),this.videoElm.addEventListener("seeking",function(t){e._isSeeking=!0,null==e._seekTarget&&(e._seekTarget=t.target.currentTime,e._syncSeekUi(e._seekTarget));var r=null!=e._seekTarget?e._seekTarget:t.target.currentTime;e._isTimeBuffered(r)||e._showLoading(),e.events.emit("seeking",t.target.currentTime)}),this.videoElm.addEventListener("seeked",function(t){var r=t.target.currentTime,n=e._seekTarget,i=null==n||Math.abs(r-n)<=.5;e.videoElm.readyState<2||!i?e._syncSeekUi(null!=n?n:r):(e._clearSeekHold(),e._syncSeekUi(r)),(e.videoElm.readyState>=3||e.videoElm.paused&&e.videoElm.readyState>=2)&&e._hideLoading(),e.events.emit("seeked",r)}),this.videoElm.addEventListener("waiting",function(){e._showLoading(),e.events.emit("waiting")}),this.videoElm.addEventListener("durationchange",function(){e.events.emit("durationchange")}),this.videoElm.addEventListener("timeupdate",function(t){e._shouldHoldSeekUi()||(e._clearSeekHold(),Nd.updateCurrentTime(e),Ud.updateLine(e)),e.events.emit("timeupdate",t.target.currentTime)}),this.videoElm.addEventListener("error",function(){var t=e.videoElm.error,r={code:t?t.code:null,message:t?t.message:"未知错误",src:e.videoElm.src,networkState:e.videoElm.networkState,readyState:e.videoElm.readyState};t&&t.code&&(r.message={1:"MEDIA_ERR_ABORTED - 用户中止",2:"MEDIA_ERR_NETWORK - 网络错误",3:"MEDIA_ERR_DECODE - 解码错误",4:"MEDIA_ERR_SRC_NOT_SUPPORTED - 格式不支持"}[t.code]||r.message),e.videoElm.src&&e.videoElm.src.startsWith("blob:")?(r.blobUrlError=!0,r.message="Blob URL加载失败: ".concat(e.videoElm.src),Ld.error("VideoPlayer日志-视频Blob URL错误",r),e.hlsInstance&&console.error("HLS实例状态:",{media:e.hlsInstance.media,url:e.hlsInstance.url,levels:e.hlsInstance.levels,currentLevel:e.hlsInstance.currentLevel})):Ld.error("VideoPlayer日志-视频加载错误",r),e.events.emit("error",r)}),this._handleFullscreenChange=function(){var t=!!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement);e.events.emit("fullscreenchange",t),e.options.controls&&Bd.changeFullScreen(e,t)},document.addEventListener("fullscreenchange",this._handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this._handleFullscreenChange),document.addEventListener("mozfullscreenchange",this._handleFullscreenChange),document.addEventListener("MSFullscreenChange",this._handleFullscreenChange),this.events.on("fullscreenchange",function(t){e.options.controls&&Bd.changeFullScreen(e,t)}),this.events.on("volumechange",function(t){Gd.sync(e,t)}),this.events.on("changeProgress",function(t){Ud.updateLineDot(e,t)}),this.options.autoPlay&&this.events.once("autoPlay",function(){e.play()});var t=new MutationObserver(function(){e.videoElm&&e.videoElm.hasAttribute("controls")&&(e.videoElm.removeAttribute("controls"),e.videoElm.controls=!1)});this.videoElm&&(t.observe(this.videoElm,{attributes:!0,attributeFilter:["controls"]}),this._controlsObserver=t,this.videoElm.hasAttribute("controls")&&(this.videoElm.removeAttribute("controls"),this.videoElm.controls=!1)),Ld.info("VideoPlayer日志-事件绑定完成")}},{key:"clearPlayer",value:function(){if(this.el){var e=this.el.querySelector("video");if(e&&(e.pause(),e.src="","function"==typeof e.remove))try{e.remove()}catch(t){}this.el.innerHTML="",Ld.info("VideoPlayer日志-清除播放器")}}},{key:"_applyPlayUi",value:function(){this.status="playing",Fd.changeBtnStatus(this)}},{key:"_applyPauseUi",value:function(){this.status="pause",Fd.changeBtnStatus(this)}},{key:"play",value:function(){if(this._applyPlayUi(),this.videoElm&&(this.videoElm.controls=!1,this.videoElm.removeAttribute("controls"),this.videoElm.paused)){var e=this.videoElm.play();e&&"function"==typeof e.catch&&e.catch(function(){})}Ld.info("VideoPlayer日志-播放",{status:this.status})}},{key:"pause",value:function(){this._applyPauseUi(),this.videoElm&&!this.videoElm.paused&&this.videoElm.pause(),Ld.info("VideoPlayer日志-暂停",{status:this.status})}},{key:"on",value:function(e,t){this.events.on(e,t)}},{key:"off",value:function(e,t){this.events.off(e,t)}},{key:"currentTimeSec",value:function(e){return void 0!==e&&this.seek(e),this.videoElm.currentTime}},{key:"duration",value:function(){return this.videoElm.duration}},{key:"_isProgressDragging",value:function(){return!(!this.progressSlider||!this.progressSlider.isDragging)}},{key:"_isTimeBuffered",value:function(e){var t=this.videoElm&&this.videoElm.buffered;if(!t||!Number.isFinite(e))return!1;for(var r=0;r<t.length;r++)if(e>=t.start(r)&&e<t.end(r)-.15)return!0;return!1}},{key:"_shouldHoldSeekUi",value:function(){return!!this._isProgressDragging()||this._isSeeking}},{key:"_syncSeekUi",value:function(e){if(Number.isFinite(e)&&this.videoElm){var t=this.videoElm.duration;Nd.updateCurrentTime(this,e),t&&Number.isFinite(t)&&t>0&&Ud.updateLine(this,e/t)}}},{key:"_clearSeekHold",value:function(){this._isSeeking=!1,this._seekTarget=null}},{key:"_showLoading",value:function(){this.loadingElm&&this.loadingElm.classList.add("is-show")}},{key:"_hideLoading",value:function(){this.loadingElm&&this.loadingElm.classList.remove("is-show")}},{key:"seek",value:function(e){if(this.videoElm&&Number.isFinite(e)){var t=this.videoElm.duration,r=t&&Number.isFinite(t)?Math.max(0,Math.min(t,e)):Math.max(0,e);this._isSeeking=!0,this._seekTarget=r,this._syncSeekUi(r),this._isTimeBuffered(r)||this._showLoading(),this.videoElm.currentTime=r}}},{key:"changeSrc",value:function(e){var t=this;this.hlsInstance&&(Md.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),e&&e.includes(".m3u8")&&Jc.isSupported()?(this.options.isSupportHls=!0,this.options.sourceURL=e,this.setVideoSource()):(this.options.isSupportHls=!1,this.options.sourceURL=e,this.videoElm.src=e,this.events.once("autoPlay",function(){t.play()}))}},{key:"muted",value:function(e){Gd.changeVolume(this,!e),this.events.emit("volumechange",!e)}},{key:"requestFullscreen",value:function(){Bd.fullScreen(this)}},{key:"exitFullscreen",value:function(){Bd.exitFullScreen(this)}},{key:"changeSpeed",value:function(e){var t=e.value;this.videoElm.playbackRate=t||1}},{key:"uploadPlayerLogs",value:(r=o(S().m(function e(){return S().w(function(e){for(;;)switch(e.n){case 0:Ld.info("VideoPlayer日志-日志已通过WebSocket实时上报");case 1:return e.a(2)}},e)})),function(){return r.apply(this,arguments)})},{key:"destroy",value:function(){this._destroyed=!0,this._hideLoading(),this._clearSeekHold(),this.hlsInstance&&(Md.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),this._controlsObserver&&(this._controlsObserver.disconnect(),this._controlsObserver=null),this._handleFullscreenChange&&(document.removeEventListener("fullscreenchange",this._handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._handleFullscreenChange),document.removeEventListener("mozfullscreenchange",this._handleFullscreenChange),document.removeEventListener("MSFullscreenChange",this._handleFullscreenChange),this._handleFullscreenChange=null),this.canvasMirror&&(this.canvasMirror.destroy(),this.canvasMirror=null),this.events&&"function"==typeof this.events.removeAll&&this.events.removeAll(),this.clearPlayer()}},{key:"useHls",value:function(){return this.options.isSupportHls&&this.options.sourceURL.includes(".m3u8")}},{key:"_findLine2Source",value:function(e){return fy.findLine2Source(e)}},{key:"switchLine",value:(t=o(S().m(function e(t){var r,n,i,a;return S().w(function(e){for(;;)switch(e.p=e.n){case 0:if(r=2===Number(t)?2:1,!this._destroyed){e.n=1;break}return e.a(2,!1);case 1:if(this.useHls()){e.n=2;break}return e.a(2,!1);case 2:if(this.currentLine!==r||!this.hlsInstance){e.n=3;break}return Hd.changeLineUI(this,r),e.a(2,!0);case 3:return e.p=3,e.n=4,fy.ableUrls(this.options);case 4:this.playUrls=e.v,e.n=6;break;case 5:if(e.p=5,e.v,this.playUrls&&this.playUrls.length){e.n=6;break}return e.a(2,!1);case 6:if(!this._destroyed){e.n=7;break}return e.a(2,!1);case 7:if(2!==r){e.n=10;break}if((n=this._findLine2Source(this.playUrls))&&n.url){e.n=8;break}return e.a(2,!1);case 8:return e.n=9,this._reloadHlsByLine({line:2,url:n.url,cdnList:[n],switchCdn:!1});case 9:return e.a(2,!0);case 10:return this.currentLine=1,Hd.changeLineUI(this,1),i=this.videoElm?this.videoElm.currentTime:0,a="playing"===this.status||this.videoElm&&!this.videoElm.paused,this._startHlsWithFastestSource(this.playUrls,{restoreTime:i,wasPlaying:a}),e.a(2,!0)}},e,this,[[3,5]])})),function(e){return t.apply(this,arguments)})},{key:"_startHlsWithFastestSource",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e&&e.length?e:null,i=!!(n&&n.length>1),a=n&&n[0]&&n[0].url||this.options.sourceURL;this.playUrls=n,this.currentLine=this.currentLine||1;var s=r.restoreTime,o=r.wasPlaying,l={},u=function(e,r){!t._destroyed&&e&&(t.hlsInstance&&(Md.destroyHlsInstance(t.hlsInstance),t.hlsInstance=null),t.hlsInstance=Md.createHlsInstance(t.videoElm,!!(r&&r.length>1),r||[],k(k({},t.options),{},{m3u8Cache:l})),Md.startLoad(t.hlsInstance,e),(s>0&&Number.isFinite(s)||o)&&t.hlsInstance.once(Jc.Events.MANIFEST_PARSED,function(){if(!t._destroyed&&t.videoElm){if(s>0&&Number.isFinite(s))try{t.videoElm.currentTime=s}catch(e){}o&&t.play()}}))};if(i){var c=!1;fy.raceFastestSource(n,function(e,r){if(!c&&!t._destroyed){c=!0,r.content&&(l[e.url]=r.content);var i=fy.putWinnerFirst(n,e);t.playUrls=i,u(e.url,i)}},l).then(function(e){var r=e.winner,i=r?fy.putWinnerFirst(n,r):t.playUrls||n;if(t.playUrls=i,i&&i.length>1&&Cd(i,l),!c&&!t._destroyed){c=!0;var s=i&&i[0]&&i[0].url||a;u(s,i||n)}}).catch(function(){c||t._destroyed||(c=!0,u(a,n))})}else u(a,n||[])}},{key:"_reloadHlsByLine",value:(e=o(S().m(function e(t){var r,n,i,a,s,o,l,u=this;return S().w(function(e){for(;;)switch(e.n){case 0:if(r=t.line,n=t.url,i=t.cdnList,a=t.switchCdn,!this._destroyed&&n){e.n=1;break}return e.a(2);case 1:s=this.videoElm?this.videoElm.currentTime:0,o="playing"===this.status||this.videoElm&&!this.videoElm.paused,this.hlsInstance&&(Md.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),this.currentLine=r,Hd.changeLineUI(this,r),this.hlsInstance=Md.createHlsInstance(this.videoElm,a,i||[],this.options),Md.startLoad(this.hlsInstance,n),l=function(){if(!u._destroyed&&u.videoElm){if(s>0&&Number.isFinite(s))try{u.videoElm.currentTime=s}catch(e){}o&&u.play()}},this.hlsInstance.once(Jc.Events.MANIFEST_PARSED,l);case 2:return e.a(2)}},e,this)})),function(t){return e.apply(this,arguments)})}]);var e,t,r,n}(),py=function(){return h(function e(t){c(this,e),this.target=t,this.eventsQueue={}},[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.eventsQueue[e]||(this.eventsQueue[e]={methods:[],onceFlags:[]}),this.eventsQueue[e].methods.includes(t)||(this.eventsQueue[e].methods.push(t),this.eventsQueue[e].onceFlags.push(!!r))}},{key:"once",value:function(e,t){this.on(e,t,!0)}},{key:"emit",value:function(e){for(var t=this,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];var a=this.eventsQueue[e];if(a){var s=a.methods,o=a.onceFlags,l=[],u=[];s.forEach(function(r,i){try{r.apply(t.target,n)}catch(a){console.error("[LivePlayer Events]",e,a)}o[i]||(l.push(r),u.push(!1))}),a.methods=l,a.onceFlags=u}}},{key:"off",value:function(e,t){var r=this.eventsQueue[e];if(r)if(t){var n=r.methods.indexOf(t);n>=0&&(r.methods.splice(n,1),r.onceFlags.splice(n,1)),r.methods.length||delete this.eventsQueue[e]}else delete this.eventsQueue[e]}},{key:"removeAll",value:function(){this.eventsQueue={}}}])}(),yy=function(){function e(){c(this,e)}return h(e,null,[{key:"injectStyle",value:function(){od()}},{key:"createVideoElement",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=document.createElement("video");return t.className="ylc-live-player-video",t.setAttribute("playsinline","true"),t.setAttribute("webkit-playsinline","true"),t.muted=!!e.muted,t.autoplay=!!e.autoPlay||!!e.autoplay,t.controls=!1,e.poster&&(t.poster=e.poster),t}},{key:"mount",value:function(t){e.injectStyle();var r=t.options||{},n=Ed(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.showControls,r=void 0===t||t,n=e.muted,i=void 0!==n&&n,a=r?'\n <div class="ylc-live-player-controls">\n <img class="ylc-live-play-button" src="'.concat(md,'/play_pause.png" title="播放" alt="">\n <img class="ylc-live-pause-button" src="').concat(md,'/new_play_pause.png" title="暂停" alt="">\n <img class="ylc-live-volume-button" src="').concat(md,'/yinliang.png" title="声音" alt="" style="').concat(i?"display:none":"",'">\n <img class="ylc-live-mute-button" src="').concat(md,'/jingyin.png" title="静音" alt="" style="').concat(i?"":"display:none",'">\n <img class="ylc-live-full-screen-button" src="').concat(md,'/ylc_full_screen.png" title="全屏" alt="">\n <img class="ylc-live-exit-full-screen-button" src="').concat(md,'/ylc_exit_screen.png" title="退出全屏" alt="">\n </div>'):"";return'\n <div class="ylc-live-player-container">\n <div class="ylc-live-player-badge">LIVE</div>\n <div class="ylc-live-player-status"></div>\n '.concat(a,"\n </div>\n ")}({showControls:!!r.controls,muted:!!r.muted})),i=e.createVideoElement(r);return n.insertBefore(i,n.firstChild),t.container=n,t.videoElm=i,t.liveBadge=n.querySelector(".ylc-live-player-badge"),t.statusText=n.querySelector(".ylc-live-player-status"),t.controlBar=n.querySelector(".ylc-live-player-controls"),t.playButton=n.querySelector(".ylc-live-play-button"),t.pauseButton=n.querySelector(".ylc-live-pause-button"),t.volumeButton=n.querySelector(".ylc-live-volume-button"),t.muteButton=n.querySelector(".ylc-live-mute-button"),t.fullScreenButton=n.querySelector(".ylc-live-full-screen-button"),t.exitFullScreenButton=n.querySelector(".ylc-live-exit-full-screen-button"),n}}])}(),my=function(){return h(function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};c(this,e),this.whepUrl=t.whepUrl||"",this.rtcConfig=t.rtcConfig||{iceServers:[{urls:"stun:stun.l.google.com:19302"}]},this.headers=t.headers||{},this.onPeer=t.onPeer,this.onTrack=t.onTrack,this.onError=t.onError,this.onConnectionState=t.onConnectionState,this.pc=null,this.resourceUrl=null,this._closed=!1},[{key:"start",value:(t=o(S().m(function e(){var t,r,n,i,a,s,o=this;return S().w(function(e){for(;;)switch(e.n){case 0:if(this.whepUrl){e.n=1;break}throw new Error("whepUrl 不能为空");case 1:return this._closed=!1,this.pc=new RTCPeerConnection(this.rtcConfig),"function"==typeof this.onPeer&&this.onPeer(this.pc),this.pc.addTransceiver("video",{direction:"recvonly"}),this.pc.addTransceiver("audio",{direction:"recvonly"}),this.pc.ontrack=function(e){if("function"==typeof o.onTrack){var t=e.streams&&e.streams[0]?e.streams[0]:new MediaStream([e.track]);o.onTrack(t,e)}},this.pc.onconnectionstatechange=function(){"function"==typeof o.onConnectionState&&o.onConnectionState(o.pc.connectionState),"failed"===o.pc.connectionState&&o._emitError(new Error("WebRTC connection failed"))},e.n=2,this.pc.createOffer();case 2:return t=e.v,e.n=3,this.pc.setLocalDescription(t);case 3:return e.n=4,this._waitIceGatheringComplete(this.pc);case 4:return r=this.pc.localDescription&&this.pc.localDescription.sdp,e.n=5,fetch(this.whepUrl,{method:"POST",headers:k({"Content-Type":"application/sdp"},this.headers),body:r});case 5:if((n=e.v).ok){e.n=7;break}return e.n=6,n.text().catch(function(){return""});case 6:throw i=e.v,new Error("WHEP 请求失败 HTTP ".concat(n.status," ").concat(i));case 7:if(a=n.headers.get("Location")||n.headers.get("location"))try{this.resourceUrl=new URL(a,this.whepUrl).toString()}catch(l){this.resourceUrl=a}return e.n=8,n.text();case 8:return s=e.v,e.n=9,this.pc.setRemoteDescription({type:"answer",sdp:s});case 9:return e.a(2,this.pc)}},e,this)})),function(){return t.apply(this,arguments)})},{key:"stop",value:(e=o(S().m(function e(){return S().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this._closed=!0,!this.resourceUrl){e.n=5;break}return e.p=1,e.n=2,fetch(this.resourceUrl,{method:"DELETE",headers:k({},this.headers)});case 2:e.n=4;break;case 3:e.p=3,e.v;case 4:this.resourceUrl=null;case 5:if(this.pc){try{this.pc.getSenders().forEach(function(e){e.track&&e.track.stop()}),this.pc.getReceivers().forEach(function(e){e.track&&e.track.stop()}),this.pc.close()}catch(t){}this.pc=null}case 6:return e.a(2)}},e,this,[[1,3]])})),function(){return e.apply(this,arguments)})},{key:"_waitIceGatheringComplete",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3e3;return"complete"===e.iceGatheringState?Promise.resolve():new Promise(function(r){var n=setTimeout(function(){e.removeEventListener("icegatheringstatechange",i),r()},t),i=function(){"complete"===e.iceGatheringState&&(clearTimeout(n),e.removeEventListener("icegatheringstatechange",i),r())};e.addEventListener("icegatheringstatechange",i)})}},{key:"_emitError",value:function(e){this._closed||"function"==typeof this.onError&&this.onError(e)}}]);var e,t}(),Ey=function(){return h(function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};c(this,e),this.video=t.video,this.options=t,this.pc=null,this.whep=null,this.stream=null,this._destroyed=!1},[{key:"start",value:(i=o(S().m(function e(){var t;return S().w(function(e){for(;;)switch(e.n){case 0:if(!this._destroyed){e.n=1;break}return e.a(2);case 1:if(!this.options.mediaStream){e.n=3;break}return e.n=2,this._attachStream(this.options.mediaStream);case 2:case 5:return this._emit("connected"),e.a(2);case 3:if("function"!=typeof this.options.getStream){e.n=6;break}return e.n=4,this.options.getStream();case 4:return t=e.v,e.n=5,this._attachStream(t);case 6:if(!this.options.whepUrl){e.n=8;break}return e.n=7,this._startWhep();case 7:case 9:case 11:return e.a(2);case 8:if("function"!=typeof this.options.signaling){e.n=10;break}return e.n=9,this._startCustomSignaling();case 10:throw new Error("LivePlayer: 请提供 mediaStream / getStream / whepUrl / signaling 之一")}},e,this)})),function(){return i.apply(this,arguments)})},{key:"_startWhep",value:(n=o(S().m(function e(){var t=this;return S().w(function(e){for(;;)switch(e.n){case 0:return this.whep=new my({whepUrl:this.options.whepUrl,rtcConfig:this.options.rtcConfig,headers:this.options.headers,onPeer:function(e){t.pc=e},onTrack:function(e){t._attachStream(e)},onConnectionState:function(e){t._emit("connectionstatechange",{state:e}),"connected"===e&&t._emit("connected"),"disconnected"!==e&&"failed"!==e&&"closed"!==e||t._emit("disconnected",{state:e})},onError:function(e){return t._emit("error",{error:e})}}),e.n=1,this.whep.start();case 1:return e.a(2)}},e,this)})),function(){return n.apply(this,arguments)})},{key:"_startCustomSignaling",value:(r=o(S().m(function e(){var t,r=this;return S().w(function(e){for(;;)switch(e.n){case 0:return t=this.options.rtcConfig||{iceServers:[{urls:"stun:stun.l.google.com:19302"}]},this.pc=new RTCPeerConnection(t),this.pc.addTransceiver("video",{direction:"recvonly"}),this.pc.addTransceiver("audio",{direction:"recvonly"}),this.pc.ontrack=function(e){var t=e.streams&&e.streams[0]?e.streams[0]:new MediaStream([e.track]);r._attachStream(t)},this.pc.onconnectionstatechange=function(){var e=r.pc.connectionState;r._emit("connectionstatechange",{state:e}),"connected"===e&&r._emit("connected"),"disconnected"!==e&&"failed"!==e&&"closed"!==e||r._emit("disconnected",{state:e})},e.n=1,this.options.signaling(this.pc,{attachStream:function(e){return r._attachStream(e)}});case 1:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"_attachStream",value:(t=o(S().m(function e(t){var r;return S().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this._destroyed&&t){e.n=1;break}return e.a(2);case 1:if(this.stream=t,!this.video){e.n=5;break}return this.video.srcObject=t,e.p=2,e.n=3,this.video.play();case 3:e.n=5;break;case 4:e.p=4,r=e.v,this._emit("autoplayblocked",{error:r});case 5:this._emit("track",{stream:t});case 6:return e.a(2)}},e,this,[[2,4]])})),function(e){return t.apply(this,arguments)})},{key:"getPeerConnection",value:function(){return this.pc}},{key:"getStream",value:function(){return this.stream}},{key:"destroy",value:(e=o(S().m(function e(){return S().w(function(e){for(;;)switch(e.n){case 0:if(this._destroyed=!0,!this.whep){e.n=2;break}return e.n=1,this.whep.stop();case 1:this.whep=null;case 2:if(this.pc&&!this.whep){try{this.pc.getReceivers().forEach(function(e){e.track&&e.track.stop()}),this.pc.close()}catch(t){}this.pc=null}if(this.stream){try{this.stream.getTracks().forEach(function(e){return e.stop()})}catch(t){}this.stream=null}this.video&&(this.video.srcObject=null);case 3:return e.a(2)}},e,this)})),function(){return e.apply(this,arguments)})},{key:"_emit",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"function"==typeof this.options.onEvent&&this.options.onEvent(k({type:e},t))}}]);var e,t,r,n,i}(),ky=function(){return h(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};c(this,e),this.containerId=t,this.options=k({poster:"",autoPlay:!0,autoplay:!0,controls:!0,muted:!0,protocol:"webrtc",whepUrl:"",mediaStream:null,getStream:null,signaling:null,rtcConfig:null,headers:null},r),this._destroyed=!1,this.status="idle",this.adapter=null,this._docFsHandler=null,this.containerId?(this.el=document.querySelector("#"+t),this.el?(this.events=new py(this),this.clearPlayer(),this.init()):Ld.error("LivePlayer日志-未查询到节点",{containerId:t})):Ld.error("LivePlayer日志-未传节点id",{containerId:t})},[{key:"init",value:function(){var e=this;Ld.info("LivePlayer日志-开始初始化",{containerId:this.containerId,protocol:this.options.protocol,hasWhep:!!this.options.whepUrl,hasStream:!!this.options.mediaStream,hasGetStream:"function"==typeof this.options.getStream,hasSignaling:"function"==typeof this.options.signaling}),this.createPlayerContainer(),this.bindUiEvents(),this.startLive().catch(function(t){e._handleError(t)})}},{key:"createPlayerContainer",value:function(){this.el.innerHTML="",yy.mount(this),this.statusText&&(this.statusText.textContent="连接中..."),this.el.appendChild(this.container)}},{key:"bindUiEvents",value:function(){var e=this;this.playButton&&(this.playButton.onclick=function(){return e.play()}),this.pauseButton&&(this.pauseButton.onclick=function(){return e.pause()}),this.volumeButton&&(this.volumeButton.onclick=function(){return e.muted(!0)}),this.muteButton&&(this.muteButton.onclick=function(){return e.muted(!1)}),this.fullScreenButton&&(this.fullScreenButton.onclick=function(){return e.requestFullscreen()}),this.exitFullScreenButton&&(this.exitFullScreenButton.onclick=function(){return e.exitFullscreen()}),this.videoElm.addEventListener("playing",function(){e.status="playing",e._syncPlayButtons(),e._setStatusText(""),e.events.emit("playing"),e.events.emit("play")}),this.videoElm.addEventListener("pause",function(){e.status="pause",e._syncPlayButtons(),e.events.emit("pause")}),this.videoElm.addEventListener("waiting",function(){e._setStatusText("加载中..."),e.events.emit("waiting")}),this.videoElm.addEventListener("error",function(){e._handleError(new Error("video element error"))}),this._docFsHandler=function(){return e._syncFullscreenButtons()},document.addEventListener("fullscreenchange",this._docFsHandler),document.addEventListener("webkitfullscreenchange",this._docFsHandler)}},{key:"startLive",value:(r=o(S().m(function e(){var t=this;return S().w(function(e){for(;;)switch(e.n){case 0:if(!this._destroyed){e.n=1;break}return e.a(2);case 1:return this.adapter=new Ey({video:this.videoElm,mediaStream:this.options.mediaStream,getStream:this.options.getStream,whepUrl:this.options.whepUrl||this.options.sourceURL,rtcConfig:this.options.rtcConfig,headers:this.options.headers,signaling:this.options.signaling,onEvent:function(e){return t._onAdapterEvent(e)}}),this.status="connecting",this._setStatusText("连接中..."),this.events.emit("connecting"),e.n=2,this.adapter.start();case 2:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"_onAdapterEvent",value:function(e){if(!this._destroyed){var t=e.type;"connected"===t?(this.status="connected",this._setStatusText(""),this.events.emit("connected"),Ld.info("LivePlayer日志-已连接")):"disconnected"===t?(this.status="disconnected",this._setStatusText("已断开"),this.events.emit("disconnected",e),Ld.info("LivePlayer日志-已断开",e)):"connectionstatechange"===t?this.events.emit("connectionstatechange",e):"track"===t?this.events.emit("track",e):"autoplayblocked"===t?(this._setStatusText("点击播放"),this.events.emit("autoplayblocked",e),Ld.info("LivePlayer日志-自动播放被拦截")):"error"===t&&this._handleError(e.error||new Error("rtc error"))}}},{key:"_handleError",value:function(e){var t=e&&e.message?e.message:String(e);this.status="error",this._setStatusText(t),Ld.error("LivePlayer日志-错误",{message:t}),this.events.emit("error",{error:e,message:t})}},{key:"_setStatusText",value:function(e){this.statusText&&(this.statusText.textContent=e||"",this.statusText.style.display=e?"block":"none")}},{key:"_syncPlayButtons",value:function(){if(this.playButton&&this.pauseButton){var e="playing"===this.status;this.playButton.style.display=e?"none":"inline-block",this.pauseButton.style.display=e?"inline-block":"none"}}},{key:"_syncFullscreenButtons",value:function(){if(this.fullScreenButton&&this.exitFullScreenButton){var e=!!(document.fullscreenElement||document.webkitFullscreenElement);this.fullScreenButton.style.display=e?"none":"inline-block",this.exitFullScreenButton.style.display=e?"inline-block":"none"}}},{key:"play",value:function(){var e=this;if(this.videoElm){var t=this.videoElm.play();t&&"function"==typeof t.then&&t.then(function(){e.status="playing",e._syncPlayButtons(),e._setStatusText(""),Ld.info("LivePlayer日志-播放")}).catch(function(t){e._handleError(t)})}}},{key:"pause",value:function(){this.videoElm&&(this.videoElm.pause(),this.status="pause",this._syncPlayButtons(),Ld.info("LivePlayer日志-暂停"))}},{key:"muted",value:function(e){this.videoElm&&(this.videoElm.muted=!!e,this.volumeButton&&this.muteButton&&(this.volumeButton.style.display=e?"none":"inline-block",this.muteButton.style.display=e?"inline-block":"none"),this.events.emit("volumechange",{muted:!!e}))}},{key:"on",value:function(e,t){this.events.on(e,t)}},{key:"once",value:function(e,t){this.events.once(e,t)}},{key:"off",value:function(e,t){this.events.off(e,t)}},{key:"changeSrc",value:(t=o(S().m(function e(t){return S().w(function(e){for(;;)switch(e.n){case 0:if(!this._destroyed){e.n=1;break}return e.a(2);case 1:if("string"==typeof t?(this.options.whepUrl=t,this.options.sourceURL=t,this.options.mediaStream=null,this.options.getStream=null,this.options.signaling=null):t&&"object"===_(t)&&Object.assign(this.options,t),!this.adapter){e.n=3;break}return e.n=2,this.adapter.destroy();case 2:this.adapter=null;case 3:return this._setStatusText("重新连接..."),e.n=4,this.startLive();case 4:return e.a(2)}},e,this)})),function(e){return t.apply(this,arguments)})},{key:"requestFullscreen",value:function(){var e=this.options.fullscreenElement||this.container||this.el;if(e){var t=e.requestFullscreen||e.webkitRequestFullscreen||e.webkitEnterFullscreen;if(t)try{var r=t.call(e);r&&"function"==typeof r.catch&&r.catch(function(){})}catch(n){this.videoElm&&this.videoElm.webkitEnterFullscreen&&this.videoElm.webkitEnterFullscreen()}this.events.emit("fullscreenchange",{fullscreen:!0})}}},{key:"exitFullscreen",value:function(){var e=document.exitFullscreen||document.webkitExitFullscreen;if(e)try{var t=e.call(document);t&&"function"==typeof t.catch&&t.catch(function(){})}catch(r){}this.events.emit("fullscreenchange",{fullscreen:!1})}},{key:"getPeerConnection",value:function(){return this.adapter?this.adapter.getPeerConnection():null}},{key:"getStream",value:function(){return this.adapter?this.adapter.getStream():null}},{key:"clearPlayer",value:function(){if(this.el){var e=this.el.querySelector("video");if(e)try{e.pause(),e.srcObject=null,e.removeAttribute("src")}catch(t){}this.el.innerHTML=""}}},{key:"destroy",value:(e=o(S().m(function e(){return S().w(function(e){for(;;)switch(e.n){case 0:if(this._destroyed=!0,this._docFsHandler&&(document.removeEventListener("fullscreenchange",this._docFsHandler),document.removeEventListener("webkitfullscreenchange",this._docFsHandler),this._docFsHandler=null),!this.adapter){e.n=2;break}return e.n=1,this.adapter.destroy();case 1:this.adapter=null;case 2:this.events&&this.events.removeAll(),this.clearPlayer(),this.status="destroyed",Ld.info("LivePlayer日志-已销毁",{containerId:this.containerId});case 3:return e.a(2)}},e,this)})),function(){return e.apply(this,arguments)})}]);var e,t,r}(),Sy=function(){return h(function e(){c(this,e)},null,[{key:"getVideoSignByFileId",value:function(e,t,r){return new Promise(function(n,i){var a=new hy,s={secret_id:t,secret_key:r,file_id:e};a.post("https://console-api.huaxiacloud.net/third_party/generate/sign",s,"json").then(function(e){n(e)}).catch(function(e){i(e)})})}},{key:"getVideoUrlBySign",value:function(e,t,r,n){return new Promise(function(i,a){var s=new hy,o={secret_id:t,file_id:String(e),timestamp:String(r),sign:n,client_type:"web"};s.post("https://console-api.huaxiacloud.net/third_party/verify/sign",o,"json").then(function(e){i(e)}).catch(function(e){a(e)})})}}])}(),Ty=["play","pause","seek","currentTimeSec","changeSrc","muted","changeSpeed","switchLine","on","off","uploadPlayerLogs","requestFullscreen","exitFullscreen"];function by(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return"live"===e.mode||("webrtc"===e.protocol||"rtc"===e.protocol||(!!e.whepUrl||!(!e.mediaStream&&"function"!=typeof e.getStream&&"function"!=typeof e.signaling)))}function Ay(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return(e.sourceURL||"").includes(".m3u8")?td()&&!e.isEncrypt?{type:"VIDEO"}:{type:"HLS"}:{type:"VIDEO"}}var Ly=function(){function e(t){var r,n=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};c(this,e),(r=t)&&"object"===_(r)&&1!==r.nodeType&&!Array.isArray(r)&&(t.id||t.el||t.container||t.url||t.sourceURL||t.fileId||t.whepUrl||t.mode)&&(t=(i=k(k({},t),i)).id||i.el||i.container);var a=function(e){if(!e)return{id:"",el:null};if("string"==typeof e){var t=e.replace(/^#/,"");return{id:t,el:"undefined"!=typeof document?document.querySelector("#"+t):null}}return 1===e.nodeType?(e.id||(e.id="hx-player-"+Date.now()),{id:e.id,el:e}):{id:"",el:null}}(t);this.containerId=a.id,this.el=a.el,this.options=function(){var e=k({},arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return e.url&&!e.sourceURL&&(e.sourceURL=e.url),null!=e.autoplay&&null==e.autoPlay&&(e.autoPlay=e.autoplay),e}(i),this._player=null,this._destroyed=!1;var s=e._instances.get(this.containerId);s&&s!==this&&"function"==typeof s.destroy&&s.destroy(),this.containerId&&e._instances.set(this.containerId,this),this._seq=(e._createSeq.get(this.containerId)||0)+1,e._createSeq.set(this.containerId,this._seq),this.ready=this._bootstrap(),Ty.forEach(function(e){n[e]=function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return n._call.apply(n,[e].concat(r))}})}return h(e,[{key:"player",get:function(){return this._player}},{key:"video",get:function(){return this._player&&this._player.videoElm}},{key:"_bootstrap",value:(t=o(S().m(function t(){var r,n,i,a,s,o,l,u;return S().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,Ld.info("HxPlayer日志-创建播放器实例",{containerId:this.containerId,options:k(k({},this.options),{},{fullscreenElement:""})}),bd.connect({userId:this.options.fansId||this.options.userId||this.options.user_id||"",terminal:this.options.terminal||bd.detectTerminal()}).catch(function(e){console.warn("[HxPlayer] LogWebSocket 连接失败",e)}),Ld.setAppContext({appId:this.options.appId,fansId:this.options.fansId}),this.options.sourceURL||!this.options.fileId||!this.options.secret_id){t.n=2;break}return t.n=1,Sy.getVideoUrlBySign(this.options.fileId,this.options.secret_id,this.options.timestamp,this.options.sign);case 1:r=t.v,n=r.code,i=r.data,a=i.play_url,s=i.encrypt_type,o=i.encrypted_data,200===n&&(this.options.sourceURL=a,this.options.url=a,this.options.isEncrypt=1===s,this.options.encryptedData=o);case 2:if(!this._destroyed){t.n=3;break}return t.a(2,this);case 3:if(!this.containerId||e._createSeq.get(this.containerId)===this._seq){t.n=4;break}return Ld.info("HxPlayer日志-检测到更新的实例,放弃本次初始化",{containerId:this.containerId,seq:this._seq}),t.a(2,this);case 4:if(!by(this.options)){t.n=5;break}this._player=new ky(this.containerId,this.options),t.n=7;break;case 5:if(l=Ay(this.options),!this._destroyed){t.n=6;break}return t.a(2,this);case 6:this._player=new gy(this.containerId,k(k({},this.options),{},{isSupportHls:"HLS"===l.type}));case 7:return t.a(2,this);case 8:throw t.p=8,u=t.v,console.log("HxPlayer日志-播放器初始化失败",u),Ld.error("HxPlayer日志-播放器初始化失败",{error:u&&u.message?u.message:String(u)}),u;case 9:return t.a(2)}},t,this,[[0,8]])})),function(){return t.apply(this,arguments)})},{key:"_call",value:function(e){for(var t=this,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return"destroy"===e?this.destroy():this.ready.then(function(){if(!t._destroyed&&t._player){var r=t._player[e];return"function"==typeof r?r.apply(t._player,n):void 0}})}},{key:"setPlaybackRate",value:function(e){return this._call("changeSpeed",{value:e})}},{key:"duration",value:function(){var e=this._player,t=e&&e.videoElm;return t?t.duration:NaN}},{key:"destroy",value:function(){this._destroyed=!0,this._player&&"function"==typeof this._player.destroy&&this._player.destroy(),this._player=null,this.containerId&&e._instances.get(this.containerId)===this&&e._instances.delete(this.containerId)}}]);var t}();v(Ly,"_instances",new Map),v(Ly,"_createSeq",new Map),Ly.VideoPlayer=gy,Ly.LivePlayer=ky,Ly.Hls=Jc,Ly.version="1.0.0","undefined"!=typeof window&&(window.HxPlayer=Ly),e.Hls=Jc,e.HxPlayer=Ly,e.LivePlayer=ky,e.VideoPlayer=gy,e.default=Ly,Object.defineProperty(e,"__esModule",{value:!0})}),"undefined"!=typeof globalThis&&globalThis.HxPlayer&&globalThis.HxPlayer.HxPlayer&&(globalThis.HxPlayer=globalThis.HxPlayer.default||globalThis.HxPlayer.HxPlayer);
120
2
  //# sourceMappingURL=hx-player.umd.js.map