stormcloud-video-player 0.3.12 → 0.3.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/stormcloud-vp.min.js +1 -1
- package/lib/index.cjs +32 -5
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +2 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +32 -5
- package/lib/index.js.map +1 -1
- package/lib/player/StormcloudVideoPlayer.cjs +32 -5
- package/lib/player/StormcloudVideoPlayer.cjs.map +1 -1
- package/lib/player/StormcloudVideoPlayer.d.cts +2 -0
- package/lib/players/HlsPlayer.cjs +32 -5
- package/lib/players/HlsPlayer.cjs.map +1 -1
- package/lib/players/index.cjs +32 -5
- package/lib/players/index.cjs.map +1 -1
- package/lib/sdk/hlsAdPlayer.cjs +17 -1
- package/lib/sdk/hlsAdPlayer.cjs.map +1 -1
- package/lib/ui/StormcloudVideoPlayer.cjs +32 -5
- package/lib/ui/StormcloudVideoPlayer.cjs.map +1 -1
- package/package.json +1 -1
|
@@ -7,4 +7,4 @@
|
|
|
7
7
|
*
|
|
8
8
|
* This source code is licensed under the MIT license found in the
|
|
9
9
|
* LICENSE file in the root directory of this source tree.
|
|
10
|
-
*/var c;s.exports;var u=(c||(c=1,s.exports=function(){if(i)return r;i=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function s(t,i,s){var r=null;if(void 0!==s&&(r=""+s),void 0!==i.key&&(r=""+i.key),"key"in i)for(var n in s={},i)"key"!==n&&(s[n]=i[n]);else s=i;return i=s.ref,{$$typeof:e,type:t,key:r,ref:void 0!==i?i:null,props:s}}return r.Fragment=t,r.jsx=s,r.jsxs=s,r}()),s.exports),f=h(),g=t(f);const m=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},p=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=y},y=Number.MAX_SAFE_INTEGER||9007199254740991;let v=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}({}),T=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.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_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.UNKNOWN="unknown",e}({}),E=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}({});var S="manifest",A="level",b="audioTrack",L="subtitleTrack",R="main",I="audio",k="subtitle";class P{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 w{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 P(e),this.fast_=new P(t),this.defaultTTFB_=s,this.ttfb_=new P(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new P(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new P(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new P(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,s=8*t/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}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(){}}function D(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function x(){return x=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},x.apply(null,arguments)}function C(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function _(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?C(Object(i),!0).forEach(function(t){D(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):C(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class M{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=O,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 O=function(){},F={trace:O,debug:O,log:O,warn:O,info:O,error:O};function N(){return x({},F)}function U(e,t,i){return t[e]?t[e].bind(t):function(e,t){const i=self.console[e];return i?i.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):O}(e,i)}const B=N();const $=B;function V(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function G(e,t){const i=Object.keys(e),s=Object.keys(t),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(e=>-1===s.indexOf(e))}function H(e,t=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(e);if(t){const e=i.indexOf("\0");return-1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}const i=e.length;let s,r,n,a="",o=0;for(;o<i;){if(s=e[o++],0===s&&t)return a;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((31&s)<<6|63&r);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((15&s)<<12|(63&r)<<6|63&n)}}return a}function K(e){let t="";for(let i=0;i<e.length;i++){let s=e[i].toString(16);s.length<2&&(s="0"+s),t+=s}return t}function j(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function W(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var q,Y={exports:{}};var z=(q||(q=1,function(e){var t,i,s,r,n;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var r=n.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return s.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):t;var o=n.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var h=o.path,c=h.substring(0,h.lastIndexOf("/")+1)+a.path;d.path=n.normalizePath(c)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=s.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(d)},parseURL:function(e){var i=t.exec(e);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(r,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=n}(Y)),Y.exports);class X{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}}}var Q="audio",J="video",Z="audiovideo";class ee{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const i=re(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let s;s=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Q]:null,[J]:null,[Z]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new X),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=z.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Q]=null,e[J]=null,e[Z]=null}}function te(e){return"initSegment"!==e.sn}class ie extends ee{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(m(e)&&m(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/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(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const i=this._decryptdata=t[e[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=m(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),i=e.length;if(i>1||1===i&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){m(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return te(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||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:n}}}class se extends ee{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function re(e,t){const i=Object.getPrototypeOf(e);if(i){const e=Object.getOwnPropertyDescriptor(i,t);return e||re(i,t)}}const ne=Math.pow(2,32)-1,ae=[].push,oe={video:1,audio:2,id3:3,text:4};function le(e){return String.fromCharCode.apply(null,e)}function de(e,t){const i=e[t]<<8|e[t+1];return i<0?65536+i:i}function he(e,t){const i=ue(e,t);return i<0?4294967296+i:i}function ce(e,t){let i=he(e,t);return i*=Math.pow(2,32),i+=he(e,t+4),i}function ue(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function fe(e,t){const i=[];if(!t.length)return i;const s=e.byteLength;for(let r=0;r<s;){const n=he(e,r),a=n>1?r+n:s;if(le(e.subarray(r+4,r+8))===t[0])if(1===t.length)i.push(e.subarray(r+8,a));else{const s=fe(e.subarray(r+8,a),t.slice(1));s.length&&ae.apply(i,s)}r=a}return i}function ge(e){const t=[],i=e[0];let s=8;const r=he(e,s);s+=4;let n=0,a=0;0===i?(n=he(e,s),a=he(e,s+4),s+=8):(n=ce(e,s),a=ce(e,s+8),s+=16),s+=2;let o=e.length+a;const l=de(e,s);s+=2;for(let i=0;i<l;i++){let i=s;const n=he(e,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return $.warn("SIDX has hierarchical references (not supported)"),null;const l=he(e,i);i+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:t}}function me(e){const t=[],i=fe(e,["moov","trak"]);for(let e=0;e<i.length;e++){const s=i[e],r=fe(s,["tkhd"])[0];if(r){let e=r[0];const i=he(r,0===e?12:20),n=fe(s,["mdia","mdhd"])[0];if(n){e=n[0];const r=he(n,0===e?12:20),a=fe(s,["mdia","hdlr"])[0];if(a){const e=le(a.subarray(8,12)),n={soun:Q,vide:J}[e],o=pe(fe(s,["mdia","minf","stbl","stsd"])[0]);n?(t[i]={timescale:r,type:n,stsd:o},t[n]=_({timescale:r,id:i},o)):t[i]={timescale:r,type:e,stsd:o}}}}}return fe(e,["moov","mvex","trex"]).forEach(e=>{const i=he(e,4),s=t[i];s&&(s.default={duration:he(e,12),flags:he(e,20)})}),t}function pe(e){const t=e.subarray(8),i=t.subarray(86),s=le(t.subarray(4,8));let r,n=s;const a="enca"===s||"encv"===s;if(a){const e=fe(t,[s])[0];fe(e.subarray("enca"===s?28:78),["sinf"]).forEach(e=>{const t=fe(e,["schm"])[0];if(t){const i=le(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=fe(e,["frma"])[0];t&&(n=le(t))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=fe(i,["avcC"])[0];e&&e.length>3&&(n+="."+Te(e[1])+Te(e[2])+Te(e[3]),r=ye("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const e=fe(t,[s])[0],i=fe(e.subarray(28),["esds"])[0];if(i&&i.length>7){let e=4;if(3!==i[e++])break;e=ve(i,e),e+=2;const t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=ve(i,e);const s=i[e++];if(64!==s)break;if(n+="."+Te(s),e+=12,5!==i[e++])break;e=ve(i,e);const r=i[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=fe(i,["hvcC"])[0];if(e&&e.length>12){const t=e[1],i=["","A","B","C"][t>>6],s=31&t,r=he(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+i+s,n+="."+function(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let e=l.length;e--;){const t=l[e];if(t||d){d="."+t.toString(16).toUpperCase()+d}}n+=d}r=ye("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ye(n,i)||n;break;case"vp09":{const e=fe(i,["vpcC"])[0];if(e&&e.length>6){const t=e[4],i=e[5],s=e[6]>>4&15;n+="."+Ee(t)+"."+Ee(i)+"."+Ee(s)}break}case"av01":{const e=fe(i,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,s=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,d=2===t&&o?l?12:10:o?10:8,h=(16&e[2])>>4,c=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],g=1,m=1,p=1,y=0;n+="."+t+"."+Ee(s)+a+"."+Ee(d)+"."+h+"."+c+u+f+"."+Ee(g)+"."+Ee(m)+"."+Ee(p)+"."+y,r=ye("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:r}}function ye(e,t){const i=fe(t,["dvvC"]),s=i.length?i[0]:fe(t,["dvcC"])[0];if(s){const t=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return e+"."+Ee(t)+"."+Ee(i)}}function ve(e,t){const i=t+5;for(;128&e[t++]&&t<i;);return t}function Te(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Ee(e){return(e<10?"0":"")+e}function Se(e,t){fe(e,["moov","trak"]).forEach(e=>{const i=fe(e,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let r=fe(s,["enca"]);const n=r.length>0;n||(r=fe(s,["encv"])),r.forEach(e=>{fe(n?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const i=Ae(e);i&&t(i,n)})})})}function Ae(e){const t=fe(e,["schm"])[0];if(t){const i=le(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=fe(e,["schi","tenc"])[0];if(t)return t}}}function be(e,t){const i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function Le(e,t){const i=[],s=t.samples,r=t.timescale,n=t.id;let a=!1;return fe(s,["moof"]).map(o=>{const l=o.byteOffset-8;fe(o,["traf"]).map(o=>{const d=fe(o,["tfdt"]).map(e=>{const t=e[0];let i=he(e,4);return 1===t&&(i*=Math.pow(2,32),i+=he(e,8)),i/r})[0];return void 0!==d&&(e=d),fe(o,["tfhd"]).map(d=>{const h=he(d,4),c=16777215&he(d,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;h===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=he(d,p),p+=4),f&&(g=he(d,p),p+=4),m&&(p+=4),"video"===t.type&&(a=Re(t.codec)),fe(o,["trun"]).map(n=>{const o=n[0],d=16777215&he(n,0),h=!!(1&d);let c=0;const f=!!(4&d),m=!!(256&d);let p=0;const y=!!(512&d);let v=0;const T=!!(1024&d),E=!!(2048&d);let S=0;const A=he(n,4);let b=8;h&&(c=he(n,b),b+=4),f&&(b+=4);let L=c+l;for(let l=0;l<A;l++){if(m?(p=he(n,b),b+=4):p=u,y?(v=he(n,b),b+=4):v=g,T&&(b+=4),E&&(S=0===o?he(n,b):ue(n,b),b+=4),t.type===J){let t=0;for(;t<v;){const n=he(s,L);if(L+=4,Ie(a,s[L])){ke(s.subarray(L,L+n),a?2:1,e+S/r,i)}L+=n,t+=n+4}}e+=p/r}}))})})}),i}function Re(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Ie(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function ke(e,t,i,s){const r=Pe(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){$.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=de(r,t);if(t+=2,49===e){const e=he(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let e=1;e<l;e++)d[e]=r[t++]}s.push({type:e,payloadType:a,pts:i,bytes:d})}}}}}else if(5===a&&o>16){const e=[];for(let i=0;i<16;i++){const s=r[t++].toString(16);e.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=r[t++];s.push({payloadType:a,pts:i,uuid:e.join(""),userData:H(l),userDataBytes:l})}}}function Pe(e){const t=e.byteLength,i=[];let s=1;for(;s<t-2;)0===e[s]&&0===e[s+1]&&3===e[s+2]?(i.push(s+2),s+=2):s++;if(0===i.length)return e;const r=t-i.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===i[0]&&(a++,i.shift()),n[s]=e[a];return n}function we(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");let s,r,n;s=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){const i=t.length;let s=8,r=i;for(;r--;)s+=t[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),r=0,s=8;r<i;r++)n.set(t[r],s),s+=t[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,i)}function De(e){const t=e.getUint32(0),i=e.byteOffset,s=e.byteLength;if(s<t)return{offset:i,size:s};if(1886614376!==e.getUint32(4))return{offset:i,size:t};const r=e.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:t};const n=e.buffer,a=K(new Uint8Array(n,i+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=e.getUint32(28);if(!r||s<32+16*r)return{offset:i,size:t};o=[];for(let e=0;e<r;e++)o.push(new Uint8Array(n,i+32+16*e,16));d=32+16*r}if(!d)return{offset:i,size:t};const h=e.getUint32(d);return t-32<h?{offset:i,size:t}:(l=new Uint8Array(n,i+d+4,h),{version:r,systemId:a,kids:o,data:l,offset:i,size:t})}const xe=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ce={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function _e(e,t){const i=Ce[t];return!!i&&!!i[e.slice(0,4)]}function Me(e,t,i=!0){return!e.split(",").some(e=>!Oe(e,t,i))}function Oe(e,t,i=!0){var s;const r=V(i);return null!=(s=null==r?void 0:r.isTypeSupported(Fe(e,t)))&&s}function Fe(e,t){return`${t}/mp4;codecs=${e}`}function Ne(e){if(e){const t=e.substring(0,4);return Ce.video[t]}return 2}function Ue(e){const t=xe();return e.split(",").reduce((e,i)=>{const s=t&&Re(i)?9:Ce.video[i];return s?(2*s+e)/(e?3:2):(Ce.audio[i]+e)/(e?2:1)},0)}const Be={};const $e=/flac|opus|mp4a\.40\.34/i;function Ve(e,t=!0){return e.replace($e,e=>function(e,t=!0){if(Be[e])return Be[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<i.length;r++){var s;if(Oe(i[r],"audio",t))return Be[e]=i[r],i[r];if("mp3"===i[r]&&null!=(s=V(t))&&s.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function Ge(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(He(e,"audio")||He(e,"video")))return e;if(t){const i=t.split(",");if(i.length>1){if(e)for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t];return i[0]}}return t||e}function He(e,t){return _e(e,t)&&Oe(e,t)}function Ke(e){if(e.startsWith("av01.")){const t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}function je(e){const t=V(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function We(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const qe={supported:!1,smooth:!1,powerEfficient:!1},Ye={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function ze(e,t){return{supported:!1,configurations:t,decodingInfoResults:[qe],error:e}}function Xe(e,t,i,s,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,h=d?parseInt(d):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,i)=>{if(i){const s=t.groups[i];if(!s)throw new Error(`Audio track group ${i} not found`);Object.keys(s.channels).forEach(t=>{e[t]=(e[t]||0)+s.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some(e=>Re(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(s,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(r,8e6))||!!c&&m(h)&&Object.keys(c).some(e=>parseInt(e)>h)}function Qe(e,t,i,s={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!i)return Promise.resolve(Ye);const n=[],a=function(e){var t;const i=null==(t=e.videoCodec)?void 0:t.split(","),s=Ze(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return i?i.map(e=>{const t={contentType:Fe(Ke(e),"video"),width:r,height:n,bitrate:s,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,i){var s;const r=null==(s=e.audioCodec)?void 0:s.split(","),n=Ze(e);if(r&&e.audioGroups)return e.audioGroups.reduce((e,s)=>{var a;const o=s?null==(a=t.groups[s])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===s){const s=parseFloat(t.channels||"");r.forEach(t=>{const r={contentType:Fe(t,"audio"),bitrate:i?Je(t,n):n};s&&(r.channels=""+s),e.push(r)})}return e},e):e},[]);return[]}(e,t,o>0),d=l.length;for(let e=o||1*d||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),d){t.audio=l[e%d];const i=t.audio.bitrate;t.video&&i&&(t.video.bitrate-=i)}n.push(t)}if(r){const e=navigator.userAgent;if(r.split(",").some(e=>Re(e))&&xe())return Promise.resolve(ze(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map(e=>{const t=function(e){let t="";const{audio:i,video:s}=e;if(s){t+=`${We(s.contentType)}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){t+=`${s?"_":""}${We(i.contentType)}_c${i.channels}`}return t}(e);return s[t]||(s[t]=i.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:n,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e}))}function Je(e,t){if(t<=1)return 1;let i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}function Ze(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}const et=["NONE","TYPE-0","TYPE-1",null];const tt=["SDR","PQ","HLG"];var it="",st="YES",rt="v2";function nt(e){const{canSkipUntil:t,canSkipDateRanges:i,age:s}=e;return t&&s<t/2?i?rt:st:it}class at{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 void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class ot{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return lt(this._audioGroups,e)}hasSubtitleGroup(e){return lt(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.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 null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function lt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function dt(e,t){let i=!1,s=[];if(e&&(i="SDR"!==e,s=[e]),t){s=t.allowedVideoRanges||tt.slice(0);const e="SDR"!==s.join("")&&!t.videoCodec;i=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}const ht=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(i,s)=>{if(e&&(s=e(i,s)),"object"==typeof s&&null!==s){if(t.has(s))return;t.add(s)}return s}})(t));function ct(e,t){$.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function ut(e){return e.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 ft(e){if(!e)return e;const{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}=e;return{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function gt(e,t,i){if("attrs"in e){const i=t.indexOf(e);if(-1!==i)return i}for(let s=0;s<t.length;s++){if(mt(e,t[s],i))return s}return-1}function mt(e,t,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===s||t.groupId===s)&&(void 0===r||t.name===r)&&(void 0===n||function(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const i=e.split(","),s=t.split(",");return i.length===s.length&&!i.some(e=>-1===s.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function pt(e,t){const{audioCodec:i,channels:s}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(t.channels||"2"))}function yt(e,t,i){for(let s=t;s>-1;s--)if(i(e[s]))return s;for(let s=t+1;s<e.length;s++)if(i(e[s]))return s;return-1}function vt(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}const Tt=function(e,t){let i=0,s=e.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=e[r];const a=t(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function Et(e,t,i=0,s=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const s=e.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===St(i,s,n)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const s=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),i);return e.start<=s}return!1}(n,e,Math.min(r,s))))return n;const a=Tt(t,St.bind(null,i,s));return!a||a===e&&n?n:a}function St(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=e?1:i.start-s>e&&i.start?-1:0}function At(e,t,i){const s=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>e}function bt(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){let s=e.fragments;const{fragmentHint:r}=e;let n;return r&&(s=s.concat(r)),Tt(s,e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=i?1:e.start>i?-1:0)),n||null}return null}function Lt(e){switch(e.details){case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_TIMEOUT:case T.LEVEL_LOAD_TIMEOUT:case T.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Rt(e){return e.details.startsWith("key")}function It(e){return Rt(e)&&!!e.frag&&!e.frag.decryptdata}function kt(e,t){const i=Lt(t);return e.default[(i?"timeout":"error")+"Retry"]}function Pt(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function wt(e){return _(_({},e),{errorRetry:null,timeoutRetry:null})}function Dt(e,t,i,s){if(!e)return!1;const r=null==s?void 0:s.code,n=t<e.maxNumRetry&&(function(e){return xt(e)||!!e&&(e<400||e>499)}(r)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,s,n):n}function xt(e){return 0===e&&!1===navigator.onLine}var Ct=0,_t=2,Mt=3,Ot=5,Ft=0,Nt=1,Ut=2,Bt=4;function $t(e){const t={action:Ct,flags:Ft};return e&&(t.resolved=!0),t}var Vt="NOT_LOADED",Gt="APPENDING",Ht="PARTIAL",Kt="OK";class jt{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.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 t=i.length;t--;){const s=i[t];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){const a=s[r[n]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,s,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(s=>{const a=this.fragments[s];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===i&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some(e=>{const i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(a.body),i}):this.removeFragment(a.body))})}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const i=e.frag,s=qt(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const n=!i.relurl;if(Object.keys(t).forEach(s=>{const a=i.elementaryStreams[s];if(!a)return;const o=t[s],l=n||!0===a.partial;r.range[s]=this.getBufferedTimes(i,e.part,l,o)}),r.loaded=null,Object.keys(r.range).length){r.buffered=!0;(r.body.endList=i.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),Wt(r)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(r.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=Yt(i,t=>t.fragment.sn>=e))}fragBuffered(e,t){const i=qt(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const r={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<s.length;e++){const t=s.start(e)-this.bufferPadding,i=s.end(e)+this.bufferPadding;if(l>=t&&o<=i){r.time.push({startPTS:Math.max(n,s.start(e)),endPTS:Math.min(a,s.end(e))});break}if(n<i&&a>t){const t=Math.max(n,s.start(e)),i=Math.min(a,s.end(e));i>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:i}))}else if(a<=t)break}return r}getPartialFragment(e){let t,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&Wt(d)&&(i=d.body.start-a,s=d.body.end+a,e>=i&&e<=s&&(t=Math.min(e-i,s-e),n<=t&&(r=d.body,n=t)))}),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||Wt(t))}getState(e){const t=qt(e),i=this.fragments[t];return i?i.buffered?Wt(i)?Ht:Kt:Gt:Vt}isTimeBuffered(e,t,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,r=qt(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:r,type:n}=t;if("initSegment"===i.sn)return;const a=i.type;if(s){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(s)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=qt(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 r=t[i[s]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=qt(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const t=e.sn;this.activePartLists[e.type]=Yt(i,e=>e.fragment.sn!==t)}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=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function Wt(e){var t,i,s;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(s=e.range.audiovideo)&&s.partial)}function qt(e){return`${e.type}_${e.level}_${e.sn}`}function Yt(e,t){return e.filter(e=>{const i=t(e);return i||e.clearElementaryStreamInfo(),i})}var zt=0,Xt=1;class Qt{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 zt:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Xt:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Jt{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 e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;const o=u[f],m=u[o],p=u[m];let y=257*u[i]^16843008*i;s[f]=y<<24|y>>>8,r[f]=y<<16|y>>>16,n[f]=y<<8|y>>>24,a[f]=y,y=16843009*p^65537*m^257*o^16843008*f,l[i]=y<<24|y>>>8,d[i]=y<<16|y>>>16,h[i]=y<<8|y>>>24,c[i]=y,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=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 r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let y,v;for(a=0;a<n;a++)a<r?y=l[a]=t[a]:(v=y,a%r===0?(v=v<<8|v>>>24,v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[255&v],v^=c[a/r|0]<<24):r>6&&a%r===4&&(v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[255&v]),l[a]=y=(l[a-r]^v)>>>0);for(o=0;o<n;o++)a=n-o,v=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?v:f[h[v>>>24]]^g[h[v>>>16&255]]^m[h[v>>>8&255]]^p[h[255&v]],d[o]=d[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],c=this.uint8ArrayToUint32Array_(i);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(e),y=new Int32Array(p.length);let v,T,E,S,A,b,L,R,I,k,P,w,D,x;const C=this.networkToHostOrderSwap;for(;t<p.length;){for(I=C(p[t]),k=C(p[t+1]),P=C(p[t+2]),w=C(p[t+3]),A=I^r[0],b=w^r[1],L=P^r[2],R=k^r[3],D=4,x=1;x<s;x++)v=o[A>>>24]^l[b>>16&255]^d[L>>8&255]^h[255&R]^r[D],T=o[b>>>24]^l[L>>16&255]^d[R>>8&255]^h[255&A]^r[D+1],E=o[L>>>24]^l[R>>16&255]^d[A>>8&255]^h[255&b]^r[D+2],S=o[R>>>24]^l[A>>16&255]^d[b>>8&255]^h[255&L]^r[D+3],A=v,b=T,L=E,R=S,D+=4;v=n[A>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&R]^r[D],T=n[b>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[255&A]^r[D+1],E=n[L>>>24]<<24^n[R>>16&255]<<16^n[A>>8&255]<<8^n[255&b]^r[D+2],S=n[R>>>24]<<24^n[A>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^r[D+3],y[t]=C(v^u),y[t+1]=C(S^f),y[t+2]=C(E^g),y[t+3]=C(T^m),u=I,f=k,g=P,m=w,t+=4}return y.buffer}}class Zt{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=function(e){switch(e){case zt:return"AES-CBC";case Xt:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class ei{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}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);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?e.slice(0,t-i):e}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==zt||16!==t.byteLength)return $.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=be(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Jt),l.expandKey(t);const d=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new Zt(this.subtle,t,s)}return this.fastAesKey.expandKey().then(t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Qt(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,t)}).catch(r=>($.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&($.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const ti=Math.pow(2,17);class ii{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){const i=e.url;if(!i)return Promise.reject(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void o(ri(e));e.gap=!1}const l=this.loader=r?new r(s):new n(s),d=si(e);e.loader=l;const h=wt(s.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:ti};e.stats=l.stats;const u={onSuccess:(t,i,s,r)=>{this.resetLoader(e,l);let n=t.data;s.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,s,r,n)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:_({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:n}))},onAbort:(t,i,s)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:(t,i,s)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:s,stats:t}))}};t&&(u.onProgress=(i,s,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})),l.load(d,c,u)})}loadPart(e,t,i){this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(ri(e,t));const l=this.loader=r?new r(s):new n(s),d=si(e,t);e.loader=l;const h=wt(s.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ti};t.stats=l.stats,l.load(d,c,{onSuccess:(s,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const d={frag:e,part:t,payload:s.data,networkDetails:o};i(d),a(d)},onError:(i,s,r,n)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:_({url:d.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:r,stats:n}))},onAbort:(i,s,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:i}))},onTimeout:(i,s,r)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:i}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(e.duration/t.duration),n=Math.min(Math.round(i.loaded/r),s),a=(s-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function si(e,t=null){const i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(m(r)&&m(n)){var a;let t=r,i=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-r;e%16&&(i=n+(16-e%16)),0!==r&&(s.resetIV=!0,t=r-16)}s.rangeStart=t,s.rangeEnd=i}var o;return s}function ri(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:v.MEDIA_ERROR,details:T.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(s.part=t),(t||e).stats.aborted=!0,new ni(s)}class ni extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class ai extends M{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&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class oi{constructor(e,t,i,s=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=n}}const li={length:0,start:()=>0,end:()=>0};class di{static isBuffered(e,t){if(e){const i=di.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=di.getBuffered(e);return di.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=di.bufferedRanges(e);if(s.length)return di.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((e,t)=>e.start-t.start||t.end-e.end);let s=-1,r=[];if(i)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(s=n);const a=r.length;if(a){const t=r[a-1].end;e[n].start-t<i?e[n].end>t&&(r[a-1].end=e[n].end):r.push(e[n])}else r.push(e[n])}else r=e;let n,a=0,o=t,l=t;for(let e=0;e<r.length;e++){const d=r[e].start,h=r[e].end;if(-1===s&&t>=d&&t<=h&&(s=e),t+i>=d&&t<h)o=d,l=h,a=l-t;else if(t+i<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||li}catch(e){return $.log("failed to get media.buffered",e),li}}}const hi=/\{\$([a-zA-Z0-9-_]+)\}/g;function ci(e){return hi.test(e)}function ui(e,t){if(null!==e.variableList||e.hasVariableRefs){const i=e.variableList;return t.replace(hi,t=>{const s=t.substring(2,t.length-1),r=null==i?void 0:i[s];return void 0===r?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),t):r})}return t}function fi(e,t,i){let s,r,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){s=t.QUERYPARAM;try{const e=new self.URL(i).searchParams;if(!e.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=e.get(s)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else s=t.NAME,r=t.VALUE;s in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function gi(e,t,i){const s=t.IMPORT;if(i&&s in i){let t=e.variableList;t||(e.variableList=t={}),t[s]=i[s]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const mi=/^(\d+)x(\d+)$/,pi=/(.+?)=(".*?"|.*?)(?:,|$)/g;class yi{constructor(e,t){"string"==typeof e&&(e=yi.parseAttrList(e,t)),x(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}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=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+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((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=mi.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const s={};for(pi.lastIndex=0;null!==(i=pi.exec(e));){const r=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=ui(t,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":$.warn(`${e}: attribute ${r} is missing quotes`)}s[r]=n}return s}}function vi(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function Ti(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class Ei{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=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(s=null==t?void 0:t.tagOrder)?s:i,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){$.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=x(new yi({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);m(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const 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}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?($.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 null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(m(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"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&m(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class Si{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);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||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):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&&m(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&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 null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&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 Ai(e,t){return e.length===t.length&&!e.some((e,i)=>e!==t[i])}function bi(e,t){return!e&&!t||!(!e||!t)&&Ai(e,t)}function Li(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Ri(e){switch(e){case"AES-128":case"AES-256":return zt;case"AES-256-CTR":return Xt;default:throw new Error(`invalid full segment method ${e}`)}}function Ii(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function ki(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function Pi(e){const t=function(e,t,i){const s=e[t];e[t]=e[i],e[i]=s};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function wi(e){const t=e.split(":");let i=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),s=e[e.length-1].split(",");if(2===s.length){const t="base64"===s[0],r=s[1];t?(e.splice(-1,1),i=Ii(r)):i=function(e){const t=ki(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(r)}}return i}const Di="undefined"!=typeof self?self:void 0;var xi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ci="org.w3.clearkey",_i="com.apple.streamingkeydelivery",Mi="com.microsoft.playready",Oi="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Fi(e){switch(e){case _i:return xi.FAIRPLAY;case Mi:return xi.PLAYREADY;case Oi:return xi.WIDEVINE;case Ci:return xi.CLEARKEY}}function Ni(e){switch(e){case xi.FAIRPLAY:return _i;case xi.PLAYREADY:return Mi;case xi.WIDEVINE:return Oi;case xi.CLEARKEY:return Ci}}function Ui(e){const{drmSystems:t,widevineLicenseUrl:i}=e,s=t?[xi.FAIRPLAY,xi.WIDEVINE,xi.PLAYREADY,xi.CLEARKEY].filter(e=>!!t[e]):[];return!s[xi.WIDEVINE]&&i&&s.push(xi.WIDEVINE),s}const Bi=null!=Di&&null!=($i=Di.navigator)&&$i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var $i;function Vi(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),s=i.substring(i.indexOf("<"),i.length),r=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(e){const t=Ii(e).subarray(0,16);return Pi(t),t}}return null}let Gi={};class Hi{static clearKeyUriToKeyIdMap(){Gi={}}static setKeyIdForUri(e,t){Gi[e]=t}constructor(e,t,i,s=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!Li(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(j(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Ai(e.keyFormatVersions,this.keyFormatVersions)&&bi(e.iv,this.iv)&&bi(e.keyId,this.keyId)}isSupported(){if(this.method){if(Li(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case _i:case Oi:case Mi:case Ci:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Li(this.method)){let t=this.iv;t||("number"!=typeof e&&($.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e));return new Hi(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){const e=Gi[this.uri];if(e&&!Ai(this.keyId,e)&&Hi.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=wi(this.uri);if(i)switch(this.keyFormat){case Oi:if(this.pssh=i,!this.keyId){const e=function(e){const t=[];if(e instanceof ArrayBuffer){const i=e.byteLength;let s=0;for(;s+32<i;){const i=De(new DataView(e,s));t.push(i),s+=i.size}}return t}(i.buffer);if(e.length){var s;const t=e[0];this.keyId=null!=(s=t.kids)&&s.length?t.kids[0]:null}}this.keyId||(this.keyId=Ki(t));break;case Mi:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=we(e,0,i),this.keyId=Vi(i);break}default:{let e=i.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=function(e){const t=null==e?void 0:e[Oi];if(t)return t.keyId;return null}(t),e||(e=Ki(t),e||(e=Gi[this.uri])),e&&(this.keyId=e,Hi.setKeyIdForUri(this.uri,e))}return this}}function Ki(e){const t=null==e?void 0:e[Mi];if(t){const e=wi(t.uri);if(e)return Vi(e)}return null}const ji=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Wi=/#EXT-X-MEDIA:(.*)/g,qi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Yi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),zi=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Xi{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 z.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return qi.test(e)}static parseMasterPlaylist(e,t){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:ci(e)},s=[];if(ji.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=ji.exec(e));)if(r[1]){var n;const e=new yi(r[1],i),a=ui(i,r[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Xi.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),ts(e.CODECS,o);const d=e["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},ts(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||s.push(o),i.levels.push(o)}else if(r[3]){const e=r[3],s=r[4];switch(e){case"SESSION-DATA":{const e=new yi(s,i),t=e["DATA-ID"];t&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[t]=e);break}case"SESSION-KEY":{const e=Zi(s,t,i);e.encrypted&&e.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(e)):$.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${s}"`);break}case"DEFINE":fi(i,new yi(s,i),t);break;case"CONTENT-STEERING":{const e=new yi(s,i);i.contentSteering={uri:Xi.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=es(s)}}const a=s.length>0&&s.length<i.levels.length;return i.levels=a?s:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,i){let s;const r={},n=i.levels,a={AUDIO:n.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:n.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(Wi.lastIndex=0;null!==(s=Wi.exec(e));){const e=new yi(s[1],i),n=e.TYPE;if(n){const i=a[n],s=r[n]||[];r[n]=s;const l=e.LANGUAGE,d=e["ASSOC-LANGUAGE"],h=e.CHANNELS,c=e.CHARACTERISTICS,u=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?Xi.resolve(e.URI,t):""};if(d&&(f.assocLang=d),h&&(f.channels=h),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=i&&i.length){const e=Xi.findGroup(i,f.groupId)||i[0];is(f,e,"audioCodec"),is(f,e,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(e,t,i,s,r,n){var a;const o={url:t},l=new Si(t),d=l.fragments,h=[];let c,u,f,g,p=null,y=0,v=0,T=0,E=0,S=0,A=null,b=new ie(s,o),L=-1,R=!1,I=null;if(Yi.lastIndex=0,l.m3u8=e,l.hasVariableRefs=ci(e),"#EXTM3U"!==(null==(a=Yi.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=Yi.exec(e));){R&&(R=!1,b=new ie(s,o),b.playlistOffset=T,b.setStart(T),b.sn=y,b.cc=E,S&&(b.bitrate=S),b.level=i,p&&(b.initSegment=p,p.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),I&&(b.setByteRange(I),I=null)));const e=c[1];if(e){b.duration=parseFloat(e);const t=(" "+c[2]).slice(1);b.title=t||null,b.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(m(b.duration)){b.playlistOffset=T,b.setStart(T),f&&ns(b,f,l),b.sn=y,b.level=i,b.cc=E,d.push(b);const e=(" "+c[3]).slice(1);b.relurl=ui(l,e),ss(b,A,h),A=b,T+=b.duration,y++,v=0,R=!0}}else{if(c=c[0].match(zi),!c){$.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const e=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(e){case"BYTERANGE":A?b.setByteRange(r,A):b.setByteRange(r);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=r,b.tagList.push(["PROGRAM-DATE-TIME",r]),-1===L&&(L=d.length);break;case"PLAYLIST-TYPE":l.type&&as(l,e,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?as(l,e,c):d.length>0&&os(l,e,c),y=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&as(l,e,c);const t=new yi(r,l),i=t.decimalInteger("SKIPPED-SEGMENTS");if(m(i)){l.skippedSegments+=i;for(let e=i;e--;)d.push(null);y+=i}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&as(l,e,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&as(l,e,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||as(l,e,c),l.live=!1;break;case"#":(r||a)&&b.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":E++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([e]);break;case"BITRATE":b.tagList.push([e,r]),S=1e3*parseInt(r),m(S)?b.bitrate=S:S=0;break;case"DATERANGE":{const e=new yi(r,l),t=new Ei(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:$.warn(`Ignoring invalid DATERANGE tag: "${r}"`),b.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const e=new yi(r,l);"IMPORT"in e?gi(l,e,n):fi(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?as(l,e,c):d.length>0&&os(l,e,c),l.startCC=E=parseInt(r);break;case"KEY":{const e=Zi(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=x({},f)),f[e.keyFormat]=e)}else $.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=es(r);break;case"MAP":{const e=new yi(r,l);if(b.duration){const t=new ie(s,o);rs(t,e,i,f),p=t,b.initSegment=p,p.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime)}else{const t=b.byteRangeEndOffset;if(t){const e=b.byteRangeStartOffset;I=`${t-e}@${e}`}else I=null;rs(b,e,i,f),p=b,R=!0}p.cc=E;break}case"SERVER-CONTROL":g&&as(l,e,c),g=new yi(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&as(l,e,c);const t=new yi(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,i=v++,s=new yi(r,l),n=new se(s,b,o,i,t);e.push(n),b.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new yi(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new yi(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:$.warn(`line parsed but not handled: ${c}`)}}}A&&!A.relurl?(d.pop(),T-=A.duration,l.partList&&(l.fragmentHint=A)):l.partList&&(ss(b,A,h),b.cc=E,l.fragmentHint=b,f&&ns(b,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const k=d.length,P=d[0],w=d[k-1];if(T+=l.skippedSegments*l.targetduration,T>0&&k&&w){l.averagetargetduration=T/k;const e=w.sn;l.endSN="initSegment"!==e?e:0,l.live||(w.endList=!0),L>0&&(!function(e,t){let i=e[t];for(let s=t;s--;){const t=e[s];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(d,L),P&&h.unshift(P))}return l.fragmentHint&&(T+=l.fragmentHint.duration),l.totalduration=T,h.length&&l.dateRangeTagCount&&P&&Qi(h,l),l.endCC=E,l}}function Qi(e,t){let i=e.length;if(!i){if(!t.hasProgramDateTime)return;{const s=t.fragments[t.fragments.length-1];e.push(s),i++}}const s=e[i-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let s=i;s--;){var a;if((null==(a=e[s])?void 0:a.sn)<t.startSN)break;const i=Ji(t,d,e,s,r);if(-1!==i){l.tagAnchor=t.fragments[i].ref;break}}}}function Ji(e,t,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(t>=o||0===s){var a;if(t<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||r)-n.start)){const r=i[s].sn-e.startSN;if(r<0)return-1;const n=e.fragments;if(n.length>i.length){for(let a=(i[s+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return r}}}return-1}function Zi(e,t,i){var s,r;const n=new yi(e,i),a=null!=(s=n.METHOD)?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&$.error(`Invalid IV: ${n.IV}`);const c=o?Xi.resolve(o,t):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Hi(a,c,h,u,l,n.KEYID)}function es(e){const t=new yi(e).decimalFloatingPoint("TIME-OFFSET");return m(t)?t:null}function ts(e,t){let i=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{const s=i.filter(t=>_e(t,e));s.length&&(t[`${e}Codec`]=s.map(e=>e.split("/")[0]).join(","),i=i.filter(e=>-1===s.indexOf(e)))}),t.unknownCodecs=i}function is(e,t,i){const s=t[i];s&&(e[i]=s)}function ss(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function rs(e,t,i,s){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",s&&(e.levelkeys=s),e.initSegment=null}function ns(e,t,i){e.levelkeys=t;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||s.push(e)}function as(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function os(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function ls(e,t){const i=t.startPTS;if(m(i)){let s,r=0;t.sn>e.sn?(r=i-e.start,s=e):(r=e.start-i,s=t),s.duration!==r&&s.setDuration(r)}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 ds(e,t,i,s,r,n,a){s-i<=0&&(a.warn("Fragment should have a positive duration",t),s=i+t.duration,n=r+t.duration);let o=i,l=s;const d=t.startPTS,h=t.endPTS;if(m(d)){const c=Math.abs(d-i);e&&c>e.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${t.level} ${e.url}`):m(t.deltaPTS)?t.deltaPTS=Math.max(c,t.deltaPTS):t.deltaPTS=c,o=Math.max(i,d),i=Math.min(i,d),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,l=Math.min(s,h),s=Math.max(s,h),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const c=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(s-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=r,t.endPTS=s,t.minEndPTS=l,t.endDTS=n;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let f;const g=u-e.startSN,p=e.fragments;for(p[g]=t,f=g;f>0;f--)ls(p[f],p[f-1]);for(f=g;f<p.length-1;f++)ls(p[f],p[f+1]);return e.fragmentHint&&ls(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function hs(e,t,i){if(e===t)return;let s=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){s=t;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){const s=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(s?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=r;d<=n;d++){const r=l[a+d];let n=o[d];if(s&&!n&&r&&(n=t.fragments[d]=r),r&&n){i(r,n,d,o);const s=r.relurl,a=n.relurl;if(s&&Ts(s,a))return void(t.playlistParsingError=cs(`media sequence mismatch ${n.sn}:`,e,t,r,n));if(r.cc!==n.cc)return void(t.playlistParsingError=cs(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,e,t,r,n))}}}(e,t,(e,i,r,a)=>{if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){const s=e.cc-i.cc;for(let e=r;e<a.length;e++)a[e].cc+=s;t.endCC=a[a.length-1].cc}m(e.startPTS)&&m(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(n=i),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.initSegment=e.initSegment,s=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(s&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=s)?void 0:t.relurl)||(e.initSegment=s)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){const{dateRanges:s,recentlyRemovedDateranges:r}=t,n=x({},e);r&&r.forEach(e=>{delete n[e]});const a=Object.keys(n).length;if(!a)return s;return Object.keys(s).forEach(e=>{const t=n[e],r=new Ei(s[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ht(s[e].attr)}"`)}),n}(e.dateRanges,t,i));const s=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&ss(o[e],o[e-1],s);Qi(s,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const i=ms(e,t.startSN-1);t.startCC=null!=(l=null==i?void 0:i.cc)?l:a[0].cc}!function(e,t,i){if(e&&t){let s=0;for(let r=0,n=e.length;r<=n;r++){const n=e[r],a=t[r+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):s--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),n?ds(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,i):us(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const e=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=e),t.driftEndTime=d,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function cs(e,t,i,s,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function us(e,t,i=!0){const s=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+s*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}fs(t,a)}function fs(e,t){if(t){const i=e.fragments;for(let s=e.skippedSegments;s<i.length;s++)i[s].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function gs(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const s=e.fragments,r=4;if(s.length&&i*r>t){const e=1e3*s[s.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}function ms(e,t,i){if(!e)return null;let s=e.fragments[t-e.startSN];return s||(s=e.fragmentHint,s&&s.sn===t?s:t<e.startSN&&i&&i.sn===t?i:null)}function ps(e,t,i){return e?ys(e.partList,t,i):null}function ys(e,t,i){if(e)for(let s=e.length;s--;){const r=e[s];if(r.index===i&&r.fragment.sn===t)return r}return null}function vs(e){e.forEach((e,t)=>{var i;null==(i=e.details)||i.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function Ts(e,t){return!(e===t||!t)&&Es(e)!==Es(t)}function Es(e){return e.replace(/\?[^?]*$/,"")}function Ss(e,t){for(let s=0,r=e.length;s<r;s++){var i;if((null==(i=e[s])?void 0:i.cc)===t)return e[s]}return null}function As(e,t){const i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function bs(e,t){const i=t.fragments;for(let t=0,s=i.length;t<s;t++)As(i[t],e);t.fragmentHint&&As(t.fragmentHint,e),t.alignedSliding=!0}function Ls(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const i=Math.min(t.endCC,e.endCC),s=Ss(t.fragments,i),r=Ss(e.fragments,i);if(!s||!r)return;$.log(`Aligning playlist at start of dicontinuity sequence ${i}`);bs(s.start-r.start,e)}function Rs(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,s=t.fragments;if(!i.length||!s.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=Ss(s,a),n=Ss(i,a)),r&&n||(r=s[Math.floor(s.length/2)],n=Ss(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;bs((l-o)/1e3-(n.start-r.start),e)}function Is(e,t,i){ks(e,t,i),e.addEventListener(t,i)}function ks(e,t,i){e.removeEventListener(t,i)}const Ps=function(e){let t="";const i=e.length;for(let s=0;s<i;s++)t+=`[${e.start(s).toFixed(3)}-${e.end(s).toFixed(3)}]`;return t},ws="STOPPED",Ds="IDLE",xs="KEY_LOADING",Cs="FRAG_LOADING",_s="FRAG_LOADING_WAITING_RETRY",Ms="WAITING_TRACK",Os="PARSING",Fs="PARSED",Ns="ENDED",Us="ERROR",Bs="WAITING_INIT_PTS",$s="WAITING_LEVEL";class Vs extends ai{constructor(e,t,i,s,r){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ws,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:r}=this,n=i?i.currentTime:0,a=di.bufferInfo(s||i,n,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${m(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===Ns)this.resetLoadingState();else if(t){const i=e.maxFragLookUpTolerance,s=t.start-i,r=t.start+t.duration+i;if(o||r<a.start||s>a.end){const e=n>r;(n<s||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===Ds&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new ii(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ei(e.config)}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===ws)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const 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=ws}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=di.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>s&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return di.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;Is(i,"seeking",this.onMediaSeeking),Is(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===ws&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(null!==s){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ks(s,"seeking",this.onMediaSeeking),ks(s,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ws,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){this._doFragLoad(e,t,i,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,i=e.frag;this.fragContextChanged(i)?(t===Cs||!this.fragCurrent&&t===Os)&&(this.fragmentTracker.removeFragment(i),this.state=Ds):("payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(E.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==ws&&this.state!==Us&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Gt){const t=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,s?s.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ht&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(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(E.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e}).then(e=>{const{hls:t}=this,{frag:i,payload:s}=e,r=i.decryptdata;if(s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&Li(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,Ri(r.method)).catch(e=>{throw t.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e}).then(s=>{const r=self.performance.now();return t.trigger(E.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:n,tdecrypt:r}}),e.payload=s,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==ws&&this.state!==Us&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==ws&&(this.state=Ds),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,s;const r=e.tracks;if(r&&!t.encrypted&&(null!=(i=r.audio)&&i.encrypted||null!=(s=r.video)&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(i.message),!e||e.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}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?Ps(di.getBuffered(i)):"(detached)"})`),te(e)){var s;if(e.type!==k){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=Ds)}const t=null==(s=this.levels)?void 0:s[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=Ds}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:r}=e,n=!r||0===r.length||r.some(e=>!e),a=new oi(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=xs,this.fragCurrent=e,a=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(E.KEY_LOADED,e),this.state===xs&&(this.state=Ds),e}),this.hls.trigger(E.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(te(e)&&(!o||e.sn!==o.sn)){const i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts&&te(e)){const r=n.partList;if(r&&s){i>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(r,e,i);if(o>-1){const l=r[o];let d;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Cs,d=a?a.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,s)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,l,t,s).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(r,i))return Promise.resolve(null)}}var l;if(te(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),m(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Cs;const d=this.config.progressive;let h;return h=d&&a?a.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,s)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,d?s:void 0),a]).then(([e])=>(!d&&s&&s(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,i,s){return new Promise((r,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,d=t=>{this.fragmentLoader.loadPart(e,t,s).then(s=>{o[t.index]=s;const n=s.part;this.hls.trigger(E.FRAG_LOADED,s);const a=ps(i.details,e.sn,t.index+1)||ys(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});d(a)}).catch(n)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===T.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===v.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Os)return void(this.fragCurrent||this.state===ws||this.state===Us||(this.state=Ds));const{frag:i,part:s,level:r}=t,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,s,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===k)return!1;if(t>=r.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)){var s;if((this.hls.hasEnoughToStart?(null==(s=this.media)?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:n}=e;if(null==t||!t[s])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=t[s],o=a.details,l=n>-1?ps(o,r,n):null,d=l?l.fragment:ms(o,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(e,t,i,s,r){if(this.state!==Os)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=be(n,a)),!o.length)return;const l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,h={type:e.type,frag:t,part:i,chunkMeta:s,offset:d,parent:t.type,data:o};if(this.hls.trigger(E.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!di.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const i=t.currentTime,s=di.bufferInfo(t,i,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,s.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const s=this.getLoadPosition();if(!m(s))return null;const r=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,r)}getFwdBufferInfoAtPos(e,t,i,s){const r=di.bufferInfo(e,t,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(r.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(r.nextStart,n.end)-t,s);return di.bufferInfo(e,t,i)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return i=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-3*t,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=R){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=i[0].start,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const i=r.initialLiveManifestSize;if(s<i)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${i})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const i=this.hls.startPosition,s=this.hls.liveSyncPosition,r=o?(-1!==i&&i>=n?i:s)||o.start:e;this.log(`Setting startPosition to ${r} to match start frag at live edge. mainStart: ${i} liveSyncPosition: ${s} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=r}}else e<=n&&(o=i[0]);if(!o){const i=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,i,t)}let d=this.filterReplacedPrimary(o,t);if(!d&&o){const e=o.sn-t.startSN;d=this.filterReplacedPrimary(i[e+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Kt||i===Ht&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&i.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==e&&i.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Gs(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Gs(this.config)&&e.type!==k){const i=this.hls.interstitialsManager,s=null==i?void 0:i.bufferingItem;if(s){const i=s.event;if(i){if(i.appendInPlace||Math.abs(e.start-s.start)>1||0===s.start)return null}else{if(e.end<=s.start&&!1===(null==t?void 0:t.live))return null;if(e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}}const r=null==i?void 0:i.playerQueue;if(r)for(let t=r.length;t--;){const i=r[t].interstitial;if(i.appendInPlace&&e.start>=i.startTime&&e.end<=i.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let s=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,s>-1&&i<o.start)break;const l=o.loaded;l?s=-1:(r||(o.independent||n)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${o.start}`),s=a),r=l}return s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!m(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let s=0;s<e.length;++s){const r=e[s];if(At(t,i,r))return r}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=bt(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(s=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let c;if(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var u;c=Et(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const e=c.sn-i.startSN,t=this.fragmentTracker.getState(c);if((t===Kt||t===Ht&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!h||d[0].fragment.sn>c.sn||!i.live)){if(c.level===r.level){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Kt?t:null}}}return c}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&m(r);if(n||!a&&!r){!function(e,t){e&&(Ls(t,e),t.alignedSliding||Rs(t,e),t.alignedSliding||t.skippedSegments||us(e,t,!1))}(i,e);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const s=this.timelineOffset;if(-1===i){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;null!==n&&m(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;const{media:t}=this;let i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&te(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===_s)||(this.state=Ds)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=t.details===T.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const a=t.errorAction;if(!a)return void(this.state=Us);const{action:o,flags:l,retryCount:d=0,retryConfig:h}=a,c=!!h,u=c&&o===Ot,f=c&&!a.resolved&&l===Nt,g=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!u&&f&&te(s)&&!s.endList&&g&&!It(t))this.resetFragmentErrors(e),this.treatAsGap(s),a.resolved=!0;else if((u||f)&&d<h.maxNumRetry){var m;const i=xt(null==(m=t.response)?void 0:m.code),r=Pt(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=_s,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${d+1}/${h.maxNumRetry} in ${r}ms`)}else if(h){if(this.resetFragmentErrors(e),!(d<h.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${d})`);n||o===Mt||(a.resolved=!0)}else this.state=o===_t?$s:Us;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!xt(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Ds)}reduceLengthAndFlushBuffer(e){if(this.state===Os||this.state===Fs){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==t?void 0:t.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===I&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ws&&(this.state=Ds)}afterBufferFlushed(e,t,i){if(!e)return;const s=di.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===Ns&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ws&&(this.state=Ds)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<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 r=i.details;if(!r)return void this.warn("level.details undefined");var n;if(!Object.keys(e.elementaryStreams).reduce((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=s?0:ds(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:r,level:i,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(n=this.transmuxer)?void 0:n.error))){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Fs,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===R?"level":"track"}fragInfo(e,t=!0,i){var s,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(null!=(s=t&&!i?e.startPTS:(i||e).start)?s:NaN).toFixed(3)}-${(null!=(r=t&&!i?e.endPTS:(i||e).end)?r:NaN).toFixed(3)}]${i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(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}}function Gs(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class Hs{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;return e.length?(i=1===e.length?e[0]:function(e,t){const i=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}(e,t),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Ks,js={exports:{}};var Ws=(Ks||(Ks=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||e,a),l=i?i+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 a(e,t){0===--e._eventsCount?e._events=new s:delete e._events[t]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,s,r=[];if(0===this._eventsCount)return r;for(s in e=this._events)t.call(e,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=i?i+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r<n;r++)a[r]=s[r].fn;return a},o.prototype.listenerCount=function(e){var t=i?i+e:e,s=this._events[t];return s?s.fn?1:s.length:0},o.prototype.emit=function(e,t,s,r,n,a){var o=i?i+e:e;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(e,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,t),!0;case 3:return h.fn.call(h.context,t,s),!0;case 4:return h.fn.call(h.context,t,s,r),!0;case 5:return h.fn.call(h.context,t,s,r,n),!0;case 6:return h.fn.call(h.context,t,s,r,n,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var u,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(e,h[d].fn,void 0,!0),c){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,t);break;case 3:h[d].fn.call(h[d].context,t,s);break;case 4:h[d].fn.call(h[d].context,t,s,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(e,t,i){return n(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return n(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,s,r){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||s&&o.context!==s||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==t||r&&!o[l].once||s&&o[l].context!==s)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(js)),js.exports),qs=W(Ws);const Ys="1.6.14",zs={};function Xs(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 Qs(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 Js(e,t){let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i}function Zs(e,t){const i=t;let s=0;for(;Qs(e,t);){s+=10;s+=Js(e,t+6),Xs(e,t+10)&&(s+=10),t+=s}if(s>0)return e.subarray(i,i+s)}function er(e,t){return 255===e[t]&&240==(246&e[t+1])}function tr(e,t){return 1&e[t+1]?7:9}function ir(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function sr(e,t){return t+1<e.length&&er(e,t)}function rr(e,t){if(sr(e,t)){const i=tr(e,t);if(t+i>=e.length)return!1;const s=ir(e,t);if(s<=i)return!1;const r=t+s;return r===e.length||sr(e,r)}return!1}function nr(e,t,i,s,r){if(!e.samplerate){const n=function(e,t,i,s){const r=t[i+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(E.ERROR,E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[i+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let h=n;5!==a&&29!==a||(h-=3);const c=[a<<3|(14&h)>>1,(1&h)<<7|o<<3];return $.log(`manifest codec:${s}, parsed codec:${l}, channels:${o}, rate:${d} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:d,channelCount:o,codec:l,parsedCodec:l,manifestCodec:s}}(t,i,s,r);if(!n)return;x(e,n)}}function ar(e){return 9216e4/e}function or(e,t,i,s,r){const n=s+r*ar(e.samplerate),a=function(e,t){const i=tr(e,t);if(t+i<=e.length){const s=ir(e,t)-i;if(s>0)return{headerLength:i,frameLength:s}}}(t,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,d=Math.max(0,i+l-t.length);d?(o=new Uint8Array(l-r),o.set(t.subarray(i+r,t.length),0)):o=t.subarray(i+r,i+l);const h={unit:o,pts:n};return d||e.samples.push(h),{sample:h,length:l,missing:d}}const l=t.length-i;o=new Uint8Array(l),o.set(t.subarray(i,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function lr(e,t){return Qs(e,t)&&Js(e,t+6)+10<=e.length-t}function dr(e,t=0,i=1/0){return function(e,t,i,s){const r=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=(c=e,c&&c.buffer instanceof ArrayBuffer&&void 0!==c.byteLength&&void 0!==c.byteOffset?e.byteOffset:0),o=(a+e.byteLength)/n,l=(a+t)/n,d=Math.floor(Math.max(0,Math.min(l,o))),h=Math.floor(Math.min(d+Math.max(i,0),o));var c;return new s(r,d,h-d)}(e,t,i,Uint8Array)}function hr(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=e.data.subarray(1).indexOf(0);if(-1===i)return;const s=H(dr(e.data,1,i)),r=e.data[2+i],n=e.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=H(dr(e.data,3+i,n));let o;return o="--\x3e"===s?H(dr(e.data,4+i+n)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+i+n)),t.mimeType=s,t.pictureType=r,t.description=a,t.data=o,t}function cr(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=H(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const i=H(e.data.subarray(t),!0);t+=i.length+1;const s=H(e.data.subarray(t));return{key:e.type,info:i,data:s}}const t=H(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?hr(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const i=H(e.data.subarray(t),!0);t+=i.length+1;const s=H(e.data.subarray(t));return{key:e.type,info:i,data:s}}const t=H(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function ur(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Js(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}function fr(e){let t=0;const i=[];for(;Qs(e,t);){const s=Js(e,t+6);e[t+5]>>6&1&&(t+=10),t+=10;const r=t+s;for(;t+10<r;){const s=ur(e.subarray(t)),r=cr(s);r&&i.push(r),t+=s.size+10}Xs(e,t)&&(t+=10)}return i}function gr(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function mr(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),i=1&t[3];let s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}function pr(e){const t=fr(e);for(let e=0;e<t.length;e++){const i=t[e];if(gr(i))return mr(i)}}let yr=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 vr(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Tr{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=be(this.cachedData,e),this.cachedData=null);let i,s=Zs(e,0),r=s?s.length:0;const n=this._audioTrack,a=this._id3Track,o=s?pr(s):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&m(o))&&(this.basePTS=Er(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:yr.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=l}else lr(e,r)?(s=Zs(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:yr.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,i=r):r++;if(r===l&&i!==l){const t=e.slice(i);this.cachedData?this.cachedData=be(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:vr(),id3Track:a,textTrack:vr()}}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:vr(),id3Track:this._id3Track,textTrack:vr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Er=(e,t,i)=>{if(m(e))return 90*e;return 9e4*t+(i?9e4*i.baseTime/i.timescale:0)};let Sr=null;const Ar=[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],br=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Lr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Rr=[0,1,1,4];function Ir(e,t,i,s,r){if(i+24>t.length)return;const n=kr(t,i);if(n&&i+n.frameLength<=t.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function kr(e,t){const i=e[t+1]>>3&3,s=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Ar[14*(3===i?3-s:3===s?3:4)+r-1],d=br[3*(3===i?0:2===i?1:2)+n],h=3===o?1:2,c=Lr[i][s],u=Rr[s],f=8*c*u,g=Math.floor(c*l/d+a)*u;if(null===Sr){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Sr=e?parseInt(e[1]):0}return!!Sr&&Sr<=87&&2===s&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function Pr(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function wr(e,t){return t+1<e.length&&Pr(e,t)}function Dr(e,t){if(t+1<e.length&&Pr(e,t)){const i=4,s=kr(e,t);let r=i;null!=s&&s.frameLength&&(r=s.frameLength);const n=t+r;return n===e.length||wr(e,n)}return!1}const xr=(e,t)=>{let i=0,s=5;t+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=e[t];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,i=i?i<<o|r[0]:r[0],t+=1,s-=o}return i};class Cr extends Tr{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=_r(e,t,i,this.basePTS,this.frameIndex);if(-1!==s){return{sample:e.samples[e.samples.length-1],length:s,missing:0}}}static probe(e){if(!e)return!1;const t=Zs(e,0);if(!t)return!1;const i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==pr(t)&&xr(e,i)<16}}function _r(e,t,i,s,r){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>t.length)return-1;const d=t[i+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(t[i+6]<<8|t[i+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|c<<2|o>>4,o<<4&224]),p=s+r*(1536/a*9e4),y=t.subarray(i,i+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:y,pts:p}),l}const Mr=/\/emsg[-/]ID3/i;function Or(e,t){return m(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class Fr{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ei(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,zt)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);s.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t);let s=0;for(let t=32;t<e.length-16;t+=160,s+=16)i.set(e.subarray(t,t+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let t=32;t<e.length-16;t+=160,s+=16)e.set(i.subarray(s,s+16),t);return e}decryptAvcSample(e,t,i,s,r){const n=Pe(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),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)return void s();const r=e[t].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,s,n),this.decrypter.isSync())))return}}}}class Nr{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,s=this.VideoSample;if(s&&0!==s.units.length||(s=e[e.length-1]),null!=(t=s)&&t.units){const e=s.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const i=t.samples,s=i.length;if(!s)return void t.dropped++;{const t=i[s-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o,l,d,h=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(t,0),r=0,h=1);h<s;)if(o=t[h++],r)if(1!==r)if(o)if(1===o){if(l=h-r-1,c>=0){const e={data:t.subarray(c,l),type:u};a.push(e)}else{const i=this.getLastNalUnit(e.samples);i&&(n&&h<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=be(i.data,t.subarray(0,l)),i.state=0))}h<s?(d=this.getNALuType(t,h),c=h,u=d,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(c>=0&&r>=0){const e={data:t.subarray(c,s),type:u,state:r};a.push(e)}if(0===a.length){const i=this.getLastNalUnit(e.samples);i&&(i.data=be(i.data,t))}return e.naluState=r,a}}class Ur{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),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>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&&$.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,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){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 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Br extends Nr{parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 1:{let t=!1;n=!0;const r=s.data;if(o&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;if(t)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,ke(s.data,1,i.pts,t.samples);break;case 7:{var h,c;n=!0,o=!0;const t=s.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(h=e.pixelRatio)?void 0:h[0])!==i.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];const s=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:n=!0,e.pps=[s.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Ur(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i,s=8,r=8;for(let n=0;n<e;n++)0!==r&&(i=t.readEG(),r=(s+i+256)%256),s=0===r?s:r}readSPS(e){const t=new Ur(e);let i,s,r,n=0,a=0,o=0,l=0;const d=t.readUByte.bind(t),h=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),p=this.skipScalingList.bind(this);d();const y=d();if(h(5),f(3),d(),m(),100===y||110===y||122===y||244===y||44===y||83===y||86===y||118===y||128===y){const e=c();if(3===e&&f(1),m(),m(),f(1),u())for(s=3!==e?8:12,r=0;r<s;r++)u()&&p(r<6?16:64,t)}m();const v=c();if(0===v)c();else if(1===v)for(f(1),g(),g(),i=c(),r=0;r<i;r++)g();m(),f(1);const T=c(),E=c(),S=h(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let A=[1,1];if(u()&&u()){switch(d()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(T+1)-2*n-2*a),height:(2-S)*(E+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}class $r extends Nr{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var d;if(n=!0,o)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,ke(s.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=x(e.params,this.readVPS(s.data)),this.initVPS=s.data),e.vps=[s.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],s.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(s.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const i in t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,s.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(s.data);for(const i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,s.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s<e.byteLength;s++)s>=2&&3===e[s]&&0===e[s-1]&&0===e[s-2]||(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 Ur(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new Ur(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),h=t.readUByte(),c=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),y=[],v=[];for(let e=0;e<i;e++)y.push(t.readBoolean()),v.push(t.readBoolean());if(i>0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e<i;e++)y[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[e]&&t.readUByte();t.readUEG();const T=t.readUEG();3==T&&t.skipBits(1);const E=t.readUEG(),S=t.readUEG(),A=t.readBoolean();let b=0,L=0,R=0,I=0;A&&(b+=t.readUEG(),L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG());const k=t.readUEG(),P=t.readUEG(),w=t.readUEG();for(let e=t.readBoolean()?0:i;e<=i;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++){if(t.readBoolean()){const i=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<i;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const D=t.readUEG();let x=0;for(let e=0;e<D;e++){let i=!1;if(0!==e&&(i=t.readBoolean()),i){e===D&&t.readUEG(),t.readBoolean(),t.readUEG();let i=0;for(let e=0;e<=x;e++){const e=t.readBoolean();let s=!1;e||(s=t.readBoolean()),(e||s)&&i++}x=i}else{const e=t.readUEG(),i=t.readUEG();x=e+i;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let e=0;e<i;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let i=0;i<e;i++){for(let e=0;e<w+4;e++)t.readBits(1);t.readBits(1)}}let C=0,_=1,M=1,O=!0,F=1,N=0;t.readBoolean(),t.readBoolean();let U=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(_=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(_=t.readBits(16),M=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(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(),U=t.readBoolean(),U&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG());if(t.readBoolean()){F=t.readBits(32),N=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),s=t.readBoolean();let r=!1;(e||s)&&(r=t.readBoolean(),r&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),r&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=i;n++){O=t.readBoolean();let i=!1;O||t.readBoolean()?t.readEG():i=t.readBoolean();const n=i?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(s)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),C=t.readUEG())}let B=E,$=S;if(A){let e=1,t=1;1===T?e=t=2:2==T&&(e=2),B=E-e*L-e*b,$=S-t*I-t*R}const V=s?["A","B","C"][s]:"",G=a<<24|o<<16|l<<8|d;let H=0;for(let e=0;e<32;e++)H=(H|(G>>e&1)<<31-e)>>>0;let K=H.toString(16);1===n&&"2"===K&&(K="6");return{codecString:`hvc1.${V}${n}.${K}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[h,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:P,min_spatial_segmentation_idc:C,chroma_format_idc:T,frame_rate:{fixed:O,fps:N/F}},width:B,height:$,pixelRatio:[_,M]}}readPPS(e){const t=new Ur(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 i=t.readBoolean(),s=t.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Vr=188;class Gr{constructor(e,t,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){const i=Gr.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){const t=e.length;let i=Math.min(940,t-Vr)+1,s=0;for(;s<i;){let r=!1,n=-1,a=0;for(let o=s;o<t;o+=Vr){if(71!==e[o]||t-o!==Vr&&71!==e[o+Vr]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,e.length-Vr)+1)),r||(r=0===Hr(e,o)),r&&a>1&&(0===n&&a>2||o+Vr>i))return n}s++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:oe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Gr.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=Gr.createTrack("audio",s),this._id3Track=Gr.createTrack("id3"),this._txtTrack=Gr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}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=!1,s=!1){let r;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,h=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(v=(e=be(this.remainderData,e)).length,this.remainderData=null),v<Vr&&!s)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const T=Math.max(0,Gr.syncOffset(e));v-=(v-T)%Vr,v<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,v,e.buffer.byteLength-v));let E=0;for(let t=T;t<v;t+=Vr)if(71===e[t]){const s=!!(64&e[t+1]),v=Hr(e,t);let E;if((48&e[t+3])>>4>1){if(E=t+5+e[t+4],E===t+Vr)continue}else E=t+4;switch(v){case d:s&&(h&&(r=Yr(h,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)),h={data:[],size:0}),h&&(h.data.push(e.subarray(E,t+Vr)),h.size+=t+Vr-E);break;case c:if(s){if(f&&(r=Yr(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(e.subarray(E,t+Vr)),f.size+=t+Vr-E);break;case u:s&&(g&&(r=Yr(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(E,t+Vr)),g.size+=t+Vr-E);break;case 0:s&&(E+=e[E]+1),y=this._pmtId=Kr(e,E);break;case y:{s&&(E+=e[E]+1);const r=jr(e,E,this.typeSupported,i,this.observer,this.logger);d=r.videoPid,d>0&&(n.pid=d,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),u=r.id3Pid,u>0&&(o.pid=u),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${T} to parse all TS packets.`),m=null,t=T-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=v}}else E++;E>0&&Wr(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=h,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return s&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:r}=e,n=i.pesData,a=t.pesData,o=s.pesData;let l;if(n&&(l=Yr(n,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,r,l,!0),i.pesData=null)):i.pesData=n,a&&(l=Yr(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Yr(o,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=o}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new Fr(this.observer,this.config,t);return this.decrypt(s,r)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new Br:"hevc"===e&&(this.videoParser=new $r))}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=e;s.samples&&"aac"===s.segmentCodec?t.decryptAacSamples(s.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let r,n,a,o=t.data;if(s){this.aacOverFlow=null;const t=s.missing,r=s.sample.unit.byteLength;if(-1===t)o=be(s.sample.unit,o);else{const n=r-t;s.sample.unit.set(o.subarray(0,t),n),e.samples.push(s.sample),i=s.missing}}for(r=i,n=o.length;r<n-1&&!sr(o,r);r++);if(r!==i){let e;const t=r<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",Wr(this.observer,new Error(e),t,this.logger),!t)return}if(nr(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=ar(e.samplerate);a=s.sample.pts+t}}let l,d=0;for(;r<n;){if(l=or(e,o,r,a,d),r+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;r<n-1&&!sr(o,r);r++);}}parseMPEGPES(e,t){const i=t.data,s=i.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<s;)if(wr(i,n)){const t=Ir(e,i,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const i=t.data,s=t.pts;if(void 0===s)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=i.length;let n,a=0,o=0;for(;o<r&&(n=_r(e,i,o,s,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=x({},t,{type:this._videoTrack?yr.emsg:yr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Hr(e,t){return((31&e[t+1])<<8)+e[t+2]}function Kr(e,t){return(31&e[t+10])<<8|e[t+11]}function jr(e,t,i,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=Hr(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!s){qr("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!s){qr("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){qr("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let s=t+5,r=l;for(;r>2;){if(106===e[s])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[s+1]+2;s+=t,r-=t}}break;case 194:case 135:return Wr(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=l+5}return a}function Wr(e,t,i,s){s.warn(`parsing error: ${t.message}`),e.emit(E.ERROR,E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function qr(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Yr(e,t){let i,s,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=be(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>e.size-6)return null;const d=i[7];192&d&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&d?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=i[8];let h=r+9;if(e.size<=h)return null;e.size-=h;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){i=l[e];let t=i.byteLength;if(h){if(h>t){h-=t;continue}i=i.subarray(h),t-=h,h=0}c.set(i,o),o+=t}return s&&(s-=r+3),{data:c,pts:n,dts:a,len:s}}return null}class zr{static getSilentFrame(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])}}}const Xr=Math.pow(2,32)-1;class Qr{static init(){let e;for(e in Qr.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Qr.types)Qr.types.hasOwnProperty(e)&&(Qr.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Qr.HDLR_TYPES={video:t,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Qr.STTS=Qr.STSC=Qr.STCO=r,Qr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Qr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Qr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Qr.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Qr.FTYP=Qr.box(Qr.types.ftyp,n,o,n,a),Qr.DINF=Qr.box(Qr.types.dinf,Qr.box(Qr.types.dref,s))}static box(e,...t){let i=8,s=t.length;const r=s;for(;s--;)i+=t[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]=255&i,n.set(e,4),s=0,i=8;s<r;s++)n.set(t[s],i),i+=t[s].byteLength;return n}static hdlr(e){return Qr.box(Qr.types.hdlr,Qr.HDLR_TYPES[e])}static mdat(e){return Qr.box(Qr.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(Xr+1)),s=Math.floor(t%(Xr+1));return Qr.box(Qr.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(e){return Qr.box(Qr.types.mdia,Qr.mdhd(e.timescale||0,e.duration||0),Qr.hdlr(e.type),Qr.minf(e))}static mfhd(e){return Qr.box(Qr.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Qr.box(Qr.types.minf,Qr.box(Qr.types.smhd,Qr.SMHD),Qr.DINF,Qr.stbl(e)):Qr.box(Qr.types.minf,Qr.box(Qr.types.vmhd,Qr.VMHD),Qr.DINF,Qr.stbl(e))}static moof(e,t,i){return Qr.box(Qr.types.moof,Qr.mfhd(e),Qr.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Qr.trak(e[t]);return Qr.box.apply(null,[Qr.types.moov,Qr.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(Qr.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Qr.trex(e[t]);return Qr.box.apply(null,[Qr.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Xr+1)),s=Math.floor(t%(Xr+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,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 Qr.box(Qr.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,r;for(s=0;s<t.length;s++)r=t[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Qr.box(Qr.types.sdtp,i)}static stbl(e){return Qr.box(Qr.types.stbl,Qr.stsd(e),Qr.box(Qr.types.stts,Qr.STTS),Qr.box(Qr.types.stsc,Qr.STSC),Qr.box(Qr.types.stsz,Qr.STSZ),Qr.box(Qr.types.stco,Qr.STCO))}static avc1(e){let t,i,s,r=[],n=[];for(t=0;t<e.sps.length;t++)i=e.sps[t],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(t=0;t<e.pps.length;t++)i=e.pps[t],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=Qr.box(Qr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return Qr.box(Qr.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Qr.box(Qr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Qr.box(Qr.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){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,255&t,0,0])}static mp4a(e){return Qr.box(Qr.types.mp4a,Qr.audioStsd(e),Qr.box(Qr.types.esds,Qr.esds(e)))}static mp3(e){return Qr.box(Qr.types[".mp3"],Qr.audioStsd(e))}static ac3(e){return Qr.box(Qr.types["ac-3"],Qr.audioStsd(e),Qr.box(Qr.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.mp4a(e));if("ac3"===t&&e.config)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.ac3(e));if("mp3"===t&&"mp3"===e.codec)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.avc1(e));if("hevc"===t&&e.vps)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.hvc1(e))}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,r=e.height||0,n=Math.floor(i/(Xr+1)),a=Math.floor(i%(Xr+1));return Qr.box(Qr.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,255&s,0,0,r>>8&255,255&r,0,0]))}static traf(e,t){const i=Qr.sdtp(e),s=e.id,r=Math.floor(t/(Xr+1)),n=Math.floor(t%(Xr+1));return Qr.box(Qr.types.traf,Qr.box(Qr.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Qr.box(Qr.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Qr.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Qr.box(Qr.types.trak,Qr.tkhd(e),Qr.mdia(e))}static trex(e){const t=e.id;return Qr.box(Qr.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,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,r=12+16*s,n=new Uint8Array(r);let a,o,l,d,h,c;for(t+=8+r,n.set(["video"===e.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<s;a++)o=i[a],l=o.duration,d=o.size,h=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Qr.box(Qr.types.trun,n)}static initSegment(e){Qr.types||Qr.init();const t=Qr.moov(e);return be(Qr.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],s=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),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let r=s.length;for(let e=0;e<i.length;e+=1){r+=3;for(let t=0;t<i[e].length;t+=1)r+=2+i[e][t].length}const n=new Uint8Array(r);n.set(s,0),r=s.length;const a=i.length-1;for(let e=0;e<i.length;e+=1){n.set(new Uint8Array([32+e|(e===a?128:0),0,i[e].length]),r),r+=3;for(let t=0;t<i[e].length;t+=1)n.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),r),r+=2,n.set(i[e][t],r),r+=i[e][t].length}const o=Qr.box(Qr.types.hvcC,n),l=e.width,d=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return Qr.box(Qr.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,d>>8&255,255&d,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,Qr.box(Qr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Qr.box(Qr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}}Qr.types=void 0,Qr.HDLR_TYPES=void 0,Qr.STTS=void 0,Qr.STSC=void 0,Qr.STCO=void 0,Qr.STSZ=void 0,Qr.VMHD=void 0,Qr.SMHD=void 0,Qr.STSD=void 0,Qr.FTYP=void 0,Qr.DINF=void 0;function Jr(e,t,i=1,s=!1){const r=e*t*i;return s?Math.round(r):r}function Zr(e,t=!1){return Jr(e,1e3,1/9e4,t)}function en(e){const{baseTime:t,timescale:i,trackId:s}=e;return`${t/i} (${t}/${i}) trackId: ${s}`}let tn,sn=null,rn=null;function nn(e,t,i,s){return{duration:t,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class an extends M{constructor(e,t,i,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===sn){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);sn=e?parseInt(e[1]):0}if(null===rn){const e=navigator.userAgent.match(/Safari\/(\d+)/i);rn=e?parseInt(e[1]):0}}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?en(t):t} > ${e?en(e):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((e,s)=>{let r=s.pts,n=r-e;return n<-4294967296&&(t=!0,r=on(r,i),n=r-e),n>0?e:r},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,r,n,a,o){let l,d,h,c,u,f,g=r,m=r;const p=e.pid>-1,y=t.pid>-1,v=t.samples.length,T=e.samples.length>0,E=a&&v>0||v>1;if((!p||T)&&(!y||E)||this.ISGenerated||a){if(this.ISGenerated){var S,A,b,L;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(A=e.pixelRatio)?void 0:A[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(L=e.pixelRatio)?void 0:L[1]))||!e&&E||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,r,n));const i=this.isVideoContiguous;let s,a=-1;if(E&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${v} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,s=m}else-1===a&&(this.warn(`No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(T&&E){const i=this.getVideoStartPts(t.samples),s=(on(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,s),m+=Math.max(0,-s)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,r,n)),d=this.remuxAudio(e,g,this.isAudioContiguous,n,y||E||o===I?m:void 0),E){const s=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,m,i,s)}}else E&&(l=this.remuxVideo(t,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=ln(i,r,this._initPTS,this._initDTS)),s.samples.length&&(c=dn(s,r,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:c,id3:u}}computeInitPts(e,t,i,s){const r=Math.round(i*t);let n=on(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${s}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,i,s){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let d,h,c,u=!l||s,f="audio/mp4",g=-1;if(u&&(d=h=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Qr.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.id,c=e.inputTimeScale,l&&c===l.timescale?u=!1:d=h=this.computeInitPts(r[0].pts,c,i,"audio"))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Qr.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.id,c=t.inputTimeScale,l&&c===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=on(n[0].dts,e),s=this.computeInitPts(t,c,i,"video"),r=this.computeInitPts(e,c,i,"video");h=Math.min(h,s),d=Math.min(d,r)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${d/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${d/c} (${d}/${c}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:c,trackId:g},this._initDTS={baseTime:h,timescale:c,trackId:g}):d=c=void 0,{tracks:o,initPTS:d,timescale:c,trackId:g}}remuxVideo(e,t,i,s){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*r/l.timescale;let h,c,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,y=!1;if(!i||null===u){const e=d+t*r,s=n[0].pts-on(n[0].dts,n[0].pts);sn&&null!==u&&Math.abs(e-s-(u+d))<15e3?i=!0:u=e-s-d}const S=u+d;for(let e=0;e<o;e++){const t=n[e];t.pts=on(t.pts,S),t.dts=on(t.dts,S),t.dts<n[e>0?e-1:e].dts&&(y=!0)}y&&n.sort(function(e,t){const i=e.dts-t.dts,s=e.pts-t.pts;return i||s}),h=n[0].dts,c=n[n.length-1].dts;const A=c-h,b=A?Math.round(A/(o-1)):g||e.inputTimeScale/30;if(i){const i=h-S,s=i>b,r=i<-1;if((s||r)&&(s?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Zr(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Zr(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||S>=n[0].pts||sn)){h=S;const e=n[0].pts-i;if(s)n[0].dts=h,n[0].pts=e;else{let t=!0;for(let s=0;s<n.length&&!(n[s].dts>e&&t);s++){const e=n[s].pts;if(n[s].dts-=i,n[s].pts-=i,s<n.length-1){const i=n[s+1].pts;t=i<=n[s].pts==i<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${Zr(e,!0)}/${Zr(h,!0)}, delta: ${Zr(i,!0)} ms`)}}h=Math.max(0,h);let L=0,R=0,I=h;for(let e=0;e<o;e++){const t=n[e],i=t.units,s=i.length;let r=0;for(let e=0;e<s;e++)r+=i[e].data.length;R+=r,L+=s,t.length=r,t.dts<I?(t.dts=I,I+=b/4|0||1):I=t.dts,m=Math.min(t.pts,m),p=Math.max(t.pts,p)}c=n[o-1].dts;const k=R+4*L+8;let P;try{P=new Uint8Array(k)}catch(e){return void this.observer.emit(E.ERROR,E.ERROR,{type:v.MUX_ERROR,details:T.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:k,reason:`fail allocating video mdat ${k}`})}const w=new DataView(P.buffer);w.setUint32(0,k),P.set(Qr.types.mdat,4);let D=!1,C=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=n[e],i=t.units;let l,h=0;for(let e=0,t=i.length;e<t;e++){const t=i[e],s=t.data,r=t.data.byteLength;w.setUint32(f,r),f+=4,P.set(s,f),f+=r,h+=4+r}if(e<o-1)g=n[e+1].dts-t.dts,l=n[e+1].pts-t.pts;else{const i=this.config,a=e>0?t.dts-n[e-1].dts:b;if(l=e>0?t.pts-n[e-1].pts:b,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(i.maxBufferHole*r),n=(s?m+s*r:this.nextAudioTs+d)-t.pts;n>e?(g=n-a,g<0?g=a:D=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const c=Math.round(t.pts-t.dts);C=Math.min(C,g),M=Math.max(M,g),_=Math.min(_,l),O=Math.max(O,l),a.push(nn(t.key,g,h,c))}if(a.length)if(sn){if(sn<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(rn&&O-_<M-C&&b/M<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=h;for(let t=0,i=a.length;t<i;t++){const s=e+a[t].duration,r=e+a[t].cts;if(t<i-1){const e=s+a[t+1].cts;a[t].duration=e-r}else a[t].duration=t?a[t-1].duration:b;a[t].cts=0,e=s}}g=D||!g?b:g;const F=c+g;this.nextVideoTs=u=F-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const N={data1:Qr.moof(e.sequenceNumber++,h,x(e,{samples:a})),data2:P,startPTS:(m-d)/r,endPTS:(p+g-d)/r,startDTS:(h-d)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,N}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,i,s,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,d=this._initPTS,h="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=e.samples,g=h?0:8,m=this.nextAudioTs||-1;const p=d.baseTime*n/d.timescale,y=p+t*n;if(this.isAudioContiguous=i=i||f.length&&m>0&&(s&&Math.abs(y-(m+p))<9e3||Math.abs(on(f[0].pts,y)-(m+p))<20*l),f.forEach(function(e){e.pts=on(e.pts,y)}),!i||m<0){const e=f.length;if(f=f.filter(e=>e.pts>=0),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${p} / ${n})`),!f.length)return;m=0===r?0:s&&!u?Math.max(0,y-p):f[0].pts-p}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let i=0,s=m+p;i<f.length;i++){const r=f[i],a=r.pts,o=a-s,d=Math.abs(1e3*o/n);if(o<=-t*l&&u)0===i&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=m=a-p,s=a);else if(o>=t*l&&d<1e4&&u){let t=Math.round(o/l);for(s=a-t*l;s<0&&t&&l;)t--,s+=l;0===i&&(this.nextAudioTs=m=s-p),this.warn(`Injecting ${t} audio frames @ ${((s-p)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=zr.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),f.splice(i,0,{unit:t,pts:s}),s+=l,i++}}r.pts=s,s+=l}}let S,A=null,b=null,L=0,R=f.length;for(;R--;)L+=f[R].unit.byteLength;for(let t=0,s=f.length;t<s;t++){const s=f[t],r=s.unit;let n=s.pts;if(null!==b){c[t-1].duration=Math.round((n-b)/a)}else{if(i&&"aac"===e.segmentCodec&&(n=m+p),A=n,!(L>0))return;L+=g;try{S=new Uint8Array(L)}catch(e){return void this.observer.emit(E.ERROR,E.ERROR,{type:v.MUX_ERROR,details:T.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:L,reason:`fail allocating audio mdat ${L}`})}if(!h){new DataView(S.buffer).setUint32(0,L),S.set(Qr.types.mdat,4)}}S.set(r,g);const l=r.byteLength;g+=l,c.push(nn(!0,o,l,0)),b=n}const I=c.length;if(!I)return;const k=c[c.length-1];m=b-p,this.nextAudioTs=m+a*k.duration;const P=h?new Uint8Array(0):Qr.moof(e.sequenceNumber++,A/a,x({},e,{samples:c}));e.samples=[];const w=(A-p)/n,D=m/n,C={data1:P,data2:S,startPTS:w,endPTS:D,startDTS:w,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,C}}function on(e,t){let i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function ln(e,t,i,s){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let a=0;a<r;a++){const r=e.samples[a];r.pts=on(r.pts-i.baseTime*n/i.timescale,t*n)/n,r.dts=on(r.dts-s.baseTime*n/s.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function dn(e,t,i){const s=e.samples.length;if(!s)return;const r=e.inputTimeScale;for(let n=0;n<s;n++){const s=e.samples[n];s.pts=on(s.pts-i.baseTime*r/i.timescale,t*r)/r}e.samples.sort((e,t)=>e.pts-t.pts);const n=e.samples;return e.samples=[],{samples:n}}function hn(e,t,i=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(i?e.duration:0))/e.timescale:t}function cn(e,t,i){const s=e.codec;if(s&&s.length>4)return s;if(t===Q){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return Ve(s,!1)}return i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}return i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}try{tn=self.performance.now.bind(self.performance)}catch(e){tn=Date.now}const un=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const r=this.videoTrack=vr("video",1),n=this.audioTrack=vr("audio",1),a=this.txtTrack=vr("text",1);if(this.id3Track=vr("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=me(e);if(o.video){const{id:e,timescale:t,codec:i,supplemental:s}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=i,r.supplemental=s}if(o.audio){const{id:e,timescale:t,codec:i}=o.audio;n.id=e,n.timescale=t,n.codec=i}a.id=oe.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let i=0;i<t;){const s=he(e,i);if(s>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=s>1?i+s:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=be(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},i=fe(e,["moof"]);if(i.length<2)return t.remainder=e,t;const s=i[i.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}(i);this.remainderData=t.remainder,s.samples=t.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,t);return r.samples=Le(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=Le(e,t),{videoTrack:t,audioTrack:vr(),id3Track:s,textTrack:vr()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=fe(e.samples,["emsg"]);s&&s.forEach(e=>{const s=function(e){const t=e[0];let i="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(0===t){for(;"\0"!==le(e.subarray(d,d+1));)i+=le(e.subarray(d,d+1)),d+=1;for(i+=le(e.subarray(d,d+1)),d+=1;"\0"!==le(e.subarray(d,d+1));)s+=le(e.subarray(d,d+1)),d+=1;s+=le(e.subarray(d,d+1)),d+=1,r=he(e,12),n=he(e,16),o=he(e,20),l=he(e,24),d=28}else if(1===t){d+=4,r=he(e,d),d+=4;const t=he(e,d);d+=4;const n=he(e,d);for(d+=4,a=2**32*t+n,p(a)||(a=Number.MAX_SAFE_INTEGER,$.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=he(e,d),d+=4,l=he(e,d),d+=4;"\0"!==le(e.subarray(d,d+1));)i+=le(e.subarray(d,d+1)),d+=1;for(i+=le(e.subarray(d,d+1)),d+=1;"\0"!==le(e.subarray(d,d+1));)s+=le(e.subarray(d,d+1)),d+=1;s+=le(e.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(d,e.byteLength)}}(e);if(Mr.test(s.schemeIdUri)){const e=Or(s,t);let r=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=s.payload;i.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:yr.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=Or(s,t);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:e,pts:e,type:yr.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}},remux:class extends M{constructor(e,t,i,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;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.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:s}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=me(e);if(t)!function(e,t){if(!e||!t)return;const i=t.keyId;i&&t.isCommonEncryption&&Se(e,(e,t)=>{const s=e.subarray(8,24);s.some(e=>0!==e)||($.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${K(s)} -> ${K(i)}`),e.set(i,8))})}(e,t);else{const e=r||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}r&&(i=cn(r,Q,this)),n&&(s=cn(n,J,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,i,s,r,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};m(d)||(d=this.lastEndTime=r||0);const c=t.samples;if(!c.length)return h;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t,i){const s={},r=fe(e,["moof","traf"]);for(let e=0;e<r.length;e++){const n=r[e],a=fe(n,["tfhd"])[0],o=he(a,4),l=t[o];if(!l)continue;s[o]||(s[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=s[o],h=fe(n,["tfdt"])[0];if(h){const e=h[0];let t=he(h,4);1===e&&(t===ne?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=ne+1,t+=he(h,8))),m(t)&&(!m(d.start)||t<d.start)&&(d.start=t)}const c=l.default,u=he(a,0)|(null==c?void 0:c.flags);let f=(null==c?void 0:c.duration)||0;8&u&&(f=he(a,2&u?12:8));const g=fe(n,["trun"]);let p=d.start||0,y=0,v=f;for(let e=0;e<g.length;e++){const t=g[e],i=he(t,4),s=d.sampleCount;d.sampleCount+=i;const r=1&t[3],n=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],h=8&t[2];let c=8,u=i;for(r&&(c+=4),n&&i&&(1&t[c+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=s),c+=4,a?(v=he(t,c),c+=4):v=f,o&&(c+=4),h&&(c+=4),p+=v,y+=v,u--);u--;)a?(v=he(t,c),c+=4):v=f,o&&(c+=4),l&&(1&t[c+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(u+1),d.keyFrameStart=p),c+=4),h&&(c+=4),p+=v,y+=v;!y&&f&&(y+=f*i)}d.duration+=y}if(!Object.keys(s).some(e=>s[e].duration)){let t=1/0,i=0;const r=fe(e,["sidx"]);for(let e=0;e<r.length;e++){const s=ge(r[e]);if(null!=s&&s.references){t=Math.min(t,s.earliestPresentationTime/s.timescale);const e=s.references.reduce((e,t)=>e+t.info.duration||0,0);i=Math.max(i,e+s.earliestPresentationTime/s.timescale)}}i&&m(i)&&Object.keys(s).forEach(e=>{s[e].duration||(s[e].duration=i*s[e].timescale-s[e].start)})}return s}(c,f,this),p=f.audio?g[f.audio.id]:null,y=f.video?g[f.video.id]:null,v=hn(y,1/0),T=hn(p,1/0),E=hn(y,0,!0),S=hn(p,0,!0);let A=r,b=0;const L=p&&(!y||!l&&T<v||l&&l.trackId===f.audio.id),R=L?p:y;if(R){const e=R.timescale,t=R.start-r*e,i=L?f.audio.id:f.video.id;A=R.start/e,b=L?S-T:E-v,!n&&l||!function(e,t,i,s){if(null===e)return!0;const r=Math.max(s,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>r}(l,A,r,b)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${A-r} (${t}/${e}) trackId: ${i}`),l=null,u.initPTS=t,u.timescale=e,u.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):(u.timescale&&void 0!==u.trackId&&void 0!==u.initPTS||(this.warn("Could not set initPTS"),u.initPTS=A,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const I=A-l.baseTime/l.timescale,k=I+b;b>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const P=!!f.audio,w=!!f.video;let D="";P&&(D+="audio"),w&&(D+="video");const x={data1:c,startPTS:I,startDTS:I,endPTS:k,endDTS:k,type:D,hasAudio:P,hasVideo:w,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};h.audio=P&&!w?x:void 0,h.video=w?x:void 0;const C=null==y?void 0:y.sampleCount;if(C){const e=y.keyFrameIndex,t=-1!==e;x.nb=C,x.dropped=0===e||this.isVideoContiguous?0:t?e:C,x.independent=t,x.firstKeyFrame=e,t&&y.keyFrameStart&&(x.firstKeyFramePTS=(y.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),x.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${C} dropped: ${x.dropped} start: ${x.firstKeyFramePTS||"NA"}`)}return h.initSegment=u,h.id3=ln(i,r,l,l),s.samples.length&&(h.text=dn(s,r,l)),h}}},{demux:Gr,remux:an},{demux:class extends Tr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Zs(e,0);let s=(null==i?void 0:i.length)||0;if(Dr(e,s))return!1;for(let i=e.length;s<i;s++)if(rr(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&er(e,t)&&ir(e,t)<=e.length-t}(e,t)}appendFrame(e,t,i){nr(e,this.observer,t,i,e.manifestCodec);const s=or(e,t,i,this.basePTS,this.frameIndex);if(s&&0===s.missing)return s}},remux:an},{demux:class extends Tr{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=Zs(e,0);let i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==pr(t)&&xr(e,i)<=16)return!1;for(let t=e.length;i<t;i++)if(Dr(e,i))return $.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return Pr(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,i){if(null!==this.basePTS)return Ir(e,t,i,this.basePTS,this.frameIndex)}},remux:an}];un.splice(2,0,{demux:Cr,remux:an});class fn{constructor(e,t,i,s,r,n){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=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const r=i.transmuxing;r.executeStart=tn();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=s||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:y,initSegmentData:S}=o,A=function(e,t){let i=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(n,t);if(A&&Li(A.method)){const e=this.getDecrypter(),t=Ri(A.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,A.key.buffer,A.iv.buffer,t).then(e=>{const t=this.push(e,null,i);return this.decryptionPromise=null,t}),this.decryptionPromise;{let s=e.softwareDecrypt(n,A.key.buffer,A.iv.buffer,t);if(i.part>-1){const t=e.flush();s=t?t.buffer:t}if(!s)return r.executeEnd=tn(),gn(i);n=new Uint8Array(s)}}const b=this.needsProbing(d,h);if(b){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=tn(),gn(i)}(d||h||f||b)&&this.resetInitSegment(S,g,m,y,t),(d||f||b)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const L=this.transmux(n,A,u,c,i);this.asyncResult=mn(L);const R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,r.executeEnd=tn(),L}flush(e){const t=e.transmuxing;t.executeStart=tn();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=s;if(i){const t=i.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=tn();const i=[gn(e)];return this.asyncResult?Promise.resolve(i):i}const d=o.flush(a);return mn(d)?(this.asyncResult=!0,d.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,d,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===R?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=tn()}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,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,i,s),a.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,r){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,s,r):this.transmuxUnencrypted(e,i,s,r),n}transmuxUnencrypted(e,t,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer.demuxSampleAes(e,t,i).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;let r;for(let t=0,i=un.length;t<i;t++){var n;if(null!=(n=un[t].demux)&&n.probe(e,this.logger)){r=un[t];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,d=r.demux;o&&o instanceof l||(this.remuxer=new l(i,t,s,this.logger)),a&&a instanceof d||(this.demuxer=new d(i,t,s,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ei(this.config)),e}}const gn=e=>({remuxResult:{},chunkMeta:e});function mn(e){return"then"in e&&e.then instanceof Function}class pn{constructor(e,t,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class yn{constructor(e,t,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}let vn=0;class Tn{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=vn++,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=e=>{const t=e.data,i=this.hls;if(i&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var s;const e=null==(s=this.workerContext)?void 0:s.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===E.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new qs,this.observer.on(E.FRAG_DECRYPTED,n),this.observer.on(E.ERROR,n);const a=je(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(i.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=zs[e];if(t)return t.clientCount++,t;const i=new self.URL(e,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return zs[e]=s,s}(r.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=zs[Ys];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return zs[Ys]=s,s}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:ht(r)})}catch(s){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new fn(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new fn(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=vn++;const t=this.hls.config,i=je(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:ht(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=zs[e||Ys];if(t&&1===t.clientCount--){const{worker:i,objectURL:s}=t;delete zs[e||Ys],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.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,r,n,a,o,l,d){var h,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,y=!(p&&r.cc===p.cc),v=!(p&&l.level===p.level),T=p?l.sn-p.sn:-1,E=this.part?l.part-this.part.index:-1,S=0===T&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),A=!v&&(1===T||0===T&&(1===E||S&&E<=0)),b=self.performance.now();(v||T||0===r.stats.parsing.start)&&(r.stats.parsing.start=b),!n||!E&&A||(n.stats.parsing.start=b);const L=!(p&&(null==(h=r.initSegment)?void 0:h.url)===(null==(c=p.initSegment)?void 0:c.url)),I=new yn(y,A,o,v,g,L);if(!A||y||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===R?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${y}\n trackSwitch: ${v}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${L}`);const e=new pn(i,s,t,a,d);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,m,l,I);mn(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}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 t=i.flush(e);mn(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.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(e=>{this.handleTransmuxComplete(e)}),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)}}class En extends M{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(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=null==t?void 0:t.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=i;break}a===e.substring(0,a.length)&&(r=i)}if(-1!==r){const e=s[r],n=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=i&&nt(i);return new at(n,a>=0?a:void 0,o)}}}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(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;s.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==s.appliedTimelineOffset){const e=Math.max(o||0,0);s.appliedTimelineOffset=e,s.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(s.live||null!=i&&i.live){const o="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){hs(i,s,this);const e=s.playlistParsingError;if(e){this.warn(e);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void i.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:T.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=s.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=r.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,c=gs(s,1e3*(s.edge-h));if(s.requestScheduled+c<n?s.requestScheduled=n:s.requestScheduled+=c,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let u,f,g;if(s.canBlockReload&&s.endSN&&s.advanced){const e=this.hls.config.lowLatencyMode,r=s.lastPartSn,a=s.endSN,l=s.lastPartIndex,d=r===a;-1!==l?d?(f=a+1,g=e?0:l):(f=r,g=e?l+1:s.maxPartIndex):f=a+1;const h=s.age,c=h+s.ageHeader;let m=Math.min(c-s.partTarget,1.5*s.targetduration);if(m>0){if(c>3*s.targetduration)this.log(`Playlist last advanced ${h.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=i&&i.tuneInGoal&&c-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${m} with playlist age: ${s.age}`),m=0;else{const e=Math.floor(m/s.targetduration);if(f+=e,void 0!==g){g+=Math.round(m%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${m} skip sn ${e} to part ${g}`)}s.tuneInGoal=m}if(u=this.getDeliveryDirectives(s,t.deliveryDirectives,f,g),e||!d)return s.requestScheduled=n,void this.loadingPlaylist(o,u)}else(s.canBlockReload||s.canSkipUntil)&&(u=this.getDeliveryDirectives(s,t.deliveryDirectives,f,g));u&&void 0!==f&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=s.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,s){let r=nt(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=it),new at(i,s,r)}checkRetry(e){const t=e.details,i=Lt(e),s=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===Ot||!s.resolved&&r===_t);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Pt(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,s.resolved=!0}return o}}function Sn(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!An(e[i].attrs,t[i].attrs))return!1;return!0}function An(e,t,i){const s=e["STABLE-RENDITION-ID"];return s&&!i?s===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>e[i]!==t[i])}function bn(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class Ln{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(null===this.queues||null===this.tracks)return;const s=this.queues[t];s.push(e),1!==s.length||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(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(t){var i;if(s.onError(t),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[e])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=null==(t=this.tracks)?void 0:t[e],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}const Rn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,In="HlsJsTrackRemovedError";class kn extends Error{constructor(e){super(e),this.name=In}}function Pn(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function wn(e){return"audio"===e?1:0}class Dn{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){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){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&m(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){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}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((t,i)=>this.isLevelAllowed(t)&&i<=e);return this.clientRect=null,Dn.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;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.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;const s=(e,t)=>!t||(e.width!==t.width||e.height!==t.height);let r=e.length-1;const n=Math.max(t,i);for(let t=0;t<e.length;t+=1){const i=e[t];if((i.width>=n||i.height>=n)&&s(i,e[t+1])){r=t;break}}return r}}const xn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Cn={HLS:"h"};class _n{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof _n?e:new _n(e))),this.value=e,this.params=t}}function Mn(e,t,i,s){return new Error(`failed to ${e} "${r=t,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${i}`,{cause:s});var r}function On(e,t,i){return Mn("serialize",e,t,i)}class Fn{constructor(e){this.description=e}}const Nn="Bare Item";function Un(e){if(!1===ArrayBuffer.isView(e))throw On(e,"Byte Sequence");return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function Bn(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw On(e,"Integer");return e.toString()}function $n(e,t){if(e<0)return-$n(-e,t);const i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){const t=Math.floor(e*i);return(t%2==0?t:t+1)/i}return Math.round(e*i)/i}function Vn(e){const t=$n(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw On(e,"Decimal");const i=t.toString();return i.includes(".")?i:`${i}.0`}const Gn=/[\x00-\x1f\x7f]+/;function Hn(e){const t=(i=e).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw On(t,"Token");return t}function Kn(e){switch(typeof e){case"number":if(!m(e))throw On(e,Nn);return Number.isInteger(e)?Bn(e):Vn(e);case"string":return function(e){if(Gn.test(e))throw On(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Hn(e);case"boolean":return function(e){if("boolean"!=typeof e)throw On(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Bn(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return Un(e);if(e instanceof Fn)return Hn(e);default:throw On(e,Nn)}}function jn(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw On(e,"Key");return e}function Wn(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${jn(e)}`:`;${jn(e)}=${Kn(t)}`).join("")}function qn(e){return e instanceof _n?`${Kn(e.value)}${Wn(e.params)}`:Kn(e)}function Yn(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw On(e,"Dict");const i=e instanceof Map?e.entries():Object.entries(e),s=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map(([e,t])=>{t instanceof _n==!1&&(t=new _n(t));let i=jn(e);var s;return!0===t.value?i+=Wn(t.params):(i+="=",Array.isArray(t.value)?i+=`(${(s=t).value.map(qn).join(" ")})${Wn(s.params)}`:i+=qn(t)),i}).join(`,${s}`)}function zn(e,t){return Yn(e,t)}const Xn="CMCD-Object",Qn="CMCD-Request",Jn="CMCD-Session",Zn="CMCD-Status",ea={br:Xn,ab:Xn,d:Xn,ot:Xn,tb:Xn,tpb:Xn,lb:Xn,tab:Xn,lab:Xn,url:Xn,pb:Qn,bl:Qn,tbl:Qn,dl:Qn,ltc:Qn,mtp:Qn,nor:Qn,nrr:Qn,rc:Qn,sn:Qn,sta:Qn,su:Qn,ttfb:Qn,ttfbb:Qn,ttlb:Qn,cmsdd:Qn,cmsds:Qn,smrt:Qn,df:Qn,cs:Qn,ts:Qn,cid:Jn,pr:Jn,sf:Jn,sid:Jn,st:Jn,v:Jn,msd:Jn,bs:Zn,bsd:Zn,cdn:Zn,rtp:Zn,bg:Zn,pt:Zn,ec:Zn,e:Zn},ta=Qn;function ia(e,t){const i={};if(!e)return i;const s=Object.keys(e),r=t?(n=t,Object.keys(n).reduce((e,t)=>{var i;return null===(i=n[t])||void 0===i||i.forEach(i=>e[i]=t),e},{})):{};var n;return s.reduce((t,i)=>{var s;const n=ea[i]||r[i]||ta;return(null!==(s=t[n])&&void 0!==s?s:t[n]={})[i]=e[i],t},i)}const sa="event";const ra=e=>Math.round(e),na=(e,t)=>Array.isArray(e)?e.map(e=>na(e,t)):e instanceof _n&&"string"==typeof e.value?new _n(na(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){const i=new URL(e),s=new URL(t);if(i.origin!==s.origin)return e;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),aa=e=>100*ra(e/100),oa={br:ra,d:ra,bl:aa,dl:aa,mtp:aa,nor:(e,t)=>{let i=e;return t.version>=2&&(e instanceof _n&&"string"==typeof e.value?i=new _n([e]):"string"==typeof e&&(i=[e])),na(i,t)},rtp:aa,tb:ra},la="request",da="response",ha=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],ca=["e"],ua=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function fa(e){return ua.test(e)}const ga=["d","dl","nor","ot","rtp","su"];const ma=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const pa=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ya(e){return pa.includes(e)||fa(e)}const va={[da]:function(e){return ha.includes(e)||ga.includes(e)||ma.includes(e)||fa(e)},[sa]:function(e){return ha.includes(e)||ca.includes(e)||fa(e)},[la]:function(e){return ha.includes(e)||ga.includes(e)||fa(e)}};function Ta(e,t={}){const i={};if(null==e||"object"!=typeof e)return i;const s=t.version||e.v||1,r=t.reportingMode||la,n=1===s?ya:va[r];let a=Object.keys(e).filter(n);const o=t.filter;"function"==typeof o&&(a=a.filter(o));const l=r===da||r===sa;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const d=x({},oa,t.formatters),h={version:s,reportingMode:r,baseUrl:t.baseUrl};return a.sort().forEach(t=>{let r=e[t];const n=d[t];if("function"==typeof n&&(r=n(r,h)),"v"===t){if(1===s)return;r=s}"pr"==t&&1===r||(l&&"ts"===t&&!m(r)&&(r=Date.now()),function(e){return"number"==typeof e?m(e):null!=e&&""!==e&&!1!==e}(r)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof r&&(r=new Fn(r)),i[t]=r))}),i}function Ea(e,t,i){return x(e,function(e,t={}){const i={};if(!e)return i;const s=ia(Ta(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(s).reduce((e,[t,i])=>{const s=zn(i,{whitespace:!1});return s&&(e[t]=s),e},i)}(t,i))}function Sa(e,t={}){if(!e)return"";const i=function(e,t={}){return e?zn(Ta(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(i)}const Aa=/CMCD=[^&#]+/;function ba(e,t,i){const s=function(e,t={}){return e?`CMCD=${Sa(e,t)}`:""}(t,i);if(!s)return e;if(Aa.test(e))return e.replace(Aa,s);const r=e.includes("?")?"&":"?";return`${e}${r}${s}`}function La(e,t,i,s){e&&Object.keys(t).forEach(r=>{const n=e.filter(e=>e.groupId===r).map(e=>{const n=x({},e);return n.details=void 0,n.attrs=new yi(n.attrs),n.url=n.attrs.URI=Ra(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=s,n});e.push(...n)})}function Ra(e,t,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(e=>{e&&l.searchParams.set(e,n[e])}),l.href}class Ia extends M{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Ia.CDMCleanupPromise?[Ia.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{const{initDataType:t,initData:i}=e,s=`"${e.type}" event: init data type: "${t}"`;if(this.debug(s),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Ui(this.config));const t=e.map(Ni).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(r=>{const n=Fi(r);if("sinf"!==t||n!==xi.FAIRPLAY)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);let a;try{const e=le(new Uint8Array(i)),t=Ae(Ii(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24))}catch(e){return void this.warn(`${s} Failed to parse sinf: ${e}`)}const o=K(a),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this;let h=l[o];for(let e=0;e<d.length;e++){const s=d[e],r=s.decryptdata;if(!r.keyId)continue;const n=K(r.keyId);if(Ai(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(o)){if(h=l[n],!h)continue;if(r.pssh)break;delete l[n],r.pssh=new Uint8Array(i),r.keyId=a,h=l[o]=h.then(()=>this.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-key-match")),h.catch(e=>this.handleError(e));break}}h||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.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=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(E.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(E.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=null==t?void 0:t[e];return s?s.licenseUrl:e===xi.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=null==t?void 0:t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,s=t.map(e=>e.audioCodec).filter(i),r=t.map(e=>e.videoCodec).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise((t,i)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,s,r).then(e=>t({keySystem:a,mediaKeys:e})).catch(t=>{e.length?n(e):i(t instanceof wa?t:new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};n(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Bi&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){var s;const r=function(e,t,i,s){let r;switch(e){case xi.FAIRPLAY:r=["cenc","sinf"];break;case xi.WIDEVINE:case xi.PLAYREADY:r=["cenc"];break;case xi.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,s){return[{initDataTypes:e,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}(r,t,i,s)}(e,t,i,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],a=null==(s=n)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ht(r)}`),a=this.requestMediaKeySystemAccess(e,r);const t=n=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const r=t.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,s.then(t=>t?this.setMediaKeysServerCertificate(i,e,t):i)));return r.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${K(e.keyId||[])} keyUri: ${e.uri}`);const s=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=ka(t),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${K(e.decryptdata.keyId||[])}\n } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Ni(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{const s=Ni(e);s?t(s):i(new Error(`Unable to find format for key-system "${e}"`))}).catch(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=Ui(this.config),i=e.map(Fi).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(i)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){const s=Pa(e,t[i]);if(s)return s}}loadKey(e){const t=e.keyInfo.decryptdata,i=ka(t),s=this.bannedKeyIds[i];if(s||"internal-error"===this.getKeyStatus(t)){const i=Da(s||"internal-error",t);return this.handleError(i,e.frag),Promise.reject(i)}const r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[i];if(!n){const s=this.getKeySystemForKeyPromise(t).then(({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t}))))).then(e=>{const i=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")});return s.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[i]=s,s}return n.catch(i=>{if(i instanceof wa){const s=_({},i.data);"internal-error"===this.getKeyStatus(t)&&(s.decryptdata=t);const r=new wa(s,i.message);this.handleError(r,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof wa){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${K(i.keyId||[])})`:""}`),this.hls.trigger(E.ERROR,e.data)}else this.error(e.message),this.hls.trigger(E.ERROR,{type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=ka(e),i=this.keyIdToKeySessionPromise[t];if(!i){const t=Fi(e.keyFormat),i=t?[t]:Ui(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Ui(this.config)),0===e.length)throw new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ht({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}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((e,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(i)}}));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(e=>-1===i.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,i,s){var r;const n=null==(r=this.config.drmSystems)||null==(r=r[e.keySystem])?void 0:r.generateRequest;if(n)try{const s=n.call(this.hls,t,i,e);if(!s)throw new Error("Invalid response from configured generateRequest filter");t=s.initDataType,i=s.initData?s.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const a=ka(e.decryptdata),o=e.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${a} URI: ${o} (init data type: ${t} length: ${i.byteLength})`);const l=new qs,d=e._onmessage=t=>{const i=e.mediaKeysSession;if(!i)return void l.emit("error",new Error("invalid state"));const{messageType:s,message:r}=t;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(e,r).catch(e=>{l.eventNames().length?l.emit("error",e):this.handleError(e)}):"license-release"===s?e.keySystem===xi.FAIRPLAY&&this.updateKeySession(e,ki("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${s}"`)},h=(e,t)=>{let i;t.keyStatus=e,e.startsWith("usable")?l.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=Da(e,t.decryptdata):"expired"===e?i=new Error(`key expired (keyId: ${a})`):"released"===e?i=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${a})`),i&&(l.eventNames().length?l.emit("error",i):this.handleError(i))},c=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const i=this.getKeyStatuses(e);if(!Object.keys(i).some(e=>"status-pending"!==i[e]))return;if("expired"===i[a])return this.log(`Expired key ${ht(i)} in key-session "${e.mediaKeysSession.sessionId}"`),void this.renewKeySession(e);let s=i[a];if(s)h(s,e);else{var r;const t=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(r=e.keyStatusTimeouts)[a]||(r[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const i=this.getKeyStatus(e.decryptdata);if(i&&"status-pending"!==i)return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${i} from other session.`),h(i,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),s="internal-error",h(s,e)},t)),this.log(`No status for keyId ${a} (${ht(i)}).`)}};Is(e.mediaKeysSession,"message",d),Is(e.mediaKeysSession,"keystatuseschange",c);const u=new Promise((e,t)=>{l.on("error",t),l.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(t=>{throw new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>u).catch(t=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((i,s)=>{if("string"==typeof s&&"object"==typeof i){const e=s;s=i,i=e}const r="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);e.keySystem===xi.PLAYREADY&&16===r.length&&Pi(r);const n=K(r);"internal-error"===i&&(this.bannedKeyIds[n]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=i}),t}fetchServerCertificate(e){const t=this.config,i=new(0,t.loader)(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((r,n)=>{const a={responseType:"arraybuffer",url:s},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,i,s)=>{r(e.data)},onError:(t,i,r,o)=>{n(new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:_({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${s}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,r)=>{n(new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(e,t,i)=>{n(new Error("aborted"))}};i.load(a,l,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,r)=>{e.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(e=>{r(new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,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"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let t;for(let i=0,s=r.length;i<s;i++){var n,a;t=r[i];const s=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;s&&o&&e.setRequestHeader(s,o)}}const o=s.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ki(atob(l))}setupLicenseXHR(e,t,i,s){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,s)}).catch(n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,i,s)}).then(i=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:i||s}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((s,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,a,n,e)}catch(e){this.error(e)}s(t)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(s,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then(({xhr:t,licenseChallenge:i})=>{e.keySystem==xi.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,Is(i,"encrypted",this.onMediaEncrypted),Is(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(ks(e,"encrypted",this.onMediaEncrypted),ks(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};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,Hi.clearKeyUriToKeyIdMap();const r=s.length;Ia.CDMCleanupPromise=Promise.all(s.map(e=>this.removeSession(e)).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i,decryptdata:s}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${K((null==s?void 0:s.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(e=>self.clearTimeout(n[e]));const{drmSystemOptions:a}=this.config,o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(e=>"persistent-license"===e)))}(a)?new Promise((e,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(i)}):Promise.resolve();return o.catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function ka(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return K(e.keyId)}function Pa(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}Ia.CDMCleanupPromise=void 0;class wa extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Da(e,t){const i="output-restricted"===e,s=i?T.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:T.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new wa({type:v.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:t},i?"HDCP level output restricted":`key status changed to "${e}"`)}function xa(e,t){let i;try{i=new Event("addtrack")}catch(e){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function Ca(e,t){const i=e.mode;if("disabled"===i&&(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: ${t}`)}catch(i){$.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){$.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function _a(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===i&&(e.mode=i)}function Ma(e,t,i,s){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,i){const s=[],r=function(e,t){if(t<=e[0].startTime)return 0;const i=e.length-1;if(t>e[i].endTime)return-1;let s,r=0,n=i;for(;r<=n;)if(s=Math.floor((n+r)/2),t<e[s].startTime)n=s-1;else{if(!(t>e[s].startTime&&r<i))return s;r=s+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(e.cues,t,i);for(let t=0;t<r.length;t++)s&&!s(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function Oa(e){const t=[];for(let i=0;i<e.length;i++){const s=e[i];"subtitles"!==s.kind&&"captions"!==s.kind||!s.label||t.push(e[i])}return t}function Fa(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}const Na=.025;let Ua=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Ba(e,t,i){return`${e.identifier}-${i+1}-${Fa(t)}`}class $a{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,null==(e=this.assetListLoader)||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;if(e<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(t=this.assetList[e])?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 Va(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-Va(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=m(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 Va(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Na))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration: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"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Ua.Range:Ua.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}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||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function Va(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Na)?t.start:t.start+t.duration}function Ga(e,t,i){const s=new self.URL(e,i);return"data:"!==s.protocol&&s.searchParams.set("_HLS_primary_id",t),s}function Ha(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function Ka(e){const t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}class ja{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(E.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(E.LEVEL_LOADED,n),r.once(E.AUDIO_TRACK_LOADED,n),r.once(E.SUBTITLE_TRACK_LOADED,n),r.on(E.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(E.BUFFER_APPENDED,()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,r.trigger(E.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=Ga(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,r=di.bufferInfo(e,s,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=di.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(null==(e=this.hls)?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(){var e;this.mediaAttached&&(null!=(e=this.hls)&&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(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;null==(s=this.hls)||s.on(e,t)}once(e,t,i){var s;null==(s=this.hls)||s.once(e,t)}off(e,t,i){var s;null==(s=this.hls)||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Ka(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class Wa extends M{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]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(t&&"primary"!==t&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return s}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){const e=i[s].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return s}return-1}findEventIndex(e){const t=this.items;if(t)for(let s=t.length;s--;){var i;if((null==(i=t[s].event)?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){const i=e.assetList,s=i.length;if(s>1)for(let e=0;e<s;e++){const r=i[e];if(!r.error){const i=r.timelineStart;if(t===i||t>i&&(t<i+(r.duration||0)||e===s-1))return e}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,i=e[e.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:s}=i,r=this.events,n=this.parseDateRanges(s,{url:i.url},t),a=Object.keys(s),o=r?r.filter(e=>!a.includes(e.identifier)):[];n.length&&n.sort((e,t)=>{const i=e.cue.pre,s=e.cue.post,r=t.cue.pre,n=t.cue.post;if(i&&!r)return-1;if(r&&!i)return 1;if(s&&!n)return 1;if(n&&!s)return-1;if(!(i||r||s||n)){const i=e.startTime,s=t.startTime;if(i!==s)return i-s}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=n,o.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],i=!1){const s=this.events||[];if(s.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(s,e);(i||t.length||(null==r?void 0:r.length)!==n.length||n.some((e,t)=>Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const s=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new $a(o,t),this.eventMap[a]=e,!1===i&&(e.appendInPlace=i)),s.push(e)}}return s}parseSchedule(e,t){const i=[],s=t.main.details,r=s.live?1/0:s.edge;let n=0;if((e=e.filter(e=>!(e.error||e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let s=0,o=0;if(e.forEach((t,a)=>{const l=t.cue.pre,d=t.cue.post,h=e[a-1]||null,c=t.appendInPlace,u=d?r:t.startOffset,f=t.duration,g=t.timelineOccupancy===Ua.Range?f:0,m=t.resumptionOffset,p=(null==h?void 0:h.startTime)===u,y=u+t.cumulativeDuration;let v=c?y+f:u+m;if(l||!d&&u<=0){const e=o;o+=g,t.timelineStart=y;const s=n;n+=f,i.push({event:t,start:y,end:v,playout:{start:s,end:n},integrated:{start:e,end:o}})}else{if(!(u<=r))return;{if(!p){const r=u-s;if(r>.033){const l=s,d=o;o+=r;const h=n;n+=r;const c={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+r,playout:{start:h,end:n},integrated:{start:d,end:o}};i.push(c)}else r>0&&h&&(h.cumulativeDuration+=r,i[i.length-1].end=u)}d&&(v=y),t.timelineStart=y;const r=o;o+=g;const l=n;n+=f,i.push({event:t,start:y,end:v,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const T=t.resumeTime;s=d||T>r?r:T}),s<r){var a;const e=s,t=o,l=r-s;o+=l;const d=n;n+=l,i.push({previousEvent:(null==(a=i[i.length-1])?void 0:a.event)||null,nextEvent:null,start:s,end:e+l,playout:{start:d,end:n},integrated:{start:t,end:o}})}this.setDurations(r,n,o)}else{const e=0;i.push({previousEvent:null,nextEvent:null,start:e,end:r,playout:{start:e,end:r},integrated:{start:e,end:r}}),this.setDurations(r,r,r)}return i}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 r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,h=l?0:d?s:a.startTime;this.updateAssetDurations(a);if(n===h?a.cumulativeDuration=r:(r=0,n=h),!d&&a.snapOptions.in&&(a.resumeAnchor=Et(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const c=m(a.resumeOffset)?a.resumeOffset:a.duration;r+=c})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,s=e.startTime+e.resumptionOffset;if(Math.abs(i-s)>Na)return this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1;return!Object.keys(t).some(s=>{const r=t[s].details,n=r.edge;if(i>=n)return this.log(`"${e.identifier}" resumption ${i} past ${s} playlist end ${n}`),!1;const a=Et(null,r.fragments,i);if(!a)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===s?.175:0;return!(Math.abs(a.start-i)<Na+o||Math.abs(a.end-i)<Na+o)&&(this.log(`"${e.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}e.duration=s&&!r?Math.max(i,e.duration):i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function qa(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class Ya{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=Ga(i,this.hls.sessionId,e.baseUrl)}catch(t){const s=this.assignAssetListError(e,T.ASSET_LIST_LOAD_ERROR,t,i);return void this.hls.trigger(E.ERROR,s)}t&&"data:"!==s.protocol&&s.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:s.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,i,s,r)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const t=this.assignAssetListError(e,T.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,r);return void this.hls.trigger(E.ERROR,t)}e.assetListResponse=n,this.hls.trigger(E.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:r})},onError:(t,i,s,r)=>{const n=this.assignAssetListError(e,T.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,r,s);this.hls.trigger(E.ERROR,n)},onTimeout:(t,i,s)=>{const r=this.assignAssetListError(e,T.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,s);this.hls.trigger(E.ERROR,r)}};return n.load(a,l,d),this.hls.trigger(E.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,i,s,r,n){return e.error=i,{type:v.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:n,stats:r}}}function za(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function Xa(e,t){return`[${e}] Advancing timeline position to ${t}`}class Qa{constructor(e){this.buffered=void 0;const t=(t,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}const Ja={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},Za=e=>String.fromCharCode(Ja[e]||e),eo=15,to=100,io={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},so={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ro={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},no={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ao=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class oo{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i="function"==typeof t?t():t;$.log(`${this.time} [${e}] ${i}`)}}}const lo=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class ho{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class co{constructor(){this.uchar=" ",this.penState=new ho}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class uo{constructor(e){this.chars=[],this.pos=0,this.currPenState=new ho,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<to;e++)this.chars.push(new co);this.logger=e}equals(e){for(let t=0;t<to;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<to;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<to;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>to&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=to)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].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=Za(e);this.pos>=to?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<to;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<to;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 fo{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<eo;t++)this.rows.push(new uo(e));this.logger=e}reset(){for(let e=0;e<eo;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<eo;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<eo;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<eo;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 = "+ht(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<eo;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[e].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[t-this.nrRollUpRows+s+1].copy(i.rows[e+s])}}this.currRow=t;const i=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,s=Math.max(t-1,0);i.setCursor(e.indent),e.color=i.chars[s].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 = "+ht(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const 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 i=0;i<eo;i++){const r=this.rows[i].getTextString();r&&(s=i+1,e?t.push("Row "+s+": '"+r+"'"):t.push(r.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class go{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 fo(i),this.nonDisplayedMemory=new fo(i),this.lastOutputScreen=new fo(i),this.currRollUpRow=this.displayedMemory.rows[14],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[14],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),"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)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(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"),"MODE_POP-ON"===this.mode){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: "+ht(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const 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))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class mo{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new oo;this.channels=[null,new go(e,t,s),new go(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const i=127&t[e],s=127&t[e+1];let r=!1,n=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+lo([t[e],t[e+1]])+"] -> ("+lo([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(yo(i,s,a)){po(null,null,a),this.logger.log(3,()=>"Repeated command ("+lo([i,s])+") is dropped");continue}po(i,s,this.cmdHistory),r=this.parseCmd(i,s),r||(r=this.parseMidrow(i,s)),r||(r=this.parsePAC(i,s)),r||(r=this.parseBackgroundAttributes(i,s))}else po(null,null,a);if(!r&&(n=this.parseChars(i,s),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+lo([i,s])+" orig: "+lo([t[e],t[e+1]]))}}parseCmd(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;const i=20===e||21===e||23===e?1:2,s=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1: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 ("+lo([e,t])+")"),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const s=e<=23?1:2;i=t>=64&&t<=95?1===s?io[e]:ro[e]:1===s?so[e]:no[e];const r=this.channels[s];return!!r&&(r.setPAC(this.interpretPAC(i,t)),this.currentChannel=s,!0)}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,s.underline=!(1&~i),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=4*Math.floor((i-16)/2),s}parseChars(e,t){let i,s=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let e;e=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,()=>"Special char '"+Za(e)+"' in channel "+i),s=[e]}else e>=32&&e<=127&&(s=0===t?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+lo(s).join(",")),s}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let i;const s={};16===e||24===e?(i=Math.floor((t-32)/2),s.background=ao[i],t%2==1&&(s.background=s.background+"_semi")):45===t?s.background="transparent":(s.foreground="black",47===t&&(s.underline=!0));const r=e<=23?1:2;return this.channels[r].setBkgData(s),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}po(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 po(e,t,i){i.a=e,i.b=t}function yo(e,t,i){return i.a===e&&i.b===t}var vo=function(){if(null!=Di&&Di.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const i=t.toLowerCase();return!!~e.indexOf(i)&&i}function s(e){return i(t,e)}function r(e,...t){let i=1;for(;i<arguments.length;i++){const t=arguments[i];for(const i in t)e[i]=t[i]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=t,u=n,f=a,g=null,m="",p=!0,y="auto",v="start",T=50,E="middle",S=50,A="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(e){d=""+e}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return h},set:function(e){h=!!e}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(t){const s=function(t){return i(e,t)}(t);if(!1===s)throw new SyntaxError("An invalid or illegal string was specified.");m=s,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},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",r({},l,{get:function(){return v},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return E},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},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",r({},l,{get:function(){return A},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");A=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class To{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Eo(e){function t(e,t,i,s){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(s||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class So{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 Ao(e,t,i,s){const r=s?e.split(s):[e];for(const e in r){if("string"!=typeof r[e])continue;const s=r[e].split(i);if(2!==s.length)continue;t(s[0],s[1])}}const bo=new vo(0,0,""),Lo="middle"===bo.align?"middle":"center";function Ro(e,t,i){const s=e;function r(){const t=Eo(e);if(null===t)throw new Error("Malformed timestamp: "+s);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=r(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);e=e.slice(3),n(),t.endTime=r(),n(),function(e,t){const s=new So;Ao(e,function(e,t){let r;switch(e){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===t){s.set(e,i[r].region);break}break;case"vertical":s.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),s.integer(e,r[0]),s.percent(e,r[0])&&s.set("snapToLines",!1),s.alt(e,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",Lo,"end"]);break;case"position":r=t.split(","),s.percent(e,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",Lo,"end","line-left","line-right","auto"]);break;case"size":s.percent(e,t);break;case"align":s.alt(e,t,["start",Lo,"end","left","right"])}},/:/,/\s/),t.region=s.get("region",null),t.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===bo.line&&(r=-1),t.line=r,t.lineAlign=s.get("lineAlign","start"),t.snapToLines=s.get("snapToLines",!0),t.size=s.get("size",100),t.align=s.get("align",Lo);let n=s.get("position","auto");"auto"===n&&50===bo.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function Io(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class ko{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new To,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function i(){let e=t.buffer,i=0;for(e=Io(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;const s=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),s}function s(e){Ao(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=i();const s=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=i(),t.state){case"HEADER":/:/.test(e)?s(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new vo(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Ro(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==e.indexOf("--\x3e");if(!e||i&&(r=!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+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const 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}}const Po=/\r\n|\n\r|\n|\r/g,wo=function(e,t,i=0){return e.slice(i,i+t.length)===t};function Do(e,t,i){return Fa(e.toString())+Fa(t.toString())+Fa(i)}function xo(e,t,i,s,r,n,a){const o=new ko,l=H(new Uint8Array(e)).trim().replace(Po,"\n").split("\n"),d=[],h=t?function(e,t=1){return Jr(e,9e4,1/t)}(t.baseTime,t.timescale):0;let c,u="00:00.000",f=0,g=0,p=!0;o.oncue=function(e){const n=i[s];let a=i.ccOffset;const o=(f-h)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(e,t,i){let s=e[t],r=e[s.prevCC];if(!r||!r.new&&s.new)return e.ccOffset=e.presentationOffset=s.start,void(s.new=!1);for(;null!=(n=r)&&n.new;){var n;e.ccOffset+=s.start-r.start,s.new=!1,s=r,r=e[s.prevCC]}e.presentationOffset=i}(i,s,o)),o){if(!t)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=e.endTime-e.startTime,u=on(9e4*(e.startTime+a-g),9e4*r)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=Do(e.startTime,e.endTime,m)),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(d)},l.forEach(e=>{if(p){if(wo(e,"X-TIMESTAMP-MAP=")){p=!1,e.slice(16).split(",").forEach(e=>{wo(e,"LOCAL:")?u=e.slice(6):wo(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{g=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(m(t)&&m(i)&&m(s)&&m(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*s,t+=36e5*r,t}(u)/1e3}catch(e){c=e}return}""===e&&(p=!1)}o.parse(e+"\n")}),o.flush()}const Co="stpp.ttml.im1t",_o=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Mo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Oo={left:"start",center:"center",right:"end",start:"start",end:"end"};function Fo(e,t,i,s){const r=fe(new Uint8Array(e),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map(e=>H(e)),a=function(e,t,i=1,s=!1){return Jr(e,t,1/i,s)}(t.baseTime,1,t.timescale);try{n.forEach(e=>i(function(e,t){const i=(new DOMParser).parseFromString(e,"text/xml"),s=i.getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((e,t)=>(e[t]=s.getAttribute(`ttp:${t}`)||r[t],e),{}),a="preserve"!==s.getAttribute("xml:space"),o=Uo(No(s,"styling","style")),l=Uo(No(s,"layout","region")),d=No(s,"body","[begin]");return[].map.call(d,e=>{const i=Bo(e,a);if(!i||!e.hasAttribute("begin"))return null;const s=Go(e.getAttribute("begin"),n),r=Go(e.getAttribute("dur"),n);let d=Go(e.getAttribute("end"),n);if(null===s)throw Vo(e);if(null===d){if(null===r)throw Vo(e);d=s+r}const h=new vo(s-t,d-t,i);h.id=Do(h.startTime,h.endTime,h.text);const c=function(e,t,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce((i,n)=>{const a=$o(t,s,n)||$o(e,s,n)||$o(r,s,n);return a&&(i[n]=a),i},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:u}=c;if(u){const e=Oo[u];e&&(h.lineAlign=e),h.align=u}return x(h,c),h}).filter(e=>null!==e)}(e,a)))}catch(e){s(e)}}function No(e,t,i){const s=e.getElementsByTagName(t)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function Uo(e){return e.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Bo(e,t){return[].slice.call(e.childNodes).reduce((e,i,s)=>{var r;return"br"===i.nodeName&&s?e+"\n":null!=(r=i.childNodes)&&r.length?Bo(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function $o(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Vo(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Go(e,t){if(!e)return null;let i=Eo(e);return null===i&&(_o.test(e)?i=function(e,t){const i=_o.exec(e),s=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/t.frameRate}(e,t):Mo.test(e)&&(i=function(e,t){const i=Mo.exec(e),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return 1e3*s;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}(e,t))),i}class Ho{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(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function Ko(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function jo(e,t){return!!e&&e.kind===Ko(t)&&bn(t,e)}function Wo(e,t,i,s){return Math.min(t,s)-Math.max(e,i)}const qo=/\s/,Yo={newCue(e,t,i,s){const r=[];let n,a,o,l,d;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(n=s.rows[u],o=!0,l=0,d="",!n.isEmpty()){var c;for(let e=0;e<n.chars.length;e++)qo.test(n.chars[e].uchar)&&o?l++:(d+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;const s=Io(d.trim()),f=Do(t,i,s);null!=e&&null!=(c=e.cues)&&c.getCueById(f)||(a=new h(t,i,s),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return e&&r.length&&(r.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),r.forEach(t=>Ca(e,t))),r}};const zo=/(\d+)-(\d+)\/(\d+)/;class Xo{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Qo,this.controller=new self.AbortController,this.stats=new X}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}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();const r=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(x({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&m(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout);(mn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var r;this.response=this.loader=i;const a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(a-s.loading.start)),!i.ok){const{status:e,statusText:t}=i;throw new Jo(t||"fetch, bad network response",e,i)}s.loading.first=a,s.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=zo.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(m(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(i.headers)||s.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&m(t.highWaterMark)?this.loadProgressively(i,s,e,t.highWaterMark,o):n?i.arrayBuffer():"json"===e.responseType?i.json():i.text()}).then(i=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[a];l&&(s.loaded=s.total=l);const d={url:o.url,data:i,code:o.status},h=null==(r=this.callbacks)?void 0:r.onProgress;h&&!m(t.highWaterMark)&&h(s,e,i,o),null==(n=this.callbacks)||n.onSuccess(d,s,e,o)}).catch(t=>{var i;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=t&&t.code||0,n=t?t.message:null;null==(i=this.callbacks)||i.onError({code:r,text:n},e,t?t.details:null,s)})}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,r){const n=new Hs,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return t.loaded+=d,d<s||n.dataLength?(n.push(l),n.dataLength>=s&&r(t,i,n.flush().buffer,e)):r(t,i,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}}function Qo(e,t){return new self.Request(e.url,t)}class Jo extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Zo=/^age:\s*[\d.]+\s*$/im;class el{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new X,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const 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()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){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 r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return r(i,t.url)}).catch(e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(e=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:e.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:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(const t in s)e.setRequestHeader(t,s[t]);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=r&&m(r)?r:n,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,r=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const s=t.status,l="text"===t.responseType?t.responseText:null;if(s>=200&&s<300){const r=null!=l?l:t.response;if(null!=r){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,e,r,t);const d={url:t.responseURL,data:r,code:s};return void(null==(a=this.callbacks)||a.onSuccess(d,i,e,t))}}const d=r.loadPolicy.errorRetry;var o;if(Dt(d,i.retry,!1,{url:e.url,data:void 0,code:s}))this.retry(d);else $.error(`${s} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:s,text:t.statusText},e,t,i)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Dt(e,this.stats.retry,!0))this.retry(e);else{var t;$.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Pt(e,i.retry),i.retry++,$.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Zo.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 tl=_(_({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:el,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends M{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:i,partCurrent:s,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!i||!a)return;const o=performance.now(),l=s?s.stats:i.stats,d=s?s.duration:i.duration,h=o-l.loading.start,c=r.minAutoLevel,u=i.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,p=!!e||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const y=r.mainForwardBufferInfo;if(!p&&null===y)return;const v=this.bwEstimator.getEstimateTTFB(),T=Math.abs(a.playbackRate);if(h<=Math.max(v,d/(2*T)*1e3))return;const S=y?y.len/T:0,A=l.loading.first?l.loading.first-l.loading.start:-1,b=l.loaded&&A>-1,L=this.getBwEstimate(),R=r.levels,I=R[u],k=Math.max(l.loaded,Math.round(d*(i.bitrate||I.averageBitrate)/8));let P=b?h-A:h;P<1&&b&&(P=Math.min(h,8*l.loaded/L));const w=b?1e3*l.loaded/P:0,D=v/1e3,x=w?(k-l.loaded)/w:8*k/L+D;if(x<=S)return;const C=w?8*w:L,_=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),M=this.hls.config.abrBandWidthUpFactor;let O,F=Number.POSITIVE_INFINITY;for(O=u-1;O>c;O--){const e=R[O].maxBitrate,t=!R[O].details||_;if(F=this.getTimeToLoadFrag(D,C,d*e,t),F<Math.min(S,d+D))break}if(F>=x)return;if(F>10*d)return;b?this.bwEstimator.sample(h-Math.min(v,A),l.loaded):this.bwEstimator.sampleTTFB(h);const N=R[O].maxBitrate;this.getBwEstimate()*M>N&&this.resetEstimator(N);const U=this.findBestLevel(N,c,O,0,S,1,1);U>-1&&(O=U),this.warn(`Fragment ${i.sn}${s?" part "+s.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${i.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${x.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|A} ms\n Current BW estimate: ${m(L)?0|L:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|N} bps`),r.nextLoadLevel=r.nextAutoLevel=O,this.clearTimer();const B=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${i.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,O>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,O,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||x>2*F?B():this.timer=self.setInterval(B,1e3*F),r.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:s,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new w(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=t.part)?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 T.BUFFER_ADD_CODEC_ERROR:case T.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case T.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:i,partCurrent:s}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){const t=performance.now(),i=s?s.stats:e.stats,r=t-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,i,s){return e+i/t+(s?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,r=s.end-s.first;m(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===R&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=i?i.duration:t.duration,r=this.hls.levels[t.level],n=(r.loaded?r.loaded.bytes:0)+s.loaded,a=(r.loaded?r.loaded.duration:0)+e;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(E.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,r=null!=s&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==R||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const s=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,s)&&t[e].loadError<=t[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,s,l,0,d,h);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=h=1}}const u=this.findBestLevel(o,n,s,l,c,d,h);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,r,n,a){var o;const l=s+r,d=this.lastLoadedFragLevel,h=-1===d?this.hls.firstLevel:d,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:y}=this.hls;if(1===f.length)return 0;const v=f[h],T=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===p||-1===d;let S,A="SDR",b=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:R}=y,I=this.audioTracksByGroup||(this.audioTracksByGroup=ut(g));let k=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(e,t,i,s){return e.slice(i,s+1).reduce((e,i,s)=>{if(!i.codecSet)return e;const r=i.audioGroups;let n=e[i.codecSet];n||(e[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,s),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;const i=t.groups[e];i&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach(e=>{n.channels[e]=(n.channels[e]||0)+i.channels[e]}))}),e},{})}(f,I,t,i)),r=function(e,t,i,s,r){const n=Object.keys(e),a=null==s?void 0:s.channels,o=null==s?void 0:s.audioCodec,l=null==r?void 0:r.videoCodec,d=a&&2===parseInt(a);let h=!1,c=!1,u=1/0,f=1/0,g=1/0,p=1/0,y=0,v=[];const{preferHDR:T,allowedVideoRanges:E}=dt(t,r);for(let t=n.length;t--;){const i=e[n[t]];h||(h=i.channels[2]>0),u=Math.min(u,i.minHeight),f=Math.min(f,i.minFramerate),g=Math.min(g,i.minBitrate),E.filter(e=>i.videoRanges[e]>0).length>0&&(c=!0)}u=m(u)?u:0,f=m(f)?f:0;const S=Math.max(1080,u),A=Math.max(30,f);g=m(g)?g:i,i=Math.max(g,i),c||(t=void 0);const b=n.length>1;return{codecSet:n.reduce((t,s)=>{const r=e[s];if(s===t)return t;if(v=c?E.filter(e=>r.videoRanges[e]>0):[],b){if(r.minBitrate>i)return ct(s,`min bitrate of ${r.minBitrate} > current estimate of ${i}`),t;if(!r.hasDefaultAudio)return ct(s,"no renditions with default or auto-select sound found"),t;if(o&&s.indexOf(o.substring(0,4))%5!=0)return ct(s,`audio codec preference "${o}" not found`),t;if(a&&!d){if(!r.channels[a])return ct(s,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||d)&&h&&0===r.channels[2])return ct(s,"no renditions with stereo sound found"),t;if(r.minHeight>S)return ct(s,`min resolution of ${r.minHeight} > maximum of ${S}`),t;if(r.minFramerate>A)return ct(s,`min framerate of ${r.minFramerate} > maximum of ${A}`),t;if(!v.some(e=>r.videoRanges[e]>0))return ct(s,`no variants with VIDEO-RANGE of ${ht(v)} found`),t;if(l&&s.indexOf(l.substring(0,4))%5!=0)return ct(s,`video codec preference "${l}" not found`),t;if(r.maxScore<y)return ct(s,`max score of ${r.maxScore} < selected max of ${y}`),t}return t&&(Ue(s)>=Ue(t)||r.fragmentError>e[t].fragmentError)?t:(p=r.minIndex,y=r.maxScore,s)},void 0),videoRanges:v,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:p}}(s,A,e,L,R),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:d,preferHDR:h}=r;k=d,S=n,A=h?a[a.length-1]:a[0],b=o,e=Math.max(e,l),this.log(`picked start tier ${ht(r)}`)}else S=null==v?void 0:v.codecSet,A=null==v?void 0:v.videoRange;const P=u?u.duration:c?c.duration:0,w=this.bwEstimator.getEstimateTTFB()/1e3,D=[];for(let o=i;o>=t;o--){var x;const t=f[o],c=o>h;if(!t)continue;if(y.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&Xe(t,I,A,b,e,L)?(t.supportedPromise=Qe(t,I,i,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;const i=this.hls.levels,s=i.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${s} ${ht(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${s} not smooth or powerEfficient: ${ht(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${ht(e)}`),s>-1&&i.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=Ye}if((S&&t.codecSet!==S||A&&t.videoRange!==A||c&&b>t.frameRate||!c&&b>0&&b<t.frameRate||null!=(x=t.supportedResult)&&null!=(x=x.decodingInfoResults)&&x.some(e=>!1===e.smooth))&&(!E||o!==k)){D.push(o);continue}const g=t.details,v=(u?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||P;let R;R=c?a*e:n*e;const C=P&&s>=2*P&&0===r?t.averageBitrate:t.maxBitrate,_=this.getTimeToLoadFrag(w,R,C*v,void 0===g);if(R>=C&&(o===d||0===t.loadError&&0===t.fragmentError)&&(_<=w||!m(_)||T&&!this.bitrateTestDelay||_<l)){const e=this.forcedAutoLevel;return o===p||-1!==e&&e===p||(D.length&&this.trace(`Skipped level(s) ${D.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[D[0]].codecs}" ${f[D[0]].videoRange}; not compatible with "${S}" ${A}`),this.info(`switch candidate:${h}->${o} adjustedbw(${Math.round(R)})-bitrate=${Math.round(R-C)} ttfb:${w.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${_.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${p}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},bufferController:class extends M{constructor(e,t){var i;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:t,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(i=V(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this),e.off(E.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?x(i,s.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(i[t]=x({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(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.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const s=V(this.appendSource);if(s){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const r=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(r),e)this._objectUrl=i.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const t=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||t&&r instanceof t,Pn(i),function(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(i=e.constructor)?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,s=t.tracks,r=s?Object.keys(s):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${ht(i,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${ht(s,(e,t)=>"initSegment"===e?void 0:t)}}`),!G(s,i)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach(e=>{const t=e,i=s[t];if(i){const e=i.buffer;if(e){const s=this.fragmentTracker,r=i.id;if(s.hasFragments(r)||s.hasParts(r)){const i=di.getBuffered(e);s.detectEvictedFragments(t,i,r,null,!0)}const n=wn(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,i)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),r.removeSourceBuffer(t[i]);e&&r.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(s.removeAttribute("src"),this.appendSource&&Pn(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(E.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[wn(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Ln(this.tracks)}onBufferCodecs(e,t){var i;const s=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(e=>!s[e]);n||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(e=>{var i,r;const n=t[e],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:c}=n;let u=s[e];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[e],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;u||(u=s[e]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:d,levelCodec:l,metadata:h,id:a});const y=Ge(m,p),v=null==y?void 0:y.replace(Rn,"$1");let T=Ge(o,l);const E=null==(r=T)?void 0:r.replace(Rn,"$1");T&&y&&v!==E&&("audio"===e.slice(0,5)&&(T=Ve(T,this.appendSource)),this.log(`switching codec ${m} to ${T}`),T!==(u.pendingCodec||u.codec)&&(u.pendingCodec=T),u.container=d,this.appendChangeType(e,d,T))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(i=t.audio)?void 0:i.id)&&(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}`,r={label:`change-type=${s}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),n.changeType(s),r.codec=i,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,R))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>s||null!=t&&t.buffer&&di.isBuffered(t.buffer,s)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,R))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=t,h=l.buffering[r],{sn:c,cc:u}=a,f=self.performance.now();h.start=f;const g=a.stats.buffering,p=o?o.stats.buffering:null;0===g.start&&(g.start=f),p&&0===p.start&&(p.start=f);const y=i.audio;let S=!1;"audio"===r&&"audio/mpeg"===(null==y?void 0:y.container)&&(S=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const A=i.video,b=null==A?void 0:A.buffer;if(b&&"initSegment"!==c){const e=o||a,t=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||A.ending||A.ended){if("video"===r){const i=e.end;if(t){const e=t.frag.start;(i>e||i<this.lastVideoAppendEnd||di.isBuffered(b,e))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const t=e.start+.05*e.duration,i=b.buffered,s=this.currentOp("video");i.length||s?!s&&!di.isBuffered(b,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const L=(o||a).start,I={label:`append-${r}`,execute:()=>{var e;h.executeStart=self.performance.now();const t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(S?this.updateTimestampOffset(t,L,.1,r,c,u):void 0!==d&&m(d)&&this.updateTimestampOffset(t,d,1e-6,r,c,u)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();h.executeEnd=h.end=e,0===g.first&&(g.first=e),p&&0===p.first&&(p.first=e);const t={};this.sourceBuffers.forEach(([e,i])=>{e&&(t[e]=di.getBuffered(i))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const i={type:v.MEDIA_ERROR,parent:a.type,details:T.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},s=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)i.details=T.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!s)i.errorAction=$t(!0);else if(e.name===In&&0===this.sourceBufferCount)i.errorAction=$t(!0);else{const e=++this.appendErrors[r];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${s||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}this.hls.trigger(E.ERROR,i)}};this.log(`queuing "${r}" append sn: ${c}${o?" p: "+o.index:""} of ${a.type===R?"level":"track"} ${a.level} cc: ${u}`),this.append(I,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:r}=t;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,s,r),e)})}onFragParsed(e,t){const{frag:i,part:s}=t,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[Z]?r.push("audiovideo"):(n[Q]&&r.push("audio"),n[J]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(()=>{const e=self.performance.now();i.stats.buffering.end=e,s&&(s.stats.buffering.end=e);const t=s?s.stats:i.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:i,part:s,stats:t,id:i.type})},r).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}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(([e])=>{if(e){const i=this.tracks[e];t.type&&t.type!==e||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}});const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){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===T.BUFFER_APPEND_ERROR&&t.frag){var i;const e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;m(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||null===t)return;if(!this.sourceBufferCount)return;const s=e.config,r=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(m(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(r/n)*n-e;this.flushBackBuffer(r,n,t)}const o=s.frontBufferFlushThreshold;if(m(o)&&o>0){const e=Math.max(s.maxBufferLength,o),t=Math.max(e,n),i=Math.floor(r/n)*n+t;this.flushFrontBuffer(r,n,i)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([e,t])=>{if(t){const r=di.getBuffered(t);if(r.length>0&&i>r.start(0)){var s;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:i});const t=this.tracks[e];if(null!=(s=this.details)&&s.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([t,s])=>{if(s){const r=di.getBuffered(s),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(i>a||e>=a&&e<=o)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,s)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return m(r)?{duration:r}:null;const n=this.media.duration;return s>(m(i.duration)?i.duration:0)&&s>n||!m(n)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==e&&(m(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),void 0!==t&&void 0!==i&&(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}) ${ht(i)}`),this.tracksReady){var s;const e=null==(s=this.transferData)?void 0:s.tracks;e&&Object.keys(e).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(E.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.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 r in e){const n=r,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),r=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${ht(a)}`);try{const e=i.addSourceBuffer(r),s=wn(n),o=[n,e];t[s]=o,a.buffer=e}catch(e){var s;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[n],void this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&("video"===t||"audiovideo"===t)&&Me(i,"video")&&(s=function(e,t){const i=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)_e(t[e],"video")||i.push(t[e])}return t&&i.push(t),i.join(",")}(s,i));const r=Ge(s,e.levelCodec);return r?"audio"===t.slice(0,5)?Ve(r,this.appendSource):r:""}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",(e,t)=>{const i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;const i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const r=this.currentOp(e);r&&r.onError(s)}updateTimestampOffset(e,t,i,s,r,n){const a=t-e.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:s,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!s||!r||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=m(s.duration)?s.duration:1/0,l=m(r.duration)?r.duration:1/0,d=Math.max(0,t),h=Math.min(i,o,l);h>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`),a.remove(d,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],s=null==i?void 0:i.buffer;if(!s)throw new kn(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,s=t.map(e=>this.appendBlocker(e));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;i&&!i.updating&&this.shiftAndExecuteNext(e)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,e);s.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(e=>{i.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}},capLevelController:Dn,errorController:class extends M{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(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===R?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;const s=e.audioGroups;if(s){return this.hls.allAudioTracks.filter(e=>s.indexOf(e.groupId)>=0).some(e=>{var i;return null==(i=e.details)?void 0:i.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,r=t.context;switch(t.details){case T.FRAG_LOAD_ERROR:case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_ERROR:case T.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case T.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=$t());case T.FRAG_GAP:case T.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=_t);case T.LEVEL_EMPTY_ERROR:case T.LEVEL_PARSING_ERROR:{var n;const e=t.parent===R?t.level:s.loadLevel;t.details===T.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case T.LEVEL_LOAD_ERROR:case T.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case T.AUDIO_TRACK_LOAD_ERROR:case T.AUDIO_TRACK_LOAD_TIMEOUT:case T.SUBTITLE_LOAD_ERROR:case T.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=s.loadLevelObj;if(e&&(r.type===b&&e.hasAudioGroup(r.groupId)||r.type===L&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=_t,void(t.errorAction.flags=Nt)}return;case T.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:_t,flags:Ut});case T.KEY_SYSTEM_SESSION_UPDATE_FAILED:case T.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case T.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:_t,flags:Bt});case T.BUFFER_ADD_CODEC_ERROR:case T.REMUX_ALLOC_ERROR:case T.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:s.loadLevel);return;case T.INTERNAL_EXCEPTION:case T.BUFFER_APPENDING_ERROR:case T.BUFFER_FULL_ERROR:case T.LEVEL_SWITCH_ERROR:case T.BUFFER_STALLED_ERROR:case T.BUFFER_SEEK_OVER_HOLE:case T.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=$t())}t.type===v.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=$t())}getPlaylistRetryOrSwitchAction(e,t){const i=kt(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++;if(Dt(i,s,Lt(e),e.response))return{action:Ot,flags:Ft,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(e,t);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=kt(Rt(e)?n:r,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(s&&(e.details!==T.FRAG_GAP&&s.fragmentError++,!It(e))){if(Dt(a,o,Lt(e),e.response))return{action:Ot,flags:Ft,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;null==t&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var r,n;const t=e.details;s.loadError++,t===T.BUFFER_APPEND_ERROR&&s.fragmentError++;let l=-1;const{levels:d,loadLevel:h,minAutoLevel:c,maxAutoLevel:u}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===I&&t===T.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===T.BUFFER_ADD_CODEC_ERROR||t===T.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:e})=>s.audioCodec!==e),m="video"===e.sourceBufferName&&(t===T.BUFFER_ADD_CODEC_ERROR||t===T.BUFFER_APPEND_ERROR)&&d.some(({codecSet:e,audioCodec:t})=>s.codecSet!==e&&s.audioCodec===t),{type:p,groupId:y}=null!=(n=e.context)?n:{};for(let i=d.length;i--;){const r=(i+h)%d.length;if(r!==h&&r>=c&&r<=u&&0===d[r].loadError){var a,o;const i=d[r];if(t===T.FRAG_GAP&&f===R&&e.frag){const t=d[r].details;if(t){const i=Et(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(p===b&&i.hasAudioGroup(y)||p===L&&i.hasSubtitleGroup(y))continue;if(f===I&&null!=(a=s.audioGroups)&&a.some(e=>i.hasAudioGroup(e))||f===k&&null!=(o=s.subtitleGroups)&&o.some(e=>i.hasSubtitleGroup(e))||g&&s.audioCodec===i.audioCodec||m&&s.codecSet===i.codecSet||!g&&s.codecSet!==i.codecSet)continue}l=r;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:_t,flags:Ft,nextAutoLevel:l}}return{action:_t,flags:Nt}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case Ct:break;case _t:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===T.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s}=i,r=i.nextAutoLevel;switch(s){case Ft:this.switchLevel(e,r);break;case Ut:{const s=this.getVariantLevelIndex(e.frag),r=t.levels[s],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(i.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){t.maxHdcpLevel=et[et.indexOf(n)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Bt:{const t=e.decryptdata;if(t){const s=this.hls.levels,r=s.length;for(let i=r;i--;){var n,a;if(this.variantHasKey(s[i],t))this.log(`Banned key found in level ${i} (${s[i].bitrate}bps) or audio group "${null==(n=s[i].audioGroups)?void 0:n.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${K(t.keyId||[])}`),s[i].fragmentError++,s[i].loadError++,this.log(`Removing level ${i} with key error (${e.error})`),this.hls.removeLevel(i)}const o=e.frag;if(this.hls.levels.length<r)i.resolved=!0;else if(o&&o.type!==R){const e=o.decryptdata;e&&!t.matches(e)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&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===T.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=We(e.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${s} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(s))}}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.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 e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(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 e=s-this.lastTime,r=i-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger(E.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,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)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Bi,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Yo,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends Vs{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",k),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(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Ds,this.setInterval(500),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,success:s}=t;if(this.fragContextChanged(i)||(te(i)&&(this.fragPrevious=i),this.state=Ds),!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let e=0;e<r.length;e++)if(a>=r[e].start&&a<=r[e].end){n=r[e];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(0===i&&s!==Number.POSITIVE_INFINITY){const e=s-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let i=0;i<t.length;)if(t[i].end<=e)t.shift();else{if(!(t[i].start<e))break;t[i].start=e,i++}}),this.fragmentTracker.removeFragmentsInRange(i,e,k)}}onError(e,t){const i=t.frag;(null==i?void 0:i.type)===k&&(t.details===T.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ws&&(this.state=Ds))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&Sn(this.levels,t)?this.levels=t.map(e=>new ot(e)):(this.tracksBuffered=[],this.levels=t.map(e=>{const t=new ot(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,k),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==ws&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:a}=t;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;const e=this.mainDetails;if(!e)return void(this.startFragRequested=!1);const t=e.fragments[0];var d;if(o.details)l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&t&&(l=t.start,fs(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(Rs(n,e),l=n.fragmentStart):t&&(l=t.start,fs(n,l));e&&!this.startFragRequested&&this.setStartPosition(e,l)}if(o.details=n,this.levelLastLoaded=o,a===s&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Ds)){Et(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&Li(s.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Ri(s.method)).catch(e=>{throw r.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(i=>{const s=performance.now();r.trigger(E.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:s}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=Ds})}}doTick(){if(this.media){if(this.state===Ds){const{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;const{config:s}=this,r=this.getLoadPosition(),n=di.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),{end:a,len:o}=n,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const d=l.fragments,h=d.length,c=l.edge;let u=null;const f=this.fragPrevious;if(a<c){const e=s.maxFragLookUpTolerance,t=a>c-e?0:e;u=Et(f,d,Math.max(d[0].start,a),t),!u&&f&&f.start<d[0].start&&(u=d[0])}else u=d[h-1];if(u=this.filterReplacedPrimary(u,i.details),!u)return;const g=d[u.sn-l.startSN-1];if(g&&g.cc===u.cc&&this.fragmentTracker.getState(g)===Vt&&(u=g),this.fragmentTracker.getState(u)===Vt){const e=this.mapToInitFragWhenRequired(u);e&&this.loadFragment(e,i,a)}}}else this.state=Ds}loadFragment(e,t,i){te(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Qa(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends En{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 e=null;const t=Oa(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}const i=this.findTrackForTextTrack(e);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,s)return;Oa(i.textTracks).forEach(e=>{_a(e)})}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:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}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 r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>-1===(null==s?void 0:s.indexOf(e)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!r&&t){this.selectDefaultTrack=!1;const i=gt(t,e);if(i>-1)r=e[i];else{const e=gt(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,n),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const r=t[s];if((!i||r.default)&&(i||e)&&(!e||mt(r,e)))return s}if(e){for(let i=0;i<t.length;i++){const s=t[i];if(An(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const s=t[i];if(An(e.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){if(bn(t[i],e))return i}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==L||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&mt(e,i))return i;const s=gt(e,this.tracksInGroup);if(s>-1){const e=this.tracksInGroup[s];return this.setSubtitleTrack(s),e}if(i)return null;{const i=gt(e,t);if(i>-1)return t[i]}}}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,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Oa(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter(e=>bn(i,e))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(e=>{"disabled"!==e.mode&&e!==s&&(e.mode="disabled")}),s){const e=this.subtitleDisplay?"showing":"hidden";s.mode!==e&&(s.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!m(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});const r=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=s;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const h=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(h)}},timelineController:class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Ho(this,"textTrack1"),t=new Ho(this,"textTrack2"),i=new Ho(this,"textTrack3"),s=new Ho(this,"textTrack4");this.cea608Parser1=new mo(1,e,t),this.cea608Parser2=new mo(3,i,s)}addCues(e,t,i,s,r){let n=!1;for(let e=r.length;e--;){const s=r[e],a=Wo(s[0],s[1],t,i);if(a>=0&&(s[0]=Math.min(s[0],t),s[1]=Math.max(s[1],i),n=!0,a/(i-t)>.5))return}if(n||r.push([t,i]),this.config.renderTextTracksNatively){const r=this.captionsTracks[e];this.Cues.newCue(r,t,i,s)}else{const r=this.Cues.newCue(null,t,i,s);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:r,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;i===R&&(this.initPTS[t.cc]={baseTime:s,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,e):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(jo(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:r,languageCode:n}=t[e],a=this.getExistingTrack(r,n);if(a)i[e]=a,_a(i[e]),xa(i[e],s);else{const t=this.createTextTrack("captions",r,n);t&&(t[e]=!0,i[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(e=>{_a(s[e]),delete s[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)_a(t[e])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(e=>e.textCodec===Co);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Sn(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const e=this.media,t=e?Oa(e.textTracks):null;if(this.tracks.forEach((e,i)=>{let s;if(t){let i=null;for(let s=0;s<t.length;s++)if(t[s]&&jo(t[s],e)){i=t[s],t[s]=null;break}i&&(s=i)}if(s)_a(s);else{const t=Ko(e);s=this.createTextTrack(t,e.name,e.lang),s&&(s.mode="disabled")}s&&this.textTracks.push(s)}),null!=t&&t.length){const e=t.filter(e=>null!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const i=`textTrack${t[1]}`,s=this.captionsProperties[i];s&&(s.label=e.name,e.lang&&(s.languageCode=e.lang),s.media=e)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===R){var i,s;const{cea608Parser1:e,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(i=null==(s=t.part)?void 0:s.index)?i:-1;e&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===k)if(s.byteLength){const e=i.decryptdata,r="stats"in t;if(null==e||!e.encrypted||r){const e=this.tracks[i.level],r=this.vttCCs;r[i.cc]||(r[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===Co?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Fo(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),i.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{i.logger.log(`Failed to parse IMSC1: ${t}`),i.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[i.cc]&&-1===a)return void n.push(e);const o=this.hls;xo(null!=(t=i.initSegment)&&t.data?be(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,e=>{this._appendCues(e,i.level),o.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},t=>{const r="Missing initPTS for VTT MPEGTS"===t.message;r?n.push(e):this._fallbackToIMSC1(i,s),o.logger.log(`Failed to parse VTT cue: ${t}`),r&&a>i.cc||o.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Fo(t,this.initPTS[e.cc],()=>{i.textCodec=Co,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach(e=>Ca(i,e))}else{const s=this.tracks[t];if(!s)return;const r=s.default?"default":"subtitles"+t;i.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===k&&this.onFragLoaded(E.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!==R||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;e<s.length;e++){const t=s[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(t);this.cea608Parser1.addData(s[e].pts,i[0]),this.cea608Parser2.addData(s[e].pts,i[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!r||"video"===r){const{captionsTracks:e}=this;Object.keys(e).forEach(s=>Ma(e[s],t,i))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==s){const{textTracks:e}=this;Object.keys(e).forEach(i=>Ma(e[i],t,s))}}}extractCea608Data(e){const t=[[],[]],i=31&e[0];let s=2;for(let r=0;r<i;r++){const i=e[s++],r=127&e[s++],n=127&e[s++];if(0===r&&0===n)continue;if(!!(4&i)){const e=3&i;0!==e&&1!==e||(t[e].push(r),t[e].push(n))}}return t}},audioStreamController:class extends Vs{constructor(e,t,i){super(e,t,i,"audio-stream-controller",I),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){if(i===R){const e=t.cc,i=this.fragCurrent;if(this.initPTS[e]={baseTime:s,timescale:r,trackId:n},this.log(`InitPTS for cc: ${e} found from main: ${s/r} (${s}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===Bs){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==e)&&this.syncWithAnchor(t,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==e?(i.abortRequests(),this.syncWithAnchor(t,i)):this.state===Ds&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const s=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(t&&(null==s?void 0:s.cc)===t.cc)return;const r=(s||e).cc,n=bt(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===Ds&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=ws);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Ds):this.state=Ms,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Ds:this.doTickIdle();break;case Ms:{const{levels:e,trackId:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=Bs}break}case _s:this.checkRetryDate();break;case Bs:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:r}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=Cs;const e={frag:t,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),r&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=Ds}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:r}=this,n=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[r])return;const a=i[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Ms,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Q,I));const d=this.getFwdBufferInfo(l,I);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return t.trigger(E.BUFFER_EOS,{type:"audio"}),void(this.state=Ns);const h=d.len,c=t.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing?g:d.end;if(this.switchingTrack&&s){const e=g;o.PTSKnown&&e<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(h>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,d,R,c)),!p)return void(this.bufferFlushed=!0);let y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&te(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Kt&&(this.mainFragLoading=y=null),y&&te(y))){if(p.start>y.end){const e=this.fragmentTracker.getFragAtPos(m,R);e&&e.end>y.end&&(y=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(p.start>y.end)return}this.loadFragment(p,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new ot(e))}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,this.flushAudioIfNeeded(t),this.state!==ws&&(this.setInterval(100),this.state=Ds,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(E.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:r,id:n,groupId:a,track:o}=t;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==ws&&(this.state=Ms));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=s[n];let h=0;if(r.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;if(d.details)h=this.alignPlaylists(r,d.details,null==(c=this.levelLastLoaded)?void 0:c.details);r.alignedSliding||(Ls(r,l),r.alignedSliding||Rs(r,l),h=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state!==Ms||this.waitForCdnTuneIn(r)||(this.state=Ds),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const h=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Tn(this.hls,I,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=s?s.index:-1,n=-1!==t,a=new oi(i.level,i.sn,i.stats.chunkCount,r.byteLength,t,n);c.push(r,f,h,"",i,s,d.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Hs,complete:!1};e.push(new Uint8Array(r)),this.state!==ws&&(this.state=Bs)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0: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===R&&te(t.frag)&&(this.mainFragLoading=t,this.state===Ds&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type===I)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"}`);else{if(te(i)){this.fragPrevious=i;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,_({},e)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==R||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var i;if(t.fatal)this.state=Us;else switch(t.details){case T.FRAG_GAP:case T.FRAG_PARSING_ERROR:case T.FRAG_DECRYPT_ERROR:case T.FRAG_LOAD_ERROR:case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_ERROR:case T.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(I,t);break;case T.AUDIO_TRACK_LOAD_ERROR:case T.AUDIO_TRACK_LOAD_TIMEOUT:case T.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Ms||(null==(i=t.context)?void 0:i.type)!==b||(this.state=Ds);break;case T.BUFFER_ADD_CODEC_ERROR:case T.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case T.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case T.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==J&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==J){this.flushing=!1,this.bufferFlushed=!0,this.state===Ns&&(this.state=Ds);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,I),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{details:h}=d,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&h){if(this.state=Os,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,g.tracks,e,n),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(c){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=c;l&&(l.elementaryStreams[Q]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),o.setElementaryStreamInfo(Q,e,t,i,s),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=x({id:i,frag:o,details:h},f);s.trigger(E.FRAG_PARSING_METADATA,e)}if(u){const e=x({id:i,frag:o,details:h},u);s.trigger(E.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,i,s){if(this.state!==Os)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const r=t.audio;r.id=I;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(E.BUFFER_CODECS,t);const a=r.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:a};this.hls.trigger(E.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);var r;if(this.switchingTrack||s===Vt||s===Ht)if(te(e))if(null!=(r=t.details)&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Bs;const i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&Rs(t.details,i)}else super.loadFragment(e,t,i);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;mt({name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},e,pt)||(vt(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.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,_({},e))}},audioTrackController:class extends En{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.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:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}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 r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>-1===(null==s?void 0:s.indexOf(e)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!r&&t){const i=gt(t,e,pt);if(i>-1)r=e[i];else{const e=gt(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==s&&-1===o)this.setAudioTrack(s);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==b||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){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&&mt(e,s,pt))return s;const r=gt(e,this.tracksInGroup,pt);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r),e}if(s){let s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);const r=function(e,t,i,s,r){const n=t[s],a=t.reduce((e,t,i)=>{const s=t.uri;return(e[s]||(e[s]=[])).push(i),e},{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),h=yt(t,s,t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==d)return!1;const s=t.audioGroups,n=i.filter(e=>!s||-1!==s.indexOf(e.groupId));return gt(e,n,r)>-1});return h>-1?h:yt(t,s,t=>{const s=t.audioGroups,n=i.filter(e=>!s||-1!==s.indexOf(e.groupId));return gt(e,n,r)>-1})}(e,t.levels,i,s,pt);if(-1===r)return null;t.nextLoadLevel=r}if(e.channels||e.audioCodec){const t=gt(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],r=s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;if(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,_({},s)),r)return;const n=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if((!this.selectDefaultTrack||s.default)&&(!e||mt(e,s,pt)))return i}if(e){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(mt({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},t[e],pt))return e}for(let i=0;i<t.length;i++){const s=t[i];if(An(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const s=t[i];if(An(e.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&vt(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},emeController:Ia,cmcdController:class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:xn.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:i}=e,s=this.hls.levels[t.level],r=this.getObjectType(t),n={d:1e3*(i||t).duration,ot:r};r!==xn.VIDEO&&r!==xn.AUDIO&&r!=xn.MUXED||(n.br=s.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=i?this.getNextPart(i):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(n.nor=a.url),this.apply(e,n)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,s;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=t.tracks.video)?void 0:s.buffer}createData(){var e;return{v:1,sf:Cn.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){x(t,this.createData());const i=t.ot===xn.INIT||t.ot===xn.VIDEO||t.ot===xn.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((e,i)=>(s.includes(i)&&(e[i]=t[i]),e),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Ea(e.headers,t,r)):e.url=ba(e.url,t,r)}getNextFrag(e){var t;const i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){const t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t;const{index:i,fragment:s}=e,r=null==(t=this.hls.levels[s.level])||null==(t=t.details)?void 0:t.partList;if(r){const{sn:e}=s;for(let t=r.length-1;t>=0;t--){const s=r[t];if(s.index===i&&s.fragment.sn===e)return r[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?xn.TIMED_TEXT:"initSegment"===e.sn?xn.INIT:"audio"===t?xn.AUDIO:"main"===t?this.hls.audioTracks.length?xn.VIDEO:xn.MUXED:void 0}getTopBandwidth(e){let t,i=0;const s=this.hls;if(e===xn.AUDIO)t=s.audioTracks;else{const e=s.maxAutoLevel,i=e>-1?e+1:s.levels.length;t=s.levels.slice(0,i)}return t.forEach(e=>{e.bitrate>i&&(i=e.bitrate)}),i>0?i:NaN}getBufferLength(e){const t=this.media,i=e===xn.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!t)return NaN;return 1e3*di.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}},contentSteeringController:class extends M{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&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=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(t=>t!==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;null!==i&&(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((null==i?void 0:i.action)===_t&&i.flags===Nt){const e=this.levels;let s=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:i,pathwayId:s,type:n}=t.context;i&&e?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&e&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r),t.details!==T.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${ht(s)} penalized: ${ht(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){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 null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(e=>{s-i[e]>3e5&&delete i[e]});for(let s=0;s<e.length;s++){const r=e[s];if(r in i)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,vs(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(t===b&&s[i].hasAudioGroup(e)||t===L&&s[i].hasSubtitleGroup(e))return s[i].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(e=>{const t=new yi(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(i[t.AUDIO]=n,t.AUDIO=n),o&&(s[t.SUBTITLES]=o,t.SUBTITLES=o);const l=Ra(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new ot({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(let t=1;t<e.audioGroups.length;t++)d.addGroupId("audio",`${e.audioGroups[t]}_clone_${r}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)d.addGroupId("text",`${e.subtitleGroups[t]}_clone_${r}`);return d});t.push(...o),La(this.audioTracks,i,a,r),La(this.subtitleTracks,s,a,r)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;let s;this.loader&&this.loader.destroy(),this.loader=new i(t);try{s=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==s.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+e)}const r={responseType:"json",url:s.href},n=t.steeringManifestLoadPolicy.default,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:(e,t,i,r)=>{this.log(`Loaded steering manifest: "${s}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,s).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:s.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(e,t,i,s)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,r)},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}},interstitialsController:class extends M{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const i=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&e<s.start||e>=s.end){var r;const t=this.findItemIndex(s);let n=this.schedule.findItemIndexAtTime(e);if(-1===n&&(n=t+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${n})`)),!this.isInterstitial(s)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&n>t){const e=this.schedule.findJumpRestrictedIndex(t+1,n);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(s)){const t=s.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;var l;(i&&e<a||e>=a+o)&&(null!=(l=s.event)&&l.appendInPlace&&(this.clearInterstitial(s.event,s),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,n))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const i=this.playingAsset;if(!i)return;e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{const i=this.schedule;if(!i)return;const s=this.playingItem,r=i.events||[],n=i.items||[],a=i.durations,o=e.map(e=>e.identifier),l=!(!r.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(e=>qa(e))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let d=null,h=null;s&&(d=this.updateItem(s,this.timelinePos),this.itemsMatch(s,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const c=this.bufferingItem;if(c&&(h=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,h)?this.bufferingItem=h:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(s){Math.abs(i)>Na&&this.warn(`${s} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),l||t){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(s)&&o.includes(s.event.identifier))return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);s&&this.trimInPlace(d,s),c&&h!==d&&this.trimInPlace(h,c),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Ya(e),this.schedule=new Wa(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){ks(e,"play",this.onPlay),ks(e,"pause",this.onPause),ks(e,"seeking",this.onSeeking),ks(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Is(i,"seeking",this.onSeeking),Is(i,"timeupdate",this.onTimeupdate),Is(i,"play",this.onPlay),Is(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const e=this.findItemIndex(i);this.setSchedulePosition(e)}}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 e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.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=t=>t?e.getAssetPlayer(t.identifier):t,s=(t,s,n,a,o)=>{if(t){let l=t[s].start;const d=t.event;if(d){if("playout"===s||d.timelineOccupancy!==Ua.Point){const e=i(n);(null==e?void 0:e.interstitial)===d&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?r():e[a])-t.start}return l}return 0},r=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=t=>{var i,s;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(s=e.schedule)?void 0:s.durations[t])||0},a=(t,r)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${r}"`);const l=e.effectivePlayingItem,d=e.schedule.findItemIndexAtTime(t,r),h=null==(a=e.schedule.items)?void 0:a[d],c=e.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&e.itemsMatch(l,h);if(l&&(f||g)){const n=i(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const i="primary"===r?a.currentTime:s(l,r,e.playingAsset,"timelinePos","currentTime"),o=t-i,d=(f?i:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(h){let i=t;if("primary"!==r){const e=t-h[r].start;i=h.start+e}const s=!e.isInterstitial(h);if(e.isInterstitial(l)&&!l.event.appendInPlace||!s&&!h.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(d>n){const t=e.schedule.findJumpRestrictedIndex(n+1,d);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(s)e.timelinePos=i,e.checkBuffer();else{const e=h.event.assetList,i=t-(h[r]||h).start;for(let t=e.length;t--;){const s=e[t];if(s.duration&&i>=s.startOffset&&i<s.startOffset+s.duration){a=t;break}}}e.setSchedulePosition(d,a)}}else{const t=e.media||(f?null==c?void 0:c.media:null);t&&(t.currentTime=i)}}},o=()=>{const i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;const s=t();return e.isInterstitial(s)?s:null},l={get bufferedEnd(){const i=t(),r=e.bufferingItem;var n;return r&&r===i&&(s(r,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=e.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const t=o(),i=e.effectivePlayingItem;return i&&i===t?s(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){const i=o(),s=e.effectivePlayingItem;s&&s===i&&a(t+s.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const i=null==(t=o())?void 0:t.event.assetList;return i?i.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var t;const i=null==(t=o())?void 0:t.event;return i&&e.effectivePlayingAsset?i.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(){const i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){var t;return((t,i)=>{var s;if(0!==t&&"primary"!==i&&null!=(s=e.schedule)&&s.length){var r;const s=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[s];if(n)return t+(n[i].start-n.start)}return t})((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){const s=e.findItemIndex(t);if(i.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(i,s,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=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(s=this.primaryMedia);const r=null==(t=s)?void 0:t.currentTime;return void 0!==r&&m(r)?r:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!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)return void(this.detachedData={media:s});const i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ht(i)}`),this.detachedData=i}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else if(l){const e=this.getBufferingPlayer();e?(r=e.transferMedia(),d=`${e}`):d="detached MediaSource"}else d="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ht(r)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach(e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}const h=r&&"mediaSource"in r&&"closed"!==(null==(s=r.mediaSource)?void 0:s.readyState),c=h&&r?r:t;this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`);const u=this.schedule;if(c===r&&u){const t=a&&e.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||t,cueRemoval:!a}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.log(Xa("checkStart",i)),this.timelinePos=i,t.length&&t[0].cue.pre){const i=e.findEventIndex(t[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){const t=this.timelinePos=i>0?i:0,s=e.findItemIndexAtTime(t);this.setSchedulePosition(s)}}else if(s&&!this.playingItem){const t=e.findItemIndex(s);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const i=e.event,s=i.findAssetIndex(t),r=Ha(i,s);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const t=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,r)}advanceAfterAssetEnded(e,t,i){const s=Ha(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=t+1;if(s>=i.length)return void this.setSchedulePosition(-1);const r=e.resumeTime;this.timelinePos<r&&(this.log(Xa("advanceAfterAssetEnded",r)),this.timelinePos=r,e.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){const t=e.assetList[s];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const s=t.parentIdentifier,r=i.getEvent(s);if(r){const t=i.findEventIndex(s),n=i.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,t,n-1)}}setSchedulePosition(e,t){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const r=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r?qa(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,d=this.playingAsset,h=null==d?void 0:d.identifier,c=h?this.getAssetPlayer(h):null;if(c&&h&&(!this.eventItemsMatch(n,r)||void 0!==t&&h!==i.assetList[t].identifier)){var o;const t=i.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${i.assetList.length} ${Ka(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:i,schedule:s.slice(0),scheduleIndex:e,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(h,r),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${qa(n)}`),i.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:e}),i.cue.once)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(r&&e){const i=this.findItemIndex(r);this.advanceSchedule(i,e,t,n,a)}return}}this.advanceSchedule(e,s,t,n,a)}advanceSchedule(e,t,i,s,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(t=>{const i=t.interstitial,s=n.findEventIndex(i.identifier);(s<e||s>e+1)&&this.clearInterstitial(i,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===i){const t=Ha(r,(i=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(t)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,e,i);i=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let d=this.preloadAssets(r,i);if(this.eventItemsMatch(a,l||s)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${qa(a)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(E.INTERSTITIAL_STARTED,{event:r,schedule:t.slice(0),scheduleIndex:e})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const h=r.assetList[i];if(!h)return void this.advanceAfterAssetEnded(r,e,i||0);if(d||(d=this.getAssetPlayer(h.identifier)),null===d||d.destroyed){const e=r.assetList.length;this.warn(`asset ${i+1}/${e} player destroyed ${r}`),d=this.createAssetPlayer(r,h,i),d.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(d,i,t,e,o),this.shouldPlay&&za(d.media)}else a?(this.resumePrimary(a,e,s),this.shouldPlay&&za(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,i){var s,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${qa(e)}`),null==(s=this.detachedData)||!s.mediaSource){let i=this.timelinePos;(i<e.start||i>=e.end)&&(i=this.getPrimaryResumption(e,t),this.log(Xa("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,e)}if(!i)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${qa(e)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(i<e.fragmentStart||i>e.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return di.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 r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Xa("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs(((null==(i=s.mainForwardBufferInfo)?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){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(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const s=_(_({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=_(_({},this.altSelection),{},{audio:i}));const r=_(_({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=_(_({},this.altSelection),{},{subtitles:i}));const r=_(_({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=ft(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=ft(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.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 e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const s=t[e];if(s.cue.post){var i;const e=this.schedule.findEventIndex(s.identifier),t=null==(i=this.schedule.items)?void 0:i[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const s=null==(i=this.schedule)?void 0:i.items;if(e&&s){return s[this.findItemIndex(e,t)]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,i)=>{e.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(t.identifier,null)});const i=e.end+.25,s=di.bufferInfo(this.primaryMedia,i,0);if(s.end>i||(s.nextStart||0)>i){this.log(`trim buffered interstitial ${qa(e)} (was ${qa(t)})`);const s=!0;this.attachPrimary(i,null,s),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===(null==(i=t.event)?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&(null==(t=this.schedule)||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=null==(t=this.schedule)?void 0:t.items;if(!i)return;const s=di.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,r=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(1===t.length&&this.itemsMatch(t[0],r))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const i=this.findItemIndex(r),s=Math.min(i+1,t.length-1),n=t[s];if((-1===o&&r&&e>=r.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=s),this.isInterstitial(r)){const e=r.event;if(s-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>i&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else i&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{const i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:s,events:r}=i;if(!s||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${qa(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const t=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,i)=>{const s=this.getAssetPlayer(e.identifier);s&&(i===t&&s.loadSource(),s.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.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(null!==i){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){const e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,r=0===s&&!e.assetListLoader,n=e.cue.once;if(r){const r=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-r;e>0&&(n=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(e,0,0,r,e.duration,i);const l=this.assetListLoader.loadAssetList(e,n);l&&(e.assetListLoader=l)}else if(!n&&s){for(let i=t;i<s;i++){const t=e.assetList[i],s=this.getAssetPlayerQueueIndex(t.identifier);-1!==s&&!this.playerQueue[s].destroyed||t.error||this.createAssetPlayer(e,t,i)}const i=e.assetList[t];if(i){const e=this.getAssetPlayer(i.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach(t=>{this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})})}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,r,n){const a={parentIdentifier:e.identifier,identifier:Ba(e,n,t),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){const s=this.hls,r=s.userConfig;let n=r.videoPreference;const a=s.loadLevelObj||s.levels[s.currentLevel];(n||a)&&(n=x({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let d=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const i=t.duration;i&&e<i&&(d=e)}}const h=t.identifier,c=_(_({},r),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(c.timelineOffset=t.timelineStart));const u=c.cmcd;null!=u&&u.sessionId&&u.contentId&&(c.cmcd=x({},u,{contentId:Fa(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const f=new ja(this.HlsPlayerClass,c,e,t);this.playerQueue.push(f),e.assetList[i]=t;let g=!0;const m=s=>{if(s.live){var r;const t=new Error(`Interstitials MUST be VOD assets ${e}`),s={fatal:!0,type:v.OTHER_ERROR,details:T.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=(null==(r=this.schedule)?void 0:r.findEventIndex(e.identifier))||-1;return void this.handleAssetItemError(s,e,n,i,t.message)}const n=s.edge-s.fragmentStart,a=t.duration;(g||null===a||n>a)&&(g=!1,this.log(`Interstitial asset "${h}" duration change ${a} > ${n}`),t.duration=n,this.updateSchedule())};f.on(E.LEVEL_UPDATED,(e,{details:t})=>m(t)),f.on(E.LEVEL_PTS_UPDATED,(e,{details:t})=>m(t)),f.on(E.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(e,t)=>{const i=this.getAssetPlayer(h);if(i&&t.tracks){i.off(E.BUFFER_CODECS,p),i.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};f.on(E.BUFFER_CODECS,p);f.on(E.BUFFERED_TO_END,()=>{var i;const s=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${s}`),!s||!this.schedule)return;const r=this.schedule.findEventIndex(e.identifier),n=null==(i=this.schedule.items)?void 0:i[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,t)});const y=t=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return f.once(E.MEDIA_ENDED,y(i)),f.once(E.PLAYOUT_LIMIT_REACHED,y(1/0)),f.on(E.ERROR,(t,s)=>{if(!this.schedule)return;const r=this.getAssetPlayer(h);if(s.details===T.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${s.error} ${e}`)}),f.on(E.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${h}`),s={fatal:!0,type:v.OTHER_ERROR,details:T.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ka(t)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)}),e.reset()}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){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(-1!==i){const e=this.playerQueue[i];this.log(`clear ${e} toSegment: ${t?qa(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(i,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,d&&d.identifier===o||(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Ka(a)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,s;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,a=this.schedule.findEventIndex(r.identifier),o=null==(i=this.schedule.items)?void 0:i[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const d=r.appendInPlace;if(d&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const h=(null==l?void 0:l.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(h&&!G(h,e.tracks)){const t=new Error(`Asset ${Ka(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),i={fatal:!0,type:v.OTHER_ERROR,details:T.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},s=r.findAssetIndex(n);return void this.handleAssetItemError(i,r,a,s,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const s=i.currentTime,r=t.findAssetIndex(e,s),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||s-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const i=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,s,r){if(e.details===T.BUFFER_STALLED_ERROR)return;const n=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?Ka(n):n} ${e.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,h=x({},e,{fatal:!1,errorAction:$t(!0),asset:n,assetListIndex:s,event:t,schedule:d,scheduleIndex:i,player:l});if(this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;const c=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),t.assetList.some(e=>!e.error))for(let e=s;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):c&&c.identifier===a?this.advanceAfterAssetEnded(t,i,s):u&&u.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${qa(i)} error: ${e.error}`);let s=this.timelinePos;-1===s&&(s=this.hls.startPosition);const r=this.updateItem(i,s);if(this.itemsMatch(i,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const n=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(n)}else this.checkStart()}onAssetListLoaded(e,t){var i,s;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((e,t)=>{const i=parseFloat(e.DURATION);this.createAsset(r,t,d,o+d,i,e.URI),d+=i}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const h=this.waitingItem,c=(null==h?void 0:h.event.identifier)===n;this.updateSchedule();const u=null==(s=this.bufferingItem)?void 0:s.event;if(c){var f;const e=this.schedule.findEventIndex(n),t=null==(f=this.schedule.items)?void 0:f[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return r.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${r}`),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==u?void 0:u.identifier)===n){const e=r.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case T.ASSET_LIST_PARSING_ERROR:case T.ASSET_LIST_LOAD_ERROR:case T.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case T.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function il(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(il):Object.keys(e).reduce((t,i)=>(t[i]=il(e[i]),t),{}):e}function sl(e,t){const i=e.loader;if(i!==Xo&&i!==el)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=Xo,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class rl extends ai{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.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(100),this.mediaSource=t.mediaSource;const i=this.media=t.media;Is(i,"playing",this.onMediaPlaying),Is(i,"waiting",this.onMediaWaiting),Is(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(ks(i,"playing",this.onMediaPlaying),ks(i,"waiting",this.onMediaWaiting),ks(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(d)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})));if(!di.getBuffered(n).length)return void(this.nudgeRetry=0);const h=di.bufferInfo(n,e,0),c=h.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const t=nl(this.hls.inFlightFragments,e),i=h.len>2,s=!c||t||c-e>2&&!u.getPartialFragment(e);if(i||s)return;this.moved=!1}const f=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(h.len>0)&&!c)return;const t=Math.max(c,h.start||0)-e,i=!(null==f||!f.live)?2*f.targetduration:2,s=ol(e,u);if(t>0&&(t<=i||s))return void(n.paused||this._trySkipBufferHole(s))}const g=r.detectStallWithCurrentTimeMs,m=self.performance.now(),p=this.waiting;let y=this.stalled;if(null===y){if(!(p>0&&m-p<g))return void(this.stalled=m);y=this.stalled=p}const v=m-y;if(!a&&(v>=g||p)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(E.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(h),!this.media||!this.hls)return}const S=di.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(S,v,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(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&s&&s.length>1&&e>s.end(0)){const i=di.bufferedInfo(di.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){const i=di.timeRangesToArray(s),r=di.bufferedInfo(i,t,0).bufferedIndex;if(r>-1&&r<i.length-1){const t=di.bufferedInfo(i,e,0).bufferedIndex,s=i[r].end,n=i[r+1].start;if((-1===t||t>r)&&n-s<1&&e-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${s} -> ${n} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;let r=ol(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=di.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,i){var s,r;const{fragmentTracker:n,media:a}=this,o=null==(s=this.hls)?void 0:s.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,d=ol(i,n);if(d||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=e.buffered,c=this.adjacentTraversal(e,i);(h&&h.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-i<o.maxBufferHole||c))&&(t>1e3*o.highBufferWatchdogPeriod||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 e=i.getFragAtPos(t,R),r=i.getFragAtPos(s,R);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:r}=this;if(!s&&null!==r&&i&&t){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ht(e)})`);this.warn(s.message),t.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,r=null==(t=this.hls)?void 0:t.config;if(!s||!i||!r)return 0;const n=s.currentTime,a=di.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=r.maxBufferHole,d=a.len>0&&a.len<1&&s.readyState<3,h=o-n;if(h>0&&(t||d)){if(h>r.maxBufferHole){let t=!1;if(0===n){const e=i.getAppendedFrag(0,R);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(nl(this.hls.inFlightFragments,o))return 0;let t=!1,s=e.end;for(;s<o;){const e=ol(s,i);if(!e){t=!0;break}s+=e.duration}if(t)return 0}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,s.currentTime=t,null==e||!e.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),s={type:v.MEDIA_ERROR,details:T.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?s.part=e:s.frag=e),this.hls.trigger(E.ERROR,s)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,r=null==t?void 0:t.config;if(!i||!r)return 0;const n=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){const a=n+(s+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),i.currentTime=a,t.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const i=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(i.message),t.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:e.len,bufferInfo:e})}}}function nl(e,t){const i=al(e.main);if(i&&i.start<=t)return i;const s=al(e.audio);return s&&s.start<=t?s:null}function al(e){if(!e)return null;switch(e.state){case Ds:case ws:case Ns:case Us:return null}return e.frag}function ol(e,t){return t.getAppendedFrag(e,R)||t.getPartialFragment(e)}function ll(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function dl(e,t,i,s,r){let n=new e(t,i,"");try{n.value=s,r&&(n.type=r)}catch(a){n=new e(t,i,ht(r?_({type:r},s):s))}return n}const hl=(()=>{const e=ll();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class cl{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(E.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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&_a(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if("metadata"===i.kind&&"id3"===i.label)return xa(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=ll();if(n)for(let e=0;e<r.length;e++){const t=r[e].type;if(t===yr.emsg&&!i||!s)continue;const a=fr(r[e].data),o=r[e].pts;let l=o+r[e].duration;l>hl&&(l=hl);l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const i=a[e];if(!gr(i)){this.updateId3CueEnds(o,t);const e=dl(n,o,l,i,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){var i;const s=null==(i=this.id3Track)?void 0:i.cues;if(s)for(let i=s.length;i--;){const r=s[i];r.type===t&&r.startTime<e&&r.endTime===hl&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===s?e=>e.type===yr.audioId3&&o:"video"===s?e=>e.type===yr.emsg&&a:e=>e.type===yr.audioId3&&o||e.type===yr.emsg&&a,Ma(r,t,i,e)}}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:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=ll();if(i&&s&&!n){const{fragmentStart:t,fragmentEnd:s}=e;let r=this.assetCue;r?(r.startTime=t,r.endTime=s):a&&(r=this.assetCue=dl(a,t,s,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,d=Object.keys(l);let h=this.dateRangeCuesAppended;var c;if(o&&t)if(null!=(c=o.cues)&&c.length){const e=Object.keys(h).filter(e=>!d.includes(e));for(let t=e.length;t--;){var u;const i=e[t],s=null==(u=h[i])?void 0:u.cues;delete h[i],s&&Object.keys(s).forEach(e=>{const t=s[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(e){}}})}}else h=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==d.length&&m(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<d.length;e++){const t=d[e],i=l[t],s=i.startTime,r=h[t],o=(null==r?void 0:r.cues)||{};let c=(null==r?void 0:r.durationKnown)||!1,u=hl;const{duration:f,endDate:g}=i;if(g&&null!==f)u=s+f,c=!0;else if(i.endOnNext&&!c){const e=d.reduce((e,t)=>{if(t!==i.id){const s=l[t];if(s.class===i.class&&s.startDate>i.startDate&&(!e||i.startDate<e.startDate))return s}return e},null);e&&(u=e.startTime,c=!0)}const m=Object.keys(i.attr);for(let e=0;e<m.length;e++){const l=m[e];if(!vi(l))continue;const d=o[l];if(d)!c||null!=r&&r.durationKnown?Math.abs(d.startTime-s)>.01&&(d.startTime=s,d.endTime=u):d.endTime=u;else if(a){let e=i.attr[l];Ti(l)&&(e=j(e));const r=dl(a,s,u,{key:l,data:e},yr.dateRange);r&&(r.id=t,this.id3Track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}h[t]={cues:o,dateRange:i,durationKnown:c}}}}}class ul{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,s=Math.min(t,Math.max(1,i));this.changeMediaPlaybackRate(e,s)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*s);const d=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,r=e-t-this.edgeStalled,n=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);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(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===T.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(s=this.targetLatency)?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 null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class fl extends En{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach(e=>{const t=e.attrs;let{audioCodec:d,videoCodec:h}=e;d&&(e.audioCodec=d=Ve(d,i)||void 0),h&&(h=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const i=t[e].split(".");i.length>2&&"avc1"===i[0]&&(t[e]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}(h));const{width:c,height:u,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(a||(a=!(!c||!u)),o||(o=!!h),l||(l=!!d),g||d&&!this.isAudioSupported(d)||h&&!this.isVideoSupported(h))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":y,"PATHWAY-ID":v,RESOLUTION:T,"VIDEO-RANGE":E}=t,S=`${`${v||"."}-`}${e.bitrate}-${T}-${p}-${m}-${E}-${y}`;if(r[S])if(r[S].uri===e.url||e.attrs["PATHWAY-ID"])r[S].addGroupId("audio",t.AUDIO),r[S].addGroupId("text",t.SUBTITLES);else{const t=n[S]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const i=this.createLevel(e);r[S]=i,s.push(i)}else{const t=this.createLevel(e);r[S]=t,n[S]=1,s.push(t)}}),this.filterAndSortMediaOptions(s,t,a,o,l)}createLevel(e){const t=new ot(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=ze(e,[])}return t}isAudioSupported(e){return Me(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Me(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,r){var n;let a=[],o=[],l=e;const d=(null==(n=t.stats)?void 0:n.parsing)||{};if((i||s)&&r&&(l=l.filter(({videoCodec:e,videoRange:t,width:i,height:s})=>{return(!!e||!(!i||!s))&&(!!(r=t)&&tt.indexOf(r)>-1);var r})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${ht(t.levels.map(e=>e.attrs.CODECS).filter((e,t,i)=>i.indexOf(e)===t))}`,this.warn(i),e+=` (${i})`);const s=new Error(e);this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:s,reason:i})}}),void(d.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),gl(a)),t.subtitles&&(o=t.subtitles,gl(o));const h=l.slice(0);l.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return tt.indexOf(e.videoRange)-tt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const i=Ne(e.videoCodec),s=Ne(t.videoCodec);if(i!==s)return s-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const i=Ue(e.codecSet),s=Ue(t.codecSet);if(i!==s)return s-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let c=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length))for(let e=0;e<h.length;e++)if(h[e].pathwayId===l[0].pathwayId){c=h[e];break}this._levels=l;for(let e=0;e<l.length;e++)if(l[e]===c){var u;this._firstLevel=e;const t=c.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const f=r&&!s,g=this.hls.config,m=!(!g.audioStreamController||!g.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:m&&!f&&a.some(e=>!!e.url)};d.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,p)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const i=new Error("invalid level idx"),s=e<0;if(this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.LEVEL_SWITCH_ERROR,level:e,fatal:s,error:i,reason:i.message}),s)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&s&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==s?void 0:s.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?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(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=i}}onError(e,t){!t.fatal&&t.context&&t.context.type===A&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===R){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(s,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(r.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,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(E.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const i=this._levels.filter((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));vs(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&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(E.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(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function gl(e){const t={};e.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function ml(){return self.SourceBuffer||self.WebKitSourceBuffer}function pl(){if(!V())return!1;const e=ml();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class yl extends Vs{constructor(e,t,i){super(e,t,i,"stream-controller",R),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!m(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const i=this.getFwdBufferInfoAtPos(e,t,R,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.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(100),this.level=-1,!this.startFragRequested){let e=s.startLevel;-1===e&&(s.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=s.firstAutoLevel),s.nextLoadLevel=e,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=Ds,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=ws}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case $s:{const{levels:e,level:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=Ds;break}if(this.hls.nextLoadLevel!==this.level){this.state=Ds;break}break}case _s:this.checkRetryDate()}this.state===Ds&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(null===t||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==i||!i[r])return;const n=i[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(E.BUFFER_EOS,e),void(this.state=Ns)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===$s||this.waitForLive(n))return this.level=r,this.state=$s,void(this.startFragRequested=!1);const d=a.len,h=this.getMaxBufferLength(n.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&te(u)&&this.fragmentTracker.getState(u)!==Kt){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?Q:J,t=(e===J?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,R)}u=this.getNextFragmentLoopLoading(u,l,a,R,h)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===Vt||s===Ht?te(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,R)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*r.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*s)+1:0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,s=Math.max(n.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case xs:case Cs:case _s:case Os:case Fs:this.state=Ds}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;Is(i,"playing",this.onMediaPlaying),Is(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(ks(i,"playing",this.onMediaPlaying),ks(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let e=0;e<t.levels.length;e++){const r=t.levels[e].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),s=s||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&s&&!function(){var e;const t=ml();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.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}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==Ds)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=$s)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,d=this.fragCurrent;!d||this.state!==Cs&&this.state!==_s||d.level!==t.level&&d.loader&&this.abortCurrentFrag();let h=0;if(a.live||null!=(i=l.details)&&i.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,h),this.hls.trigger(E.LEVEL_UPDATED,{details:a,level:n}),this.state===$s){if(this.waitForCdnTuneIn(a))return;this.state=Ds}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r<s||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&i.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=di.bufferInfo(i,s,0);if(null==(l=e.buffered)||!l.length)return void(i.currentTime=s);if(e.start<=r)return void(i.currentTime=s);const{nextStart:t}=di.bufferedInfo(e.buffered,r,0);t&&(i.currentTime=t)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(t=i.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Tn(this.hls,R,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=-1!==f,m=new oi(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[i.cc];u.push(r,h,c,l,i,s,o.totalduration,d,m,p)}onAudioTrackSwitching(e,t){const i=this.hls,s=2===this.altAudio;if(vt(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.fragmentTracker.removeAllFragments(),i.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),void i.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=vt(t.url,this.hls);if(i){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,r,n=!1;for(const e in i){const t=i[e];if("main"===t.id){if(r=e,s=t,"video"===e){const t=i[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,r=i.type===R;if(r){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Fs&&(this.state=Ds));const e=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),te(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const n=this.media;n&&(!this._hasEnoughToStart&&di.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal)this.state=Us;else switch(t.details){case T.FRAG_GAP:case T.FRAG_PARSING_ERROR:case T.FRAG_DECRYPT_ERROR:case T.FRAG_LOAD_ERROR:case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_ERROR:case T.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(R,t);break;case T.LEVEL_LOAD_ERROR:case T.LEVEL_LOAD_TIMEOUT:case T.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==$s||(null==(i=t.context)?void 0:i.type)!==A||(this.state=Ds);break;case T.BUFFER_ADD_CODEC_ERROR:case T.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case T.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 T.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Ds,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Q||!this.altAudio){const e=(t===J?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,R),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&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)return void this.log(`could not seek to ${i}, already seeking at ${t}`);const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=di.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${a}`),e.currentTime=i)}}_getAudioCodec(e){let 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}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:i}=this,s=null==e?void 0:e.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=Ds,this.startFragRequested=!1,this.bitrateTest=!1;const r=s.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(E.FRAG_LOADED,e),s.bitrateTest=!1}).catch(t=>{this.state!==ws&&this.state!==Us&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:d,text:h,id3:c,initSegment:u}=s,{details:f}=l,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Os,u){const e=u.tracks;if(e){const s=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,e,s,r),i.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:s,id:t,tracks:e})}const s=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(m(s)&&(!o||o.baseTime!==s||o.timescale!==n)){const e=u.trackId;this.initPTS[a.cc]={baseTime:s,timescale:n,trackId:e},i.trigger(E.INIT_PTS_FOUND,{frag:a,id:t,initPTS:s,timescale:n,trackId:e})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,i=!e||a.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:s,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:e,endPTS:s,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!i)return void this.backtrack(a);i&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,s,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,e,s,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,t||i)}else{if(!t&&!i)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=g;o&&(o.elementaryStreams[Q]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),a.setElementaryStreamInfo(Q,e,t,i,s),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const e={id:t,frag:a,details:f,samples:c.samples};i.trigger(E.FRAG_PARSING_METADATA,e)}if(f&&h){const e={id:t,frag:a,details:f,samples:h.samples};i.trigger(E.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${te(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==Os)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:a}=t;if(r){const i=e.audioCodec;let s=Ge(r.codec,i);"mp4a"===s&&(s="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){s&&(s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===n.indexOf("firefox")&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),i&&i!==s&&this.log(`Swapping manifest audio codec "${i}" for "${s}"`),r.levelCodec=s,r.id=R,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=R;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:e,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,R)}get maxBufferLength(){const{levels:e,level:t}=this,i=null==e?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=Ds}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const i=e.currentTime;if(di.isBuffered(e,i)?t=this.getAppendedFrag(i):di.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,i=t.level;e&&t.sn===e.sn&&e.level===i||(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(E.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return m(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(m(t)){const e=this.getLevelDetails(),i=this.currentFrag||(e?Et(null,e.fragments,t):null);if(i){const e=i.programDateTime;if(null!==e){const s=e+1e3*(t-i.start);return new Date(s)}}}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 vl extends M{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var t;if(e&&e!==(null==(t=s.context)?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=T.KEY_LOAD_ERROR,i,s,r){return new ni({type:v.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,r=t.length;s<r;s++){const n=t[s];if(e.cc<=n.cc&&(!te(e)||!te(n)||e.sn<n.sn)||!i&&s==r-1)return this.emeController.selectKeySystemFormat(n).then(e=>{if(!this.emeController)return;n.setKeyFormat(e);const t=Fi(e);return t?this.emeController.getKeySystemAccess([t]):void 0})}if(this.config.requireKeySystemAccessOnStart){const e=Ui(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const i=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,T.KEY_LOAD_ERROR,i))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,T.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=Tl(r);let o=this.keyIdToKeyInfo[a];if(null!=(i=o)&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(s=o)&&s.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(t=>{const{keyInfo:i}=t;return r.key=i.decryptdata.key,{frag:e,keyInfo:i}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+K(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,T.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&null!=(s=t.initSegment)&&s.data){const i=function(e){const t=[];return Se(e,e=>t.push(e.subarray(8,24))),t}(t.initSegment.data);if(i.length){const t=i[0];t.some(e=>0!==e)&&(this.log(`Using keyId found in init segment ${K(t)}`),e.decryptdata.keyId=t,Hi.setKeyIdForUri(e.decryptdata.uri,t))}}const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(t=>(e.mediaKeySessionContext=t,i))).catch(i=>{throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=new(0,i.loader)(i);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((r,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,i,s)=>{const{frag:a,keyInfo:o}=i,l=Tl(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,T.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(e,i,s,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,T.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),s,_({url:a.url,data:void 0},e)))},onTimeout:(e,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,T.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(e,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,T.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(a,l,d)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const n=Tl(i.decryptdata)||s;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function Tl(e){if(e.keyFormat!==_i){const t=e.keyId;if(t)return K(t)}return e.uri}function El(e){const{type:t}=e;switch(t){case b:return I;case L:return k;default:return R}}function Sl(e,t){let i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}class Al{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,r=new(i||s)(t);return this.loaders[e.type]=r,r}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:S,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:A,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:b,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:L,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const i=this.loaders[A];if(i){const e=i.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(i.abort(),delete this.loaders[A])}}load(e){var t;const i=this.hls.config;let s,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,i=r.context;if(i&&i.levelOrTrack===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives))return void(i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(s=e.type===S?i.manifestLoadPolicy.default:x({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),m(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===A&&null!==e.level?t=this.hls.levels[e.level].details:e.type===b&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===L&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,i=t.targetduration;if(e&&i){const t=1e3*Math.max(3*e,.8*i);s=x({},s,{maxTimeToFirstByteMs:Math.min(t,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,s.maxTimeToFirstByteMs)})}}}const n=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=e.data;t.parsing.start=performance.now(),Xi.isMediaPlaylist(n)||i.type!==S?this.handleTrackOrLevelPlaylist(e,t,i,s||null,r):this.handleMasterPlaylist(e,t,i,s)},onError:(e,t,i,s)=>{this.handleNetworkError(t,i,!1,e,s)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};r.load(e,a,o)}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 r=this.hls,n=e.data,a=Sl(e,i),o=Xi.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,i,o.playlistParsingError,s,t);const{contentSteering:l,levels:d,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f,d.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:r}=e;for(let n=t.length;n--;){const a=t[n];Me(a,"audio",i)?(e.audioCodec=s=s?`${s},${a}`:a,Ce.audio[s.substring(0,4)]=2,t.splice(n,1)):Me(a,"video",i)&&(e.videoCodec=r=r?`${r},${a}`:a,Ce.video[r.substring(0,4)]=2,t.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Xi.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some(e=>!e.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new yi({}),bitrate:0,url:""}))}r.trigger(E.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:s,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,s,r){const n=this.hls,{id:a,level:o,type:l}=i,d=Sl(e,i),h=m(o)?o:m(a)?a:0,c=El(i),u=Xi.parseLevelPlaylist(e.data,d,h,c,0,this.variableList);if(l===S){const e={attrs:new yi({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=t.loading.start+gs(u,0),n.trigger(E.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=u,this.handlePlaylistLoaded(u,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:T.MANIFEST_PARSING_ERROR,fatal:t.type===S,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===A?n+=`: ${e.level} id: ${e.id}`:e.type!==b&&e.type!==L||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=T.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case S:o=i?T.MANIFEST_LOAD_TIMEOUT:T.MANIFEST_LOAD_ERROR,l=!0;break;case A:o=i?T.LEVEL_LOAD_TIMEOUT:T.LEVEL_LOAD_ERROR,l=!1;break;case b:o=i?T.AUDIO_TRACK_LOAD_TIMEOUT:T.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case L:o=i?T.SUBTITLE_TRACK_LOAD_TIMEOUT:T.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);const h={type:v.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:r};if(s){const i=(null==t?void 0:t.url)||e.url;h.response=_({url:i,data:void 0},s)}this.hls.trigger(E.ERROR,h)}handlePlaylistLoaded(e,t,i,s,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:h,groupId:c,deliveryDirectives:u}=s,f=Sl(t,s),g=El(s);let m="number"==typeof s.level&&g===R?l:void 0;const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:T.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:s,level:m,parent:g,networkDetails:r,stats:i});e.playlistParsingError=null}if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:T.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:s,level:m,parent:g,networkDetails:r,stats:i})}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case S:case A:if(m)if(d){if(d!==a.levels[m]){const e=a.levels.indexOf(d);e>-1&&(m=e)}}else m=0;a.trigger(E.LEVEL_LOADED,{details:e,levelInfo:d||a.levels[0],level:m||0,id:h||0,stats:i,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===S});break;case b:a.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:u});break;case L:a.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:u})}}}class bl{static get version(){return Ys}static isMSESupported(){return pl()}static isSupported(){return function(){if(!pl())return!1;const e=V();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(Fe(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(Fe(t,"audio"))))}()}static getMediaSource(){return V()}static get Events(){return E}static get MetadataSchema(){return yr}static get ErrorTypes(){return v}static get ErrorDetails(){return T}static get DefaultConfig(){return bl.defaultConfig?bl.defaultConfig:tl}static set DefaultConfig(e){bl.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new qs,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,i){const s=N();if("object"==typeof console&&!0===e||"object"==typeof e){const r=["debug","log","info","warn","error"];r.forEach(t=>{s[t]=U(t,e,i)});try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.6.14`)}catch(e){return N()}r.forEach(t=>{B[t]=U(t,e)})}else x(B,s);return s}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(e,t,i){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"');const s=il(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach(i=>{const r=`${e}Loading${i}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=s[n].default;switch(t[n]={default:e},i){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${ht(t[n])}`)}),_(_({},s),t)}(bl.DefaultConfig,e,t);this.userConfig=e,i.progressive&&sl(i,t);const{abrController:s,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=i,l=new a(this),d=this.abrController=new s(this),h=new jt(this),c=i.interstitialsController,u=c?this.interstitialsController=new c(this,bl):null,f=this.bufferController=new r(this,h),g=this.capLevelController=new n(this),m=new o(this),p=new Al(this),y=i.contentSteeringController,v=y?new y(this):null,T=this.levelController=new fl(this,v),S=new cl(this),A=new vl(this.config,this.logger),b=this.streamController=new yl(this,h,A),L=this.gapController=new rl(this,h);g.setStreamController(b),m.setStreamController(b);const R=[p,T,b];u&&R.splice(1,0,u),v&&R.splice(1,0,v),this.networkControllers=R;const I=[d,f,L,g,m,S,h];this.audioTrackController=this.createController(i.audioTrackController,R);const k=i.audioStreamController;k&&R.push(this.audioStreamController=new k(this,h,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,R);const P=i.subtitleStreamController;P&&R.push(this.subtititleStreamController=new P(this,h,A)),this.createController(i.timelineController,I),A.emeController=this.emeController=this.createController(i.emeController,I),this.cmcdController=this.createController(i.cmcdController,I),this.latencyController=this.createController(ul,I),this.coreComponents=I,R.push(l);const w=l.onErrorOut;"function"==typeof w&&this.on(E.ERROR,w,l),this.on(E.MANIFEST_LOADED,p.onManifestLoaded,p)}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(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const i=e===E.ERROR;this.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}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(E.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,s=this._url=z.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[R]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[I]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[k]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)})}}}()),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-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){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){(function(e){return et.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}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(s=-1===t&&null!=e&&e.length?e.length-1:t,i)for(let t=s;t--;){const s=e[t].attrs["HDCP-LEVEL"];if(s&&s<=i)return t}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?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 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}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(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Qe(e,ut(t),navigator.mediaCapabilities)}}function Ll(){const e=navigator.userAgent,t=function(){var e;if("userAgentData"in navigator&&(null===(e=navigator.userAgentData)||void 0===e?void 0:e.platform))return navigator.userAgentData.platform;const t=navigator.userAgent;return/Mac|iPhone|iPad|iPod/i.test(t)?/iPhone|iPad|iPod/i.test(t)?"iPhone":"MacIntel":/Win/i.test(t)?"Win32":/Linux/i.test(t)?/Android/i.test(t)?"Linux armv8l":"Linux x86_64":/CrOS/i.test(t)?"CrOS":navigator.platform||"Unknown"}();let i="Unknown",s="0",r=0,n=!1,a=!1,o=!0,l=!0,d="ima";if(/Web0S|webOS/i.test(e)){i="LG WebOS",n=!0;const t=e.match(/Web0S[/\s]*([\d.]+)/i);if(s=t&&t[1]?t[1]:"Unknown","Unknown"!==s){const e=s.split(".");r=e[0]?parseInt(e[0],10):0}}else if(/Tizen/i.test(e)){i="Samsung Tizen",n=!0;const t=e.match(/Tizen[/\s]*([\d.]+)/i);if(s=t&&t[1]?t[1]:"Unknown","Unknown"!==s){const e=s.split(".");r=e[0]?parseInt(e[0],10):0}}else/SMART-TV|SmartTV/i.test(e)?(i="Smart TV",n=!0):/NetCast/i.test(e)?(i="LG NetCast",n=!0,a=!0):/BRAVIA/i.test(e)&&(i="Sony BRAVIA",n=!0);const h=function(e){const t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e),c=function(e){const t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e);return h>0&&(n||(i="Chrome",s=h.toString(),r=h),h<50&&(o=!1,l=!1,a=!0,d="hls")),c>0&&c<600&&(l=!1,n&&(a=!0,o=!1,d="hls")),"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(l=!1,o=!1,d="hls"),"undefined"==typeof URLSearchParams&&(l=!1),{name:i,version:s,majorVersion:r,isSmartTV:n,isLegacyTV:a,platform:t,supportsIMA:o,supportsModernJS:l,recommendedAdPlayer:d}}function Rl(){const e=Ll();if(e.isLegacyTV)return!1;if("undefined"==typeof document||"function"!=typeof document.createElement)return!1;try{if(!document.createElement("video"))return!1}catch(e){return!1}return"undefined"!=typeof Promise&&e.supportsIMA}function Il(e=!1){if(!e)return;const t=Ll(),i=Rl();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",{browser:`${t.name} ${t.version}`,platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsIMA:i,supportsModernJS:t.supportsModernJS,recommendedAdPlayer:t.recommendedAdPlayer,userAgent:navigator.userAgent})}function kl(){const e=Ll(),t={};return!e.isLegacyTV&&e.supportsIMA||(t.adPlayerType="hls"),e.isSmartTV&&(t.allowNativeHls=!0),t}function Pl(e,t){let i=!1,s=!1,r=!1,n="number"!=typeof e.volume||Number.isNaN(e.volume)?1:Math.max(0,Math.min(1,e.volume));const a=new Map,o=new Map,l=new Map;let d,h,c,u,f,g;function m(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function p(){s&&(e.style.visibility="visible",e.style.transition="opacity 0.3s ease-in-out",e.offsetHeight,e.style.opacity="1",e.muted=r,e.volume=n,s=!1)}function y(){const e=document.createElement("video");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="contain",e.style.backgroundColor="transparent",e.style.zIndex="15",e.playsInline=!0,e.muted=!1,e.volume=r?0:n,e.style.opacity="0",e.addEventListener("canplay",()=>{e.style.opacity="1"},{once:!0}),e}function v(e,t){const i=a.get(e);if(i)for(const e of Array.from(i))try{e(t)}catch{}}function T(){var e,t,i;if(!Rl())return console.warn("[IMA] Google IMA SDK is not supported on this browser. Please use HLS ad player instead."),Promise.reject(new Error("Google IMA SDK not supported on this browser"));try{const t=window.frameElement,i=(null===(e=null==t?void 0:t.getAttribute)||void 0===e?void 0:e.call(t,"sandbox"))||"";if(i){const e=new Set(i.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0));e.has("allow-scripts")||console.error("StormcloudVideoPlayer: The host page is inside a sandboxed iframe without 'allow-scripts'. Google IMA cannot run ads within sandboxed frames. Remove the sandbox attribute or include 'allow-scripts allow-same-origin'.")}}catch{}if("undefined"!=typeof window&&(null===(t=window.google)||void 0===t?void 0:t.ima))return Promise.resolve();const s=document.querySelector('script[data-ima="true"]');return s?(null===(i=window.google)||void 0===i?void 0:i.ima)?Promise.resolve():new Promise((e,t)=>{const i=setTimeout(()=>{t(new Error("IMA SDK load timeout"))},1e4);s.addEventListener("load",()=>{clearTimeout(i),e()}),s.addEventListener("error",()=>{clearTimeout(i),t(new Error("IMA SDK load failed"))})}):new Promise((e,t)=>{const i=document.createElement("script");i.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",i.async=!0,i.defer=!0,i.setAttribute("data-ima","true"),i.onload=()=>e(),i.onerror=()=>t(new Error("IMA SDK load failed")),document.head.appendChild(i)})}let E=0;let S,A,b;function L(t,i){const s=new t.ima.AdsRequest;console.log("[IMA] 📡 Requesting VAST from URL (letting IMA fetch fresh)"),s.adTagUrl=i;const r=e.offsetWidth||e.clientWidth||640,n=e.offsetHeight||e.clientHeight||360;if(s.linearAdSlotWidth=r,s.linearAdSlotHeight=n,s.nonLinearAdSlotWidth=r,s.nonLinearAdSlotHeight=n,"function"==typeof s.setAdWillAutoPlay)try{const t=!e.paused||e.autoplay;s.setAdWillAutoPlay(t)}catch(e){console.warn("[IMA] Failed to call setAdWillAutoPlay:",e)}if("function"==typeof s.setAdWillPlayMuted)try{const t=e.muted||0===e.volume;s.setAdWillPlayMuted(t)}catch(e){console.warn("[IMA] Failed to call setAdWillPlayMuted:",e)}s.vastLoadTimeout=1e4,c.requestAds(s)}function R(){var t;if(f)return;const i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="transparent",i.style.transition="opacity 0.3s ease-in-out, background-color 0.3s ease-in-out",i.style.opacity="0",null===(t=e.parentElement)||void 0===t||t.appendChild(i),f=i}function I(){if(h){try{h.destroy()}catch{}h=void 0}d&&(d.style.opacity="0")}return{initialize(){T().then(()=>{var e;const t=window.google;if(R(),!u&&f){d||(d=y(),f.appendChild(d)),u=new t.ima.AdDisplayContainer(f,d);try{null===(e=u.initialize)||void 0===e||e.call(u)}catch{}}}).catch(()=>{})},async requestAds(a){if(!a||""===a.trim()){const e=new Error("VAST tag URL is empty or undefined");return console.warn("[IMA] ❌",e.message),Promise.reject(e)}try{new URL(a)}catch(e){const t=new Error(`Invalid VAST tag URL format: ${a}`);return console.warn("[IMA] ❌",t.message),Promise.reject(t)}if(i)return console.warn("[IMA] ⚠️ Cannot request new ads while an ad is playing. Call stop() first."),Promise.reject(new Error("Ad already playing - cannot request new ads"));let o;I(),b=void 0,A=void 0,S=new Promise((e,t)=>{A=e,b=t,o=t,setTimeout(()=>{b&&(b(new Error("Ad request timeout")),b=void 0,A=void 0)},1e4)});try{await T();const l=window.google;if(g=a,E=0,!u){const t=document.createElement("div");if(t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.right="0",t.style.bottom="0",t.style.display="none",t.style.alignItems="center",t.style.justifyContent="center",t.style.pointerEvents="none",t.style.zIndex="10",t.style.backgroundColor="transparent",t.style.transition="opacity 0.3s ease-in-out, background-color 0.3s ease-in-out",t.style.opacity="0",!e.parentElement)throw new Error("Video element has no parent for ad container");e.parentElement.appendChild(t),f=t,d||(d=y(),f.appendChild(d)),u=new l.ima.AdDisplayContainer(t,d)}const R=e.offsetWidth||e.clientWidth,k=e.offsetHeight||e.clientHeight;if(!R||!k||0===R||0===k){const e=new Error(`Invalid video dimensions: ${R}x${k}. Cannot initialize ads.`);return console.warn("[IMA]",e.message),null==o||o(e),b=void 0,A=void 0,Promise.reject(e)}if(!c){const a=new l.ima.AdsLoader(u);c=a,c.addEventListener(l.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,a=>{try{const o=new l.ima.AdsRenderingSettings;o.enablePreloading=!0,h=a.getAdsManager(e,o);const c=l.ima.AdEvent.Type,u=l.ima.AdErrorEvent.Type;h.addEventListener(u.AD_ERROR,s=>{var r,n;const a=s.getError();if(console.error("[DEBUG-ERROR] ❌ AD_ERROR:",null===(r=a.getMessage)||void 0===r?void 0:r.call(a)),I(),i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p(),b&&(b(new Error("Ad playback error")),b=void 0,A=void 0),g&&E<2){const e=500*Math.pow(2,E++);window.setTimeout(()=>{try{L(l,g)}catch{}},e)}else v("ad_error"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&(null===(n=e.play())||void 0===n||n.catch(()=>{}))}),h.addEventListener(c.CONTENT_PAUSE_REQUESTED,()=>{(null==t?void 0:t.continueLiveStreamDuringAds)||e.pause(),i=!0,m(!0),v("content_pause")}),h.addEventListener(c.STARTED,()=>{m(!0),s||(e.style.transition="opacity 0.3s ease-in-out",e.style.opacity="0",setTimeout(()=>{e.style.visibility="hidden"},300),e.muted=!0,e.volume=0,s=!0),d&&(d.volume=r?0:n,d.muted=r),f&&(f.style.pointerEvents="auto",f.style.display="flex",f.style.backgroundColor="#000",f.offsetHeight,f.style.opacity="1")}),h.addEventListener(c.CONTENT_RESUME_REQUESTED,()=>{i=!1,m(!1),v("content_resume")}),h.addEventListener(c.ALL_ADS_COMPLETED,()=>{i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p(),!(null==t?void 0:t.continueLiveStreamDuringAds)&&e.paused&&e.play().catch(()=>{}),v("all_ads_completed")}),A&&(A(),A=void 0,b=void 0)}catch(s){console.error("[IMA] Error setting up ads manager:",s),i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p(),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(()=>{}),b&&(b(new Error("Failed to setup ads manager")),b=void 0,A=void 0),v("ad_error")}},!1),c.addEventListener(l.ima.AdErrorEvent.Type.AD_ERROR,s=>{var r;const n=s.getError();console.error("[DEBUG-ERROR] ❌ ADS_LOADER ERROR:",null===(r=n.getMessage)||void 0===r?void 0:r.call(n)),i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p(),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(()=>{}),b&&(b(new Error("Ads loader error")),b=void 0,A=void 0),v("ad_error")},!1)}return L(l,a),S}catch(e){return console.error("[IMA] Failed to request ads:",e),null==o||o(e),b=void 0,A=void 0,Promise.reject(e)}},async preloadAds(e){if(!e||""===e.trim())return Promise.resolve();if(o.has(e))return Promise.resolve();const t=l.get(e);if(t)return t;const i=async function(e){const t=await fetch(e,{mode:"cors"});if(!t.ok)throw new Error(`Failed to preload VAST: ${t.status}`);return t.text()}(e).then(t=>{o.set(e,t)}).catch(()=>{o.delete(e)}).finally(()=>{l.delete(e)});return l.set(e,i),i},hasPreloadedAd:e=>o.has(e),async play(){var s,a;if(!(null===(s=window.google)||void 0===s?void 0:s.ima)||!u)return Promise.reject(new Error("IMA SDK not available"));if(!h)return Promise.reject(new Error("No ads manager"));try{const t=e.clientWidth||640,s=e.clientHeight||360;h.init(t,s,window.google.ima.ViewMode.NORMAL),i=!0;const a=r?0:n;d&&(d.volume=a,d.muted=r);try{h.setVolume(a)}catch{}return h.start(),Promise.resolve()}catch(s){return console.error("[IMA] ❌ Error starting ad:",s),i=!1,m(!1),(null==t?void 0:t.continueLiveStreamDuringAds)||null===(a=e.play())||void 0===a||a.catch(()=>{}),Promise.reject(s)}},async stop(){var e;i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p();try{null===(e=null==h?void 0:h.stop)||void 0===e||e.call(h)}catch{}I()},destroy(){var e;I(),i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none",f.parentElement&&f.parentElement.removeChild(f),f=void 0,d=void 0)},300)),p();try{null===(e=null==c?void 0:c.destroy)||void 0===e||e.call(c)}catch{}u=void 0,c=void 0,s=!1,o.clear(),l.clear()},isAdPlaying:()=>i,resize(e,t){var i;if(h&&(null===(i=window.google)||void 0===i?void 0:i.ima))try{console.log(`[IMA] Resizing ads manager to ${e}x${t}`),h.resize(e,t,window.google.ima.ViewMode.NORMAL)}catch(e){console.warn("[IMA] Error resizing ads manager:",e)}else console.warn("[IMA] Cannot resize: No ads manager or IMA SDK available")},on(e,t){a.has(e)||a.set(e,new Set),a.get(e).add(t)},off(e,t){var i;null===(i=a.get(e))||void 0===i||i.delete(t)},updateOriginalMutedState(e,t){const i="number"!=typeof t||Number.isNaN(t)?n:Math.max(0,Math.min(1,t));r=e,n=i},getOriginalMutedState:()=>r,getOriginalVolume:()=>n,setAdVolume(e){const t=Math.max(0,Math.min(1,e));if(d&&i&&(d.volume=t,d.muted=0===t),h&&i)try{h.setVolume(t)}catch{}},getAdVolume(){if(d&&i)return d.volume;if(h&&i)try{return h.getVolume()}catch(e){return console.warn("[IMA] Failed to get ad volume:",e),1}return 1},showPlaceholder(){R(),f&&(f.style.display="flex",f.style.backgroundColor="#000",f.offsetHeight,f.style.opacity="1",f.style.pointerEvents="auto")},hidePlaceholder(){f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.display="none",f.style.pointerEvents="none")},300))}}}function wl(e,t){let i=!1,s=!1,r=Math.max(0,Math.min(1,e.volume||1));const n=new Map,a=null==t?void 0:t.licenseKey,o=null==t?void 0:t.mainHlsInstance;let l,d,h,c,u;const f=new Map,g=new Map;let m={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function p(e,t){const i=n.get(e);if(i)for(const s of Array.from(i))try{s(t)}catch(t){console.warn(`[HlsAdPlayer] Error in event listener for ${e}:`,t)}}function y(e){e&&0!==e.length&&e.forEach(e=>{try{let t=e;u&&(t=`${t}${t.includes("?")?"&":"?"}session_id=${u}`),a&&(t=`${t}${t.includes("?")?"&":"?"}license_key=${a}`);new Image(1,1).src=t,console.log(`[HlsAdPlayer] Fired tracking pixel: ${t}`)}catch(e){console.warn("[HlsAdPlayer] Error firing tracking pixel:",e)}})}function v(e){if(0===e.length)throw new Error("No media files available");const t=e[0];if(!t)throw new Error("No media files available");if(1===e.length)return t;const i=function(){if(!o||!o.levels)return null;const e=o.currentLevel;if(-1===e||!o.levels[e]){const e=o.loadLevel;if(-1!==e&&o.levels[e]){const t=o.levels[e];return{width:t.width||1920,height:t.height||1080,bitrate:t.bitrate||5e6}}return null}const t=o.levels[e];return{width:t.width||1920,height:t.height||1080,bitrate:t.bitrate||5e6}}();if(!i)return console.log("[HlsAdPlayer] No main stream quality info, using first media file"),t;console.log("[HlsAdPlayer] Main stream quality:",i);const s=e.map(e=>{const t=Math.abs(e.width-i.width)+Math.abs(e.height-i.height),s=1e3*(e.bitrate||5e3),r=Math.abs(s-i.bitrate);return{file:e,score:2*t+r/1e3,resolutionDiff:t,bitrateDiff:r}});s.sort((e,t)=>e.score-t.score);const r=s[0];return r?(console.log("[HlsAdPlayer] Selected media file:",{url:r.file.url,resolution:`${r.file.width}x${r.file.height}`,bitrate:r.file.bitrate,score:r.score,resolutionDiff:r.resolutionDiff,bitrateDiff:r.bitrateDiff}),r.file):(console.log("[HlsAdPlayer] No best match found, using first media file"),t)}async function T(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch VAST: ${t.statusText}`);const i=await t.text();return console.log("[HlsAdPlayer] VAST XML received"),console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):",i.substring(0,2e3)),function(e){var t,i,s,r;try{const n=(new DOMParser).parseFromString(e,"text/xml"),a=n.querySelector("parsererror");if(a)return console.error("[HlsAdPlayer] XML parsing error (malformed VAST XML):",a.textContent),null;const o=n.querySelector("Ad");if(!o)return console.warn("[HlsAdPlayer] No Ad element found in VAST XML"),null;const l=o.getAttribute("id")||"unknown",d=(null===(t=n.querySelector("AdTitle"))||void 0===t?void 0:t.textContent)||"Ad",h="empty"===l||d.toLowerCase().includes("no ad available")||"no ad available"===d.toLowerCase(),c=((null===(i=n.querySelector("Duration"))||void 0===i?void 0:i.textContent)||"00:00:30").split(":"),u=3600*parseInt(c[0]||"0",10)+60*parseInt(c[1]||"0",10)+parseInt(c[2]||"0",10),f=n.querySelectorAll("MediaFile"),g=[];if(console.log(`[HlsAdPlayer] Found ${f.length} MediaFile element(s) in VAST XML`),f.forEach((e,t)=>{var i;const s=e.getAttribute("type")||"",r=(null===(i=e.textContent)||void 0===i?void 0:i.trim())||"",n=e.getAttribute("width")||"",a=e.getAttribute("height")||"";if(console.log(`[HlsAdPlayer] MediaFile ${t}: type="${s}", url="${r}", width="${n}", height="${a}"`),"application/x-mpegURL"===s||s.includes("m3u8")){if(!r)return void console.warn(`[HlsAdPlayer] MediaFile ${t} has HLS type but empty URL`);const i=e.getAttribute("bitrate"),o=i?parseInt(i,10):void 0;g.push({url:r,type:s,width:parseInt(n||"1920",10),height:parseInt(a||"1080",10),bitrate:o&&o>0?o:void 0}),console.log(`[HlsAdPlayer] Added HLS MediaFile: ${r}`)}else console.log(`[HlsAdPlayer] MediaFile ${t} ignored (type="${s}" is not HLS)`)}),0===g.length)return h?console.warn("[HlsAdPlayer] No ads available (VAST response indicates no ads)"):console.warn("[HlsAdPlayer] No HLS media files found in VAST XML"),null;const m={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],mute:[],unmute:[],pause:[],resume:[],fullscreen:[],exitFullscreen:[],skip:[],error:[]};n.querySelectorAll("Impression").forEach(e=>{var t;const i=null===(t=e.textContent)||void 0===t?void 0:t.trim();i&&m.impression.push(i)}),n.querySelectorAll("Tracking").forEach(e=>{var t;const i=e.getAttribute("event"),s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(i&&s){const e=i;m[e]&&m[e].push(s)}});const p=null===(r=null===(s=n.querySelector("ClickThrough"))||void 0===s?void 0:s.textContent)||void 0===r?void 0:r.trim();return{id:l,title:d,duration:u,mediaFiles:g,trackingUrls:m,clickThrough:p}}catch(e){return console.error("[HlsAdPlayer] Error parsing VAST XML:",e),null}}(i)}function E(){l&&c&&(l.addEventListener("timeupdate",()=>{if(!c||!l)return;const e=l.currentTime/c.duration;e>=.25&&!m.firstQuartile&&(m.firstQuartile=!0,y(c.trackingUrls.firstQuartile)),e>=.5&&!m.midpoint&&(m.midpoint=!0,y(c.trackingUrls.midpoint)),e>=.75&&!m.thirdQuartile&&(m.thirdQuartile=!0,y(c.trackingUrls.thirdQuartile))}),l.addEventListener("playing",()=>{c&&!m.start&&(m.start=!0,y(c.trackingUrls.start),console.log("[HlsAdPlayer] Ad started playing"))}),l.addEventListener("ended",()=>{c&&!m.complete&&(m.complete=!0,y(c.trackingUrls.complete),console.log("[HlsAdPlayer] Ad completed"),console.log("[HlsAdPlayer] Handling ad completion"),i=!1,S(!1),p("content_resume"),setTimeout(()=>{"true"===e.dataset.stormcloudAdPlaying&&(console.log("[HlsAdPlayer] Still in ad pod - keeping ad container visible (black screen)"),h&&(h.style.display="flex",h.style.pointerEvents="auto"))},50))}),l.addEventListener("error",e=>{console.error("[HlsAdPlayer] Ad video error:",e),c&&y(c.trackingUrls.error),A()}),l.addEventListener("volumechange",()=>{c&&(l.muted?y(c.trackingUrls.mute):y(c.trackingUrls.unmute))}),l.addEventListener("pause",()=>{c&&!l.ended&&y(c.trackingUrls.pause)}),l.addEventListener("play",()=>{c&&l.currentTime>0&&y(c.trackingUrls.resume)}))}function S(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function A(){console.log("[HlsAdPlayer] Handling ad error"),i=!1,S(!1);const n=e.muted;e.muted=s,e.volume=s?0:r,console.log(`[HlsAdPlayer] Restored mute state: ${n} -> ${s}`),h&&(h.style.display="none",h.style.pointerEvents="none"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(()=>{}),p("ad_error")}return{initialize(){var t;if(console.log("[HlsAdPlayer] Initializing"),!h){const i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(i),h=i}},async requestAds(e){if(console.log("[HlsAdPlayer] Requesting ads:",e),i)return console.warn("[HlsAdPlayer] Cannot request new ads while an ad is playing"),Promise.reject(new Error("Ad already playing"));try{let t;return u=`session-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,f.has(e)?(t=f.get(e),f.delete(e),console.log("[HlsAdPlayer] Using preloaded VAST response:",e)):t=await T(e),t?(c=t,console.log(`[HlsAdPlayer] Ad parsed: ${t.title}, duration: ${t.duration}s`),y(t.trackingUrls.impression),m.impression=!0,Promise.resolve()):(console.warn("[HlsAdPlayer] No ads available from VAST response"),p("ad_error"),Promise.resolve())}catch(e){return console.error("[HlsAdPlayer] Error requesting ads:",e),p("ad_error"),Promise.reject(e)}},async preloadAds(e){if(!e||""===e.trim())return Promise.resolve();if(f.has(e))return Promise.resolve();const t=g.get(e);if(t)return t;const i=T(e).then(t=>{t&&(f.set(e,t),console.log("[HlsAdPlayer] Cached VAST response for preloading:",e))}).catch(t=>{console.warn("[HlsAdPlayer] Failed to preload VAST response:",t),f.delete(e)}).finally(()=>{g.delete(e)});return g.set(e,i),i},hasPreloadedAd:e=>f.has(e),async play(){if(!c)return console.warn("[HlsAdPlayer] Cannot play: No ad loaded (no ads available)"),Promise.reject(new Error("No ad loaded"));console.log("[HlsAdPlayer] Starting ad playback");try{l||(l=function(){const e=document.createElement("video");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="contain",e.style.backgroundColor="#000",e.playsInline=!0,e.muted=!1,e.volume=1,console.log(`[HlsAdPlayer] Created ad video element with volume ${e.volume}`),e}(),null==h||h.appendChild(l),E()),m={impression:m.impression,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};const n=e.volume;if(r=Math.max(0,Math.min(1,n||r)),(null==t?void 0:t.continueLiveStreamDuringAds)?console.log("[HlsAdPlayer] Content continues (Live mode)"):(e.pause(),console.log("[HlsAdPlayer] Content paused (VOD mode)")),console.log("[HlsAdPlayer] FORCE MUTING main video"),e.muted=!0,e.volume=0,i=!0,S(!0),l){const e=s?0:r;l.volume=Math.max(0,Math.min(1,e)),l.muted=!1,console.log(`[HlsAdPlayer] Set ad video volume to ${l.volume}, muted: ${l.muted}, originalMutedState: ${s}, contentVolume: ${n}`)}h&&(h.style.display="flex",h.style.pointerEvents="auto"),p("content_pause");const a=v(c.mediaFiles);if(!a)throw new Error("No media file available for ad");if(console.log(`[HlsAdPlayer] Loading ad from: ${a.url}`),bl.isSupported())d&&d.destroy(),d=new bl({enableWorker:!0,lowLatencyMode:!1}),d.loadSource(a.url),d.attachMedia(l),d.on(bl.Events.MANIFEST_PARSED,()=>{console.log("[HlsAdPlayer] HLS manifest parsed, starting playback"),l.play().catch(e=>{console.error("[HlsAdPlayer] Error starting ad playback:",e),A()})}),d.on(bl.Events.ERROR,(e,t)=>{console.error("[HlsAdPlayer] HLS error:",t),t.fatal&&A()});else{if(!l.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS not supported");l.src=a.url,l.play().catch(e=>{console.error("[HlsAdPlayer] Error starting ad playback:",e),A()})}return Promise.resolve()}catch(e){return console.error("[HlsAdPlayer] Error playing ad:",e),A(),Promise.reject(e)}},async stop(){console.log("[HlsAdPlayer] Stopping ad"),i=!1,S(!1),h&&(h.style.display="none",h.style.pointerEvents="none"),d&&(d.destroy(),d=void 0),l&&(l.pause(),l.src=""),c=void 0},destroy(){console.log("[HlsAdPlayer] Destroying"),i=!1,S(!1),e.muted=s,e.volume=s?0:r,d&&(d.destroy(),d=void 0),l&&(l.pause(),l.src="",l.remove(),l=void 0),(null==h?void 0:h.parentElement)&&h.parentElement.removeChild(h),h=void 0,c=void 0,n.clear(),f.clear(),g.clear()},isAdPlaying:()=>i,resize(e,t){console.log(`[HlsAdPlayer] Resizing to ${e}x${t}`),h&&(h.style.width=`${e}px`,h.style.height=`${t}px`),l&&(l.style.width=`${e}px`,l.style.height=`${t}px`)},on(e,t){n.has(e)||n.set(e,new Set),n.get(e).add(t)},off(e,t){var i;null===(i=n.get(e))||void 0===i||i.delete(t)},updateOriginalMutedState(e,t){const i="number"!=typeof t||Number.isNaN(t)?r:Math.max(0,Math.min(1,t));console.log(`[HlsAdPlayer] updateOriginalMutedState called: { muted: ${s} -> ${e}, volume: ${r} -> ${i} }`),s=e,r=i},getOriginalMutedState:()=>s,getOriginalVolume:()=>r,setAdVolume(e){l&&i&&(l.volume=Math.max(0,Math.min(1,e)))},getAdVolume:()=>l&&i?l.volume:1,showPlaceholder(){var t;if(!h){const i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(i),h=i}h&&(h.style.display="flex",h.style.pointerEvents="auto")},hidePlaceholder(){h&&(h.style.display="none",h.style.pointerEvents="none")}}}bl.defaultConfig=void 0;let Dl=null;function xl(){var e,t,i,s;const r=navigator.userAgent,n=navigator.platform,a=navigator.vendor||"",o=navigator.maxTouchPoints||0,l=navigator.deviceMemory||null,d=navigator.hardwareConcurrency||1,h={width:null===screen||void 0===screen?void 0:screen.width,height:null===screen||void 0===screen?void 0:screen.height,availWidth:null===screen||void 0===screen?void 0:screen.availWidth,availHeight:null===screen||void 0===screen?void 0:screen.availHeight,orientation:(null===(e=null===screen||void 0===screen?void 0:screen.orientation)||void 0===e?void 0:e.type)||"",pixelDepth:null===screen||void 0===screen?void 0:screen.pixelDepth};let c="desktop",u="Unknown",f="Unknown",g="",m=!1,p=!1,y=!1,v=!1;if(r.includes("Web0S")){u="LG",f="webOS",m=!0,c="tv";const e=r.match(/Web0S\/([^\s]+)/);g=e?`webOS ${e[1]}`:"webOS TV"}else if(r.includes("Tizen")){u="Samsung",f="Tizen",m=!0,c="tv";const e=r.match(/Tizen\/([^\s]+)/),t=r.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";g=e?`Tizen ${e[1]} ${t}`.trim():"Tizen TV"}else r.includes("Philips")?(u="Philips",f="Saphi",m=!0,c="tv"):r.includes("Sharp")||r.includes("AQUOS")?(u="Sharp",f="Android TV",m=!0,c="tv"):r.includes("Android")&&(r.includes("Sony")||a.includes("Sony"))?(u="Sony",f="Android TV",m=!0,c="tv"):r.includes("Android")&&(r.includes("NetCast")||r.includes("LG"))?(u="LG",f="Android TV",m=!0,c="tv"):r.includes(" Roku")||r.includes("Roku/")?(u="Roku",f="Roku OS",m=!0,c="tv"):r.includes("AppleTV")&&(u="Apple",f="tvOS",m=!0,c="tv");if(r.includes("Android")){p=!0,f="Android",c=/Mobile/.test(r)?"mobile":"tablet",r.includes("Android")&&(0===o||r.includes("Google TV")||r.includes("XiaoMi"))&&(c="tv",m=!0,u="Unknown"===u?"Android TV":u);const e=r.match(/\(([^)]*Android[^)]*)\)/);e&&e[1]&&(g=e[1])}return/iPad|iPhone|iPod/.test(r)&&(f="iOS",c="mobile",u="Apple",navigator.maxTouchPoints>1&&/iPad/.test(r)&&(c="tablet")),p||m||/Mobile/.test(r)||(r.includes("Windows")?(f="Windows",c="desktop"):r.includes("Mac")&&!/iPhone/.test(r)?(f="macOS",c="desktop",o>1&&(c="tablet")):r.includes("Linux")&&(f="Linux",c="desktop")),"Unknown"===u&&((a.includes("Google")||r.includes("Chrome"))&&(u="Google"),a.includes("Apple")&&(u="Apple"),(a.includes("Samsung")||r.includes("SM-"))&&(u="Samsung")),y=/wv|WebView|Linux; U;/.test(r),0===(null===window||void 0===window?void 0:window.outerHeight)&&0===(null===window||void 0===window?void 0:window.outerWidth)&&(y=!0),v=window.matchMedia("(display-mode: standalone)").matches||!0===window.navigator.standalone||void 0!==(null===(i=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===i?void 0:i.angle),{brand:u,os:f,model:g||r.substring(0,50)+"...",deviceType:c,isSmartTV:m,isAndroid:p,isWebView:y,isWebApp:v,domain:window.location.hostname,origin:window.location.origin,path:window.location.pathname,userAgent:r,vendor:a,platform:n,screen:h,hardwareConcurrency:d,deviceMemory:l,maxTouchPoints:o,language:navigator.language,languages:(null===(s=navigator.languages)||void 0===s?void 0:s.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}async function Cl(e){if(Dl)return Dl;const t=JSON.stringify(e);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)try{let e;if(await crypto.subtle.digest("SHA-256",new Uint8Array([1,2,3])),"undefined"!=typeof TextEncoder)e=(new TextEncoder).encode(t);else{const i=unescape(encodeURIComponent(t)),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);e=s}const i=await crypto.subtle.digest("SHA-256",e),s=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("");return Dl=s,s}catch(e){console.warn("[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash")}let i=0;for(let e=0;e<t.length;e++){i=(i<<5)-i+t.charCodeAt(e),i&=i}const s=Math.abs(i).toString(16).padStart(8,"0"),r=Date.now().toString(16).padStart(12,"0"),n=Math.random().toString(16).substring(2,14).padStart(12,"0");return Dl=(s+r+n).padEnd(64,"0"),Dl}async function _l(e){try{const t=xl(),i={browserId:await Cl(t),...t},s={"Content-Type":"application/json"};e&&(s.Authorization=`Bearer ${e}`);const r=await fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track",{method:"POST",headers:s,body:JSON.stringify(i)});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);await r.json()}catch(e){console.error("[StormcloudVideoPlayer] Error sending initial tracking data:",e)}}async function Ml(e){try{const t=xl(),i={browserId:await Cl(t),timestamp:(new Date).toISOString()},s={"Content-Type":"application/json"};e&&(s.Authorization=`Bearer ${e}`);const r=await fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat",{method:"POST",headers:s,body:JSON.stringify(i)});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);await r.json()}catch(e){console.error("[StormcloudVideoPlayer] Error sending heartbeat:",e)}}function Ol(){"function"!=typeof Object.assign&&(Object.assign=function(e,...t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");const i=Object(e);for(let e=0;e<t.length;e++){const s=t[e];if(null!=s)for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(i[e]=s[e])}return i}),Array.from||(Array.from=function(e,t,i){const s=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");const r=s.length>>>0,n=new Array(r);for(let e=0;e<r;e++)n[e]=t?t.call(i,s[e],e):s[e];return n}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=!t||t<0?0:+t,this.substring(t,t+e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e}),String.prototype.includes||(String.prototype.includes=function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),function(){if("undefined"==typeof URLSearchParams){class e{constructor(t){this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach((e,t)=>{this.append(t,e)})}parseQueryString(e){const t=e.startsWith("?")?e.slice(1):e;t&&t.split("&").forEach(e=>{const[t,i]=e.split("=");if(t){const e=this.safeDecodeURIComponent(t),s=i?this.safeDecodeURIComponent(i):"";this.append(e,s)}})}safeDecodeURIComponent(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}}append(e,t){const i=this.params.get(e)||[];i.push(String(t)),this.params.set(e,i)}delete(e){this.params.delete(e)}get(e){const t=this.params.get(e);return t&&t.length>0&&void 0!==t[0]?t[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,t){this.params.set(e,[String(t)])}forEach(e){this.params.forEach((t,i)=>{t.forEach(t=>{e(t,i,this)})})}toString(){const e=[];return this.params.forEach((t,i)=>{t.forEach(t=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(t)}`)})}),e.join("&")}}window.URLSearchParams=e}}(),"undefined"==typeof TextEncoder&&(window.TextEncoder=class{constructor(){this.encoding="utf-8"}encode(e){const t=[];for(let i=0;i<e.length;i++){let s=e.charCodeAt(i);s<128?t.push(s):s<2048?t.push(192|s>>6,128|63&s):s<55296||s>=57344?t.push(224|s>>12,128|s>>6&63,128|63&s):(i++,s=65536+((1023&s)<<10|1023&e.charCodeAt(i)),t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s))}return new Uint8Array(t)}}),"undefined"==typeof Promise||Promise.prototype.finally||(Promise.prototype.finally=function(e){const t=this.constructor;return this.then(i=>t.resolve(e()).then(()=>i),i=>t.resolve(e()).then(()=>{throw i}))})}class Fl{constructor(e){this.attached=!1,this.inAdBreak=!1,this.ptsDriftEmaMs=0,this.adPodQueue=[],this.lastHeartbeatTime=0,this.currentAdIndex=0,this.totalAdsInBreak=0,this.showAds=!1,this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,this.adPodAllUrls=[],this.preloadingAdUrls=new Set,this.vastToMediaUrlMap=new Map,this.preloadedMediaUrls=new Set,this.preloadingMediaUrls=new Set,this.adRequestTokenCounter=0,this.activeAdRequestToken=null,this.adRequestWatchdogToken=null,this.adFailsafeToken=null,this.fetchedAdDurations=new Map,this.targetAdBreakDurationMs=null,this.isAdaptiveMode=!1,this.failedVastUrls=new Set,this.continuousFetchingActive=!1,this.adRequestQueue=[],this.successfulAdRequests=[],this.maxPlaceholderDurationMs=5e3,this.placeholderStartTimeMs=null,this.isShowingPlaceholder=!1,Ol();const t=kl();this.config={...e,...t},this.video=e.videoElement,Il(e.debugAdTiming),this.ima=this.createAdPlayer(!1)}createAdPlayer(e){const t=this.config.vastMode||"default";let i=this.config.adPlayerType||("adstorm"===t?"hls":"ima");return"ima"!==i||Rl()||(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Google IMA SDK not supported on this browser, falling back to HLS ad player"),i="hls"),"hls"===i?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Creating HLS ad player (AdStorm mode)"),wl(this.video,{continueLiveStreamDuringAds:e,...this.config.licenseKey?{licenseKey:this.config.licenseKey}:{},...this.hls?{mainHlsInstance:this.hls}:{}})):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Creating Google IMA ad player (Default mode)"),Pl(this.video,{continueLiveStreamDuringAds:e}))}async load(){var e,t;this.attached||this.attach();try{await this.fetchAdConfiguration()}catch(e){this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration:",e)}if(this.initializeTracking(),this.shouldUseNativeHls())return this.nativeHlsMode=!0,this.videoSrcProtection=this.config.src,this.video.src=this.config.src,this.isLiveStream=null!==(e=this.config.lowLatencyMode)&&void 0!==e&&e,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using native HLS playback - VOD mode:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:"vod (main video pauses during ads)"}),this.ima.destroy(),this.ima=this.createAdPlayer(!1),this.ima.initialize(),void(this.config.autoplay&&await(null===(t=this.video.play())||void 0===t?void 0:t.catch(()=>{})));this.hls=new bl({enableWorker:!0,backBufferLength:30,liveDurationInfinity:!0,lowLatencyMode:!!this.config.lowLatencyMode,maxLiveSyncPlaybackRate:this.config.lowLatencyMode?1.5:1,...this.config.lowLatencyMode?{liveSyncDuration:2}:{},maxBufferLength:30,maxMaxBufferLength:600,maxBufferSize:6e7,maxBufferHole:.5,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,startPosition:-1}),this.hls.on(bl.Events.MEDIA_ATTACHED,()=>{var e;null===(e=this.hls)||void 0===e||e.loadSource(this.config.src)}),this.hls.on(bl.Events.MANIFEST_PARSED,async(e,t)=>{var i,s,r,n,a;if(this.isLiveStream=null!==(r=null===(s=null===(i=this.hls)||void 0===i?void 0:i.levels)||void 0===s?void 0:s.some(e=>{var t,i;return!0===(null===(t=null==e?void 0:e.details)||void 0===t?void 0:t.live)||"LIVE"===(null===(i=null==e?void 0:e.details)||void 0===i?void 0:i.type)}))&&void 0!==r&&r,this.config.debugAdTiming){const e=this.shouldContinueLiveStreamDuringAds()?"live (main video continues muted during ads)":"vod (main video pauses during ads)";console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:e})}this.ima.destroy(),this.ima=this.createAdPlayer(this.shouldContinueLiveStreamDuringAds()),this.ima.initialize(),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay;const o=null!==(n=this.config.minSegmentsBeforePlay)&&void 0!==n?n:2;this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Waiting for",o,"segments to buffer before playback"),0!==o&&this.config.autoplay||(this.hasInitialBufferCompleted=!0,this.config.autoplay&&await(null===(a=this.video.play())||void 0===a?void 0:a.catch(()=>{})))}),this.hls.on(bl.Events.FRAG_BUFFERED,async(e,t)=>{var i,s;if(this.hasInitialBufferCompleted)return;this.bufferedSegmentsCount++;const r=null!==(i=this.config.minSegmentsBeforePlay)&&void 0!==i?i:2;this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Buffered segment ${this.bufferedSegmentsCount}/${r}`),this.bufferedSegmentsCount>=r&&(this.hasInitialBufferCompleted=!0,this.shouldAutoplayAfterBuffering&&(this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Initial buffer complete (${this.bufferedSegmentsCount} segments). Starting playback.`),await(null===(s=this.video.play())||void 0===s?void 0:s.catch(e=>{this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)}))))}),this.hls.on(bl.Events.FRAG_PARSING_METADATA,(e,t)=>{((null==t?void 0:t.samples)||[]).map(e=>({key:"ID3",value:null==e?void 0:e.data,ptsSeconds:null==e?void 0:e.pts})).forEach(e=>this.onId3Tag(e))}),this.hls.on(bl.Events.FRAG_CHANGED,(e,t)=>{var i,s,r;const n=null==t?void 0:t.frag,a=null==n?void 0:n.tagList;if(Array.isArray(a))for(const e of a){let t="",n="";if(Array.isArray(e))t=String(null!==(i=e[0])&&void 0!==i?i:""),n=String(null!==(s=e[1])&&void 0!==s?s:"");else if("string"==typeof e){const i=e.indexOf(":");i>=0?(t=e.substring(0,i),n=e.substring(i+1)):(t=e,n="")}if(t)if(t.includes("EXT-X-CUE-OUT")){const e=this.parseCueOutDuration(n),i={type:"start",...void 0!==e?{durationSeconds:e}:{},raw:{tag:t,value:n}};this.onScte35Marker(i)}else if(t.includes("EXT-X-CUE-OUT-CONT")){const e=this.parseCueOutCont(n),i={type:"progress",...void 0!==(null==e?void 0:e.duration)?{durationSeconds:e.duration}:{},...void 0!==(null==e?void 0:e.elapsed)?{ptsSeconds:e.elapsed}:{},raw:{tag:t,value:n}};this.onScte35Marker(i)}else if(t.includes("EXT-X-CUE-IN"))this.onScte35Marker({type:"end",raw:{tag:t,value:n}});else if(t.includes("EXT-X-DATERANGE")){const e=this.parseAttributeList(n),i="SCTE35-OUT"in e||void 0!==e["SCTE35-OUT"],s="SCTE35-IN"in e||void 0!==e["SCTE35-IN"],a=String(null!==(r=e.CLASS)&&void 0!==r?r:""),o=this.toNumber(e.DURATION);if(i||/com\.apple\.hls\.cue/i.test(a)){const i={type:"start",...void 0!==o?{durationSeconds:o}:{},raw:{tag:t,value:n,attrs:e}};this.onScte35Marker(i)}s&&this.onScte35Marker({type:"end",raw:{tag:t,value:n,attrs:e}})}}}),this.hls.on(bl.Events.ERROR,(e,t)=>{var i,s;if(null==t?void 0:t.fatal)switch(t.type){case bl.ErrorTypes.NETWORK_ERROR:null===(i=this.hls)||void 0===i||i.startLoad();break;case bl.ErrorTypes.MEDIA_ERROR:null===(s=this.hls)||void 0===s||s.recoverMediaError();break;default:this.destroy()}}),this.hls.attachMedia(this.video)}attach(){this.attached||(this.attached=!0,this.video.autoplay=!!this.config.autoplay,this.video.muted=!!this.config.muted,this.ima.initialize(),this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),this.ima.on("all_ads_completed",()=>{this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] IMA all_ads_completed event received - ending ad break"),this.inAdBreak&&this.handleAdPodComplete()}),this.ima.on("ad_error",e=>{const t=this.getRemainingAdMs();if(console.error("[AD-ERROR] Ad playback failed",e||""),this.inAdBreak)if(t>500&&this.adPodQueue.length>0){const e=this.findNextPreloadedAd();e?(this.currentAdIndex++,this.playSingleAd(e).catch(()=>{this.handleAdFailure()})):this.handleAdFailure()}else this.handleAdFailure();else this.handleAdFailure()}),this.ima.on("content_pause",()=>{this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog(),this.activeAdRequestToken=null,this.showAds=!0}),this.ima.on("content_resume",()=>{if(this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog(),this.activeAdRequestToken=null,this.showAds=!1,!this.inAdBreak)return;const e=this.getRemainingAdMs();this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] content_resume event: remaining=${e}ms, queued ads=${this.adRequestQueue.length}`),e>500?this.tryNextAvailableAd():this.handleAdPodComplete()}),this.video.addEventListener("timeupdate",()=>{this.onTimeUpdate(this.video.currentTime)}),this.video.addEventListener("emptied",()=>{if(this.nativeHlsMode&&this.videoSrcProtection&&!this.ima.isAdPlaying()){this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring:",this.videoSrcProtection);const e=this.video.currentTime,t=this.video.paused;this.video.src=this.videoSrcProtection,this.video.currentTime=e,t||this.video.play().catch(()=>{})}}))}shouldUseNativeHls(){if("other"===this.getStreamType())return!0;const e=this.video.canPlayType("application/vnd.apple.mpegurl");return!(!this.config.allowNativeHls||!e)}onId3Tag(e){"number"==typeof e.ptsSeconds&&this.updatePtsDrift(e.ptsSeconds);const t=this.parseScte35FromId3(e);t&&this.onScte35Marker(t)}parseScte35FromId3(e){var t,i,s,r;const n=this.decodeId3ValueToText(e.value);if(!n)return;const a=n.match(/EXT-X-CUE-OUT(?::([^\r\n]*))?/i)||n.match(/CUE-OUT(?::([^\r\n]*))?/i);if(a){const i=(null!==(t=a[1])&&void 0!==t?t:"").trim(),s=this.parseCueOutDuration(i);return{type:"start",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},...void 0!==s?{durationSeconds:s}:{},raw:{id3:n}}}const o=n.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(o){const t=(null!==(i=o[1])&&void 0!==i?i:"").trim(),s=this.parseCueOutCont(t);return{type:"progress",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},...void 0!==(null==s?void 0:s.duration)?{durationSeconds:s.duration}:{},raw:{id3:n}}}if(n.match(/EXT-X-CUE-IN\b/i)||n.match(/CUE-IN\b/i)){return{type:"end",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},raw:{id3:n}}}const l=n.match(/EXT-X-DATERANGE:([^\r\n]*)/i);if(l){const t=this.parseAttributeList(null!==(s=l[1])&&void 0!==s?s:""),i="SCTE35-OUT"in t||void 0!==t["SCTE35-OUT"],a="SCTE35-IN"in t||void 0!==t["SCTE35-IN"],o=String(null!==(r=t.CLASS)&&void 0!==r?r:""),d=this.toNumber(t.DURATION);if(i||/com\.apple\.hls\.cue/i.test(o)){return{type:"start",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},...void 0!==d?{durationSeconds:d}:{},raw:{id3:n,attrs:t}}}if(a){return{type:"end",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},raw:{id3:n,attrs:t}}}}if(/SCTE35-OUT/i.test(n)){return{type:"start",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},raw:{id3:n}}}if(/SCTE35-IN/i.test(n)){return{type:"end",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},raw:{id3:n}}}if(e.value instanceof Uint8Array){const t=this.parseScte35Binary(e.value);if(t)return t}}decodeId3ValueToText(e){try{if("string"==typeof e)return e;const t=new TextDecoder("utf-8",{fatal:!1}).decode(e);if(t&&/[\x20-\x7E]/.test(t))return t;let i="";for(let t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return i}catch{return}}onScte35Marker(e){var t,i;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 marker detected:",{type:e.type,ptsSeconds:e.ptsSeconds,durationSeconds:e.durationSeconds,currentTime:this.video.currentTime,raw:e.raw}),"start"===e.type){if(this.inAdBreak)return;this.inAdBreak=!0;const s=null!=e.durationSeconds?1e3*e.durationSeconds:void 0;this.expectedAdBreakDurationMs=s,this.currentAdBreakStartWallClockMs=Date.now();const r=this.isManifestBasedMarker(e),n=null===(t=this.config.immediateManifestAds)||void 0===t||t;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad start decision:",{isManifestMarker:r,forceImmediate:n,hasPts:"number"==typeof e.ptsSeconds}),r&&n)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (manifest-based)"),this.clearAdStartTimer(),this.handleAdStart(e);else if("number"==typeof e.ptsSeconds){const t=null!==(i=this.config.driftToleranceMs)&&void 0!==i?i:1e3,s=1e3*this.video.currentTime,r=s-this.ptsDriftEmaMs,n=Math.floor(1e3*e.ptsSeconds-r);this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] PTS-based timing calculation:",{nowMs:s,estCurrentPtsMs:r,markerPtsMs:1e3*e.ptsSeconds,deltaMs:n,tolerance:t}),n>t?(this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Scheduling ad start in ${n}ms`),this.scheduleAdStartIn(n)):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (within tolerance)"),this.clearAdStartTimer(),this.handleAdStart(e))}else this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (fallback)"),this.clearAdStartTimer(),this.handleAdStart(e);return void(null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs))}if("progress"===e.type&&this.inAdBreak){if(null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds),null!=this.expectedAdBreakDurationMs&&null!=this.currentAdBreakStartWallClockMs){const e=Date.now()-this.currentAdBreakStartWallClockMs,t=Math.max(0,this.expectedAdBreakDurationMs-e);this.scheduleAdStopCountdown(t)}if(!this.ima.isAdPlaying()&&null===this.activeAdRequestToken){const e=this.findCurrentOrNextBreak(1e3*this.video.currentTime),t=this.selectVastTagsForBreak(e)||(this.apiVastTagUrl?[this.apiVastTagUrl]:void 0);if(t&&t.length>0){const e=t[0],i=t.slice(1);this.adPodQueue=i,this.playSingleAd(e).catch(()=>{})}}}else if("end"===e.type)return this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.ima.isAdPlaying()&&this.ima.stop().catch(()=>{}),void this.handleAdPodComplete()}parseCueOutDuration(e){const t=parseFloat(e.trim());if(!Number.isNaN(t))return t;const i=e.match(/(?:^|[,\s])DURATION\s*=\s*([0-9.]+)/i)||e.match(/Duration\s*=\s*([0-9.]+)/i);if(i&&null!=i[1]){const e=i[1],t=parseFloat(e);return Number.isNaN(t)?void 0:t}}parseCueOutCont(e){const t=e.match(/Elapsed\s*=\s*([0-9.]+)/i),i=e.match(/Duration\s*=\s*([0-9.]+)/i),s={};if(t&&null!=t[1]){const e=parseFloat(t[1]);Number.isNaN(e)||(s.elapsed=e)}if(i&&null!=i[1]){const e=parseFloat(i[1]);Number.isNaN(e)||(s.duration=e)}if("elapsed"in s||"duration"in s)return s}parseAttributeList(e){var t,i,s;const r={},n=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;let a;for(;null!==(a=n.exec(e));){const e=null!==(t=a[1])&&void 0!==t?t:"";let n=null!==(s=null!==(i=a[3])&&void 0!==i?i:a[4])&&void 0!==s?s:"";n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1)),e&&(r[e]=n)}return r}toNumber(e){if(null==e)return;const t="string"==typeof e?parseFloat(e):Number(e);return Number.isNaN(t)?void 0:t}isManifestBasedMarker(e){const t=e.raw;if(!t)return!1;if(t.tag){const e=String(t.tag);return e.includes("EXT-X-CUE-OUT")||e.includes("EXT-X-CUE-IN")||e.includes("EXT-X-DATERANGE")}return t.id3||t.splice_command_type,!1}parseScte35Binary(e){const t=new class{constructor(e){this.buf=e,this.bytePos=0,this.bitPos=0}readBits(e){let t=0;for(;e>0;){if(this.bytePos>=this.buf.length)return t;const i=8-this.bitPos,s=Math.min(e,i);t=t<<s|this.buf[this.bytePos]>>i-s&((1<<s)-1&255),this.bitPos+=s,this.bitPos>=8&&(this.bitPos=0,this.bytePos+=1),e-=s}return t>>>0}skipBits(e){this.readBits(e)}}(e);if(252!==t.readBits(8))return;t.readBits(1),t.readBits(1),t.readBits(2);t.readBits(12);t.readBits(8),t.readBits(1),t.readBits(6);t.readBits(1),t.readBits(32);t.readBits(8),t.readBits(12);t.readBits(12);if(5!==t.readBits(8))return;t.readBits(32);const i=1===t.readBits(1);if(t.readBits(7),i)return;const s=1===t.readBits(1),r=1===t.readBits(1),n=1===t.readBits(1),a=1===t.readBits(1);if(t.readBits(4),r&&!a){1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7)}else if(!r){const e=t.readBits(8);for(let i=0;i<e;i++)if(t.readBits(8),!a){1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7)}}let o;if(n){t.readBits(6),t.readBits(1);o=(4294967296*t.readBits(1)+t.readBits(32))/9e4}if(t.readBits(16),t.readBits(8),t.readBits(8),s){return{type:"start",...void 0!==o?{durationSeconds:o}:{},raw:{splice_command_type:5}}}}initializeTracking(){_l(this.config.licenseKey).then(()=>{this.heartbeatInterval=window.setInterval(()=>{this.sendHeartbeatIfNeeded()},5e3)}).catch(e=>{this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send initial tracking:",e),this.heartbeatInterval=window.setInterval(()=>{this.sendHeartbeatIfNeeded()},5e3)})}sendHeartbeatIfNeeded(){const e=Date.now();(!this.lastHeartbeatTime||e-this.lastHeartbeatTime>3e4)&&(this.lastHeartbeatTime=e,Ml(this.config.licenseKey).catch(e=>{this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send heartbeat:",e)}))}async fetchAdConfiguration(){var e,t,i,s,r,n,a;const o=this.config.vastMode||"default";if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] VAST mode:",o),"adstorm"===o){if(!this.config.licenseKey)return void(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] AdStorm mode requires a license key"));const e=`https://adstorm.co/api-adstorm-dev/adstorm/vast/${this.config.licenseKey}`;return this.apiVastTagUrl=e,void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using AdStorm VAST endpoint (adstorm mode):",e))}if(this.config.vastTagUrl)return this.apiVastTagUrl=this.config.vastTagUrl,void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using custom VAST tag URL:",this.apiVastTagUrl));const l="https://adstorm.co/api-adstorm-dev/adstorm/ads/web";this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Fetching ad configuration from:",l);const d={};this.config.licenseKey&&(d.Authorization=`Bearer ${this.config.licenseKey}`);const h=await fetch(l,{headers:d});if(!h.ok)return void(this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Failed to fetch ad configuration: ${h.status}`));const c=await h.json(),u=null===(i=null===(t=null===(e=c.response)||void 0===e?void 0:e.ima)||void 0===t?void 0:t["publisherdesk.ima"])||void 0===i?void 0:i.payload;u?(this.apiVastTagUrl=decodeURIComponent(u),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Extracted VAST tag URL from /ads/web:",this.apiVastTagUrl)):this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] No VAST tag URL found in /ads/web response");const f=null===(a=null===(n=null===(r=null===(s=c.response)||void 0===s?void 0:s.options)||void 0===r?void 0:r.vast)||void 0===n?void 0:n.cue_tones)||void 0===a?void 0:a.number_ads;null!=f&&f>0&&(this.apiNumberAds=f,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Number of ads per break from API:",this.apiNumberAds))}getCurrentAdIndex(){return this.currentAdIndex}getTotalAdsInBreak(){return this.totalAdsInBreak}generateVastUrlsWithCorrelators(e,t){const i=[];for(let s=0;s<t;s++)try{const t=new URL(e),r=Date.now(),n=`${r}${Math.floor(1e6*Math.random())}${s}`;t.searchParams.set("correlator",n),i.push(t.toString())}catch(t){console.warn("[StormcloudVideoPlayer] Failed to parse VAST URL:",e,t),i.push(`${e}${e.includes("?")?"&":"?"}correlator=${Date.now()}${s}`)}return i}isAdPlaying(){return this.inAdBreak&&this.ima.isAdPlaying()}isShowingAds(){return this.showAds}getStreamType(){const e=this.config.src.toLowerCase();return e.includes(".m3u8")||e.includes("/hls/")||e.includes("application/vnd.apple.mpegurl")?"hls":"other"}shouldShowNativeControls(){var e,t;return"other"===this.getStreamType()?!(null!==(e=this.config.showCustomControls)&&void 0!==e&&e):!(!this.config.allowNativeHls||null!==(t=this.config.showCustomControls)&&void 0!==t&&t)}shouldContinueLiveStreamDuringAds(){return!this.config.allowNativeHls&&!!this.isLiveStream}async handleAdStart(e){const t=this.findCurrentOrNextBreak(1e3*this.video.currentTime),i=this.selectVastTagsForBreak(t);let s;if(this.apiVastTagUrl)s=this.apiVastTagUrl;else{if(!(i&&i.length>0&&i[0]))return;s=i[0]}const r=null!=e.durationSeconds?1e3*e.durationSeconds:null==t?void 0:t.durationMs;this.isLiveStream&&null!=r&&r>0?(this.isAdaptiveMode=!0,this.targetAdBreakDurationMs=r,this.fetchedAdDurations.clear(),this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] 📺 LIVE MODE: Target duration=${r}ms | Will continuously fetch ads during break`)):(this.isAdaptiveMode=!1,this.targetAdBreakDurationMs=null,this.fetchedAdDurations.clear(),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🎬 VOD MODE: Using fixed ad strategy")),this.adPodAllUrls=[],this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.failedVastUrls.clear(),this.adRequestQueue=[],this.successfulAdRequests=[],this.continuousFetchingActive=!0,this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null;const n=this.video.muted,a=this.video.volume;this.ima.updateOriginalMutedState(n,a),this.inAdBreak=!0,this.currentAdIndex=0,this.totalAdsInBreak=1,this.adPodQueue=[],null==this.expectedAdBreakDurationMs&&null!=r&&(this.expectedAdBreakDurationMs=r,this.currentAdBreakStartWallClockMs=Date.now(),this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🚀 Immediately requesting first ad...");const o=this.generateVastUrlsWithCorrelators(s,1)[0];if(!o)return this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ Failed to generate first ad URL"),void this.handleAdPodComplete();try{await this.ima.requestAds(o),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ First ad request successful, starting playback"),this.successfulAdRequests.push(o),this.currentAdIndex++,this.startContinuousFetching(s),await this.ima.play()}catch(e){this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ First ad request failed:",e),this.failedVastUrls.add(o),this.startContinuousFetching(s),this.tryNextAvailableAd()}}startContinuousFetching(e){this.continuousFetchingActive&&(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🔄 Starting continuous ad fetching loop"),this.continuousFetchLoop(e))}async continuousFetchLoop(e){for(;this.continuousFetchingActive&&this.inAdBreak;){if(this.getRemainingAdMs()<=0){this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ Ad break time expired, stopping fetch loop");break}const t=3;if(this.adRequestQueue.length>=t){this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] ⏸️ Queue full (${this.adRequestQueue.length}), pausing fetching...`),await new Promise(e=>setTimeout(e,2e3));continue}const i=this.generateVastUrlsWithCorrelators(e,1)[0];if(i&&!this.failedVastUrls.has(i)){this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] 📡 Attempting to fetch ad (${this.successfulAdRequests.length+this.adRequestQueue.length+1} total)...`);try{const e=await fetch(i,{mode:"cors"});if(!e.ok)throw new Error(`Failed to fetch VAST: ${e.status}`);const t=await e.text(),s=(new DOMParser).parseFromString(t,"text/xml");if(0===s.querySelectorAll("MediaFile").length){this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⚠️ VAST response has no media files, skipping"),this.failedVastUrls.add(i),await new Promise(e=>setTimeout(e,1e3));continue}this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] ✅ Successfully fetched ad, adding to queue (queue size: ${this.adRequestQueue.length+1})`),this.adRequestQueue.push(i),this.totalAdsInBreak++,await new Promise(e=>setTimeout(e,500))}catch(e){this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ❌ Ad fetch failed:",e.message),this.failedVastUrls.add(i),await new Promise(e=>setTimeout(e,2e3))}}else await new Promise(e=>setTimeout(e,1e3))}this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Continuous fetch loop ended")}stopContinuousFetching(){this.continuousFetchingActive=!1,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Stopping continuous ad fetching")}async tryNextAvailableAd(e=0){const t=this.getRemainingAdMs();if(t<=500)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No time remaining, ending ad break"),void this.handleAdPodComplete();if(this.adRequestQueue.length>0){const e=this.adRequestQueue.shift();if(e){this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] 🎬 Playing next queued ad (${this.currentAdIndex+1}/${this.totalAdsInBreak}, ${this.adRequestQueue.length} remaining in queue)`);const t=this.video.muted,i=this.video.volume;return this.ima.updateOriginalMutedState(t,i),this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] 🔊 Updated ad audio state: muted=${t}, volume=${i}`),this.currentAdIndex++,this.successfulAdRequests.push(e),void await this.playSingleAd(e).catch(()=>{this.tryNextAvailableAd(0)})}}if(this.continuousFetchingActive&&e<5&&t>2e3)return this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] ⏳ Queue empty but fetching active, waiting... (retry ${e+1}/5)`),await new Promise(e=>setTimeout(e,1e3)),void await this.tryNextAvailableAd(e+1);!this.isShowingPlaceholder&&t>1e3?this.showPlaceholderAndWaitForAds():(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No more ads available, ending ad break"),this.handleAdPodComplete())}async showPlaceholderAndWaitForAds(){const e=this.getRemainingAdMs(),t=Math.min(this.maxPlaceholderDurationMs,e);if(t<1e3)return void this.handleAdPodComplete();this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] ⬛ Showing black placeholder for ${t}ms while waiting for ads`),this.isShowingPlaceholder=!0,this.placeholderStartTimeMs=Date.now(),this.ima.showPlaceholder();const i=Math.floor(t/500);for(let e=0;e<i;e++){if(await new Promise(e=>setTimeout(e,500)),!this.inAdBreak)return;if(this.adRequestQueue.length>0){this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ New ad became available during placeholder"),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,this.ima.hidePlaceholder();const e=this.video.muted,t=this.video.volume;this.ima.updateOriginalMutedState(e,t);const i=this.adRequestQueue.shift();return void(i&&(this.currentAdIndex++,this.successfulAdRequests.push(i),await this.playSingleAd(i).catch(()=>{this.tryNextAvailableAd()})))}}this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏰ Placeholder timeout reached, no ads fetched"),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,this.ima.hidePlaceholder(),this.handleAdPodComplete()}findCurrentOrNextBreak(e){var t;const i=[];let s;for(const r of i){const i=null!==(t=this.config.driftToleranceMs)&&void 0!==t?t:1e3;r.startTimeMs<=e+i&&(null==s||r.startTimeMs>(s.startTimeMs||0))&&(s=r)}return s}onTimeUpdate(e){if(this.ima.isAdPlaying())return;const t=1e3*e,i=this.findBreakForTime(t);i&&this.handleMidAdJoin(i,t)}async handleMidAdJoin(e,t){var i;const s=null!==(i=e.durationMs)&&void 0!==i?i:0,r=e.startTimeMs+s;if(s>0&&t>e.startTimeMs&&t<r){const i=r-t,s=this.selectVastTagsForBreak(e)||(this.apiVastTagUrl?[this.apiVastTagUrl]:void 0);if(s&&s.length>0){const e=s[0],t=s.slice(1);this.adPodQueue=t,this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),await this.playSingleAd(e),this.inAdBreak=!0,this.expectedAdBreakDurationMs=i,this.currentAdBreakStartWallClockMs=Date.now(),this.scheduleAdStopCountdown(i)}}}scheduleAdStopCountdown(e){this.clearAdStopTimer();const t=Math.max(0,Math.floor(e));0!==t?this.adStopTimerId=window.setTimeout(()=>{this.ensureAdStoppedByTimer()},t):this.ensureAdStoppedByTimer()}clearAdStopTimer(){null!=this.adStopTimerId&&(clearTimeout(this.adStopTimerId),this.adStopTimerId=void 0)}ensureAdStoppedByTimer(){var e,t;if(!this.inAdBreak)return;this.adStopTimerId=void 0;const i=this.ima.isAdPlaying(),s=this.adPodQueue.length>0,r=Math.max(250,Math.floor(null!==(e=this.config.adBreakCheckIntervalMs)&&void 0!==e?e:1e3)),n=this.config.maxAdBreakExtensionMs,a="number"==typeof n&&n>0?n:6e4;let o=0;null!=this.currentAdBreakStartWallClockMs&&(o=Date.now()-this.currentAdBreakStartWallClockMs);const l=null!==(t=this.expectedAdBreakDurationMs)&&void 0!==t?t:0,d=Math.max(0,o-l);(i||s||this.showAds)&&d<a?this.scheduleAdStopCountdown(r):(i&&this.ima.stop().catch(()=>{}),this.handleAdPodComplete())}scheduleAdStartIn(e){this.clearAdStartTimer();const t=Math.max(0,Math.floor(e));0!==t?this.adStartTimerId=window.setTimeout(()=>{this.handleAdStart({type:"start"}).catch(()=>{})},t):this.handleAdStart({type:"start"}).catch(()=>{})}clearAdStartTimer(){null!=this.adStartTimerId&&(clearTimeout(this.adStartTimerId),this.adStartTimerId=void 0)}updatePtsDrift(e){const t=1e3*(this.video.currentTime-e);if(!Number.isFinite(t)||Math.abs(t)>6e4)return;this.ptsDriftEmaMs=.9*this.ptsDriftEmaMs+.1*t}async playSingleAd(e){if(this.ima.isAdPlaying())return;if(this.failedVastUrls.has(e))return console.warn("[AD-ERROR] Skipping already-failed VAST URL:",e.substring(0,60)),void this.handleAdFailure();const t=++this.adRequestTokenCounter;this.activeAdRequestToken=t,this.startAdRequestWatchdog(t);try{if(await this.ima.requestAds(e),this.clearAdRequestWatchdog(),this.activeAdRequestToken!==t)return;try{this.startAdFailsafeTimer(t),await this.ima.play()}catch(i){return console.error("[AD-ERROR] Failed to play ad:",i),this.failedVastUrls.add(e),this.clearAdFailsafeTimer(),this.activeAdRequestToken===t&&(this.activeAdRequestToken=null),void this.handleAdFailure()}}catch(i){console.error("[AD-ERROR] Ad request failed:",null==i?void 0:i.message),this.failedVastUrls.add(e),this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken===t&&(this.activeAdRequestToken=null),this.handleAdFailure()}}handleAdPodComplete(){var e;this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken=null,this.stopContinuousFetching(),this.isShowingPlaceholder&&(this.ima.hidePlaceholder(),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null),this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.adRequestQueue=[],this.successfulAdRequests=[],this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.adPodQueue=[],this.adPodAllUrls=[],this.showAds=!1,this.currentAdIndex=0,this.totalAdsInBreak=0,this.ima.stop().catch(()=>{});const t=this.ima.getOriginalMutedState(),i=this.ima.getOriginalVolume();this.video.muted!==t&&(this.video.muted=t),Math.abs(this.video.volume-i)>.01&&(this.video.volume=i),!this.shouldContinueLiveStreamDuringAds()&&this.video.paused&&(null===(e=this.video.play())||void 0===e||e.catch(()=>{}))}handleAdFailure(){const e=this.getRemainingAdMs();this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] Ad failure: remaining=${e}ms, queued ads=${this.adRequestQueue.length}`),e>500?this.tryNextAvailableAd():(console.error("[AD-ERROR] Ad failed and no time remaining. Failed URLs:",this.failedVastUrls.size),this.handleAdPodComplete())}startAdRequestWatchdog(e){var t;this.clearAdRequestWatchdog();const i=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adRequestWatchdogToken=e,this.adRequestWatchdogId=window.setTimeout(()=>{this.adRequestWatchdogToken===e&&(this.adRequestWatchdogId=void 0,this.adRequestWatchdogToken=null,this.activeAdRequestToken===e&&(this.activeAdRequestToken=null),this.logAdState("ad_request_timeout",{token:e,timeoutMs:i}),this.handleAdFailure())},i),this.logAdState("ad_request_watchdog_started",{token:e,timeoutMs:i})}clearAdRequestWatchdog(){null!=this.adRequestWatchdogId&&(clearTimeout(this.adRequestWatchdogId),this.adRequestWatchdogId=void 0),null!=this.adRequestWatchdogToken&&(this.logAdState("ad_request_watchdog_cleared",{token:this.adRequestWatchdogToken}),this.adRequestWatchdogToken=null)}startAdFailsafeTimer(e){var t;this.clearAdFailsafeTimer();const i=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adFailsafeToken=e,this.adFailsafeTimerId=window.setTimeout(()=>{this.adFailsafeToken===e&&(this.adFailsafeTimerId=void 0,this.adFailsafeToken=null,this.activeAdRequestToken===e&&(this.activeAdRequestToken=null),this.logAdState("ad_failsafe_triggered",{token:e,failsafeMs:i,videoPaused:this.video.paused,imaAdPlaying:this.ima.isAdPlaying()}),this.handleAdFailure())},i),this.logAdState("ad_failsafe_started",{token:e,failsafeMs:i})}clearAdFailsafeTimer(){null!=this.adFailsafeTimerId&&(clearTimeout(this.adFailsafeTimerId),this.logAdState("ad_failsafe_cleared",{token:this.adFailsafeToken}),this.adFailsafeTimerId=void 0),this.adFailsafeToken=null}selectVastTagsForBreak(e){if(e&&e.vastTagUrl)return e.vastTagUrl.includes(",")?e.vastTagUrl.split(",").map(e=>e.trim()).filter(e=>e.length>0):[e.vastTagUrl]}logAdState(e,t={}){this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer][AdState]",{event:e,timestamp:(new Date).toISOString(),showAds:this.showAds,adPlaying:this.ima.isAdPlaying(),inAdBreak:this.inAdBreak,activeAdRequestToken:this.activeAdRequestToken,...t})}async fetchAndParseVastXml(e){try{const t=await fetch(e,{mode:"cors"});if(!t.ok)throw new Error(`Failed to fetch VAST: ${t.status}`);const i=await t.text();return this.extractMediaUrlsFromVast(i)}catch(t){return this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Failed to fetch/parse VAST XML: ${e}`,t),[]}}extractMediaUrlsFromVast(e){var t;const i=[];try{const s=new DOMParser,r=s.parseFromString(e,"text/xml").querySelectorAll("MediaFile");for(const e of Array.from(r)){const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s){const e=s.toLowerCase();(e.endsWith(".mp4")||e.endsWith(".webm")||e.endsWith(".mov")||e.endsWith(".avi")||e.includes(".mp4?")||e.includes(".webm?")||e.includes("/mp4/")||e.includes("type=video"))&&i.push(s)}}this.config.debugAdTiming&&i.length>0&&console.log(`[StormcloudVideoPlayer] Extracted ${i.length} media URLs from VAST:`,i)}catch(e){this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to parse VAST XML:",e)}return i}async fetchVastDuration(e){var t;try{const i=await fetch(e,{mode:"cors"});if(!i.ok)return this.config.debugAdTiming&&console.warn(`[ADAPTIVE-POD] Failed to fetch VAST: ${i.status}`),null;const s=await i.text(),r=new DOMParser,n=null===(t=r.parseFromString(s,"text/xml").querySelector("Duration"))||void 0===t?void 0:t.textContent;if(!n)return this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] No Duration element found in VAST"),null;const a=n.split(":");return 3600*parseInt(a[0]||"0",10)+60*parseInt(a[1]||"0",10)+parseInt(a[2]||"0",10)}catch(t){return this.config.debugAdTiming&&console.warn(`[ADAPTIVE-POD] Error fetching VAST duration from ${e}:`,t),null}}calculateAdditionalAdsNeeded(){if(!this.isAdaptiveMode||null===this.targetAdBreakDurationMs)return 0;let e=0;for(const t of this.fetchedAdDurations.values())e+=1e3*t;const t=this.fetchedAdDurations.size,i=t>0?e/t:3e4,s=this.adPodAllUrls.length-t,r=s*i,n=e+r,a=this.targetAdBreakDurationMs-n;if(a<=0)return this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✅ Target duration met: Fetched=${e}ms + Queued(${s} ads)=${r}ms = ${n}ms / Target=${this.targetAdBreakDurationMs}ms`),0;const o=Math.ceil(a/i);return this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] 📊 Need ${o} more ads | Fetched: ${e}ms (${t} ads) | Queued: ${r}ms (${s} ads) | Target: ${this.targetAdBreakDurationMs}ms | Remaining: ${a}ms | Avg duration: ${i}ms`),o}async addAdaptiveAdsToQueue(){if(!this.isAdaptiveMode||!this.apiVastTagUrl)return;const e=this.calculateAdditionalAdsNeeded();if(e<=0)return;const t=this.generateVastUrlsWithCorrelators(this.apiVastTagUrl,e);this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] 🔄 Adding ${t.length} additional VAST URLs to queue (will be preloaded sequentially)`),this.adPodAllUrls.push(...t),this.adPodQueue.push(...t),this.totalAdsInBreak+=t.length}async preloadMediaFile(e){if(!this.preloadedMediaUrls.has(e)&&!this.preloadingMediaUrls.has(e)){this.preloadingMediaUrls.add(e);try{this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Preloading video file: ${e}`);const t=await fetch(e,{mode:"cors",method:"GET",headers:{Range:"bytes=0-1048576"}});(t.ok||206===t.status)&&(this.preloadedMediaUrls.add(e),this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Successfully preloaded video file: ${e}`))}catch(t){this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Failed to preload video file: ${e}`,t)}finally{this.preloadingMediaUrls.delete(e)}}}async preloadAllAdsInBackground(){var e,t;if(0!==this.adPodAllUrls.length)if(this.isAdaptiveMode){this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 🔄 Starting sequential preload of remaining ads");const i=new Set;for(const s of this.adPodAllUrls)((null===(t=(e=this.ima).hasPreloadedAd)||void 0===t?void 0:t.call(e,s))||this.fetchedAdDurations.has(s))&&i.add(s);for(this.config.debugAdTiming&&i.size>0&&console.log(`[ADAPTIVE-POD] 📦 Skipping ${i.size} already-preloaded ads`);;){const e=this.adPodAllUrls.find(e=>!i.has(e));if(!e){this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✅ All queued ads processed (${i.size} total)`);break}i.add(e),this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] 📥 Preloading ad ${i.size}/${this.adPodAllUrls.length}...`);try{await this.preloadSingleAd(e)}catch(e){this.config.debugAdTiming&&console.warn(`[ADAPTIVE-POD] ⚠️ Preload failed for ad ${i.size}:`,e)}if(0===this.calculateAdditionalAdsNeeded()){this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✅ Target duration reached (${i.size} ads preloaded), stopping`);break}}this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✅ Sequential preloading completed (${i.size} ads ready)`)}else{this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Starting parallel preload of ${this.adPodAllUrls.length} ads`);const e=this.adPodAllUrls.map(e=>this.preloadSingleAd(e).catch(t=>{this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Preload failed for ${e}:`,t)}));await Promise.all(e),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Background preloading completed for all ads")}}async preloadSingleAd(e){if(e)try{if(this.isAdaptiveMode&&!this.fetchedAdDurations.has(e)){const t=await this.fetchVastDuration(e);null!==t&&(this.fetchedAdDurations.set(e,t),this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✓ Fetched ad duration: ${t}s (${this.fetchedAdDurations.size} ads fetched so far)`),await this.addAdaptiveAdsToQueue())}this.ima.preloadAds&&!this.ima.hasPreloadedAd(e)&&(this.preloadingAdUrls.has(e)||(this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Preloading VAST: ${e}`),this.preloadingAdUrls.add(e),await this.ima.preloadAds(e).then(()=>{this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] IMA VAST preload complete: ${e}`)}).catch(t=>{this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] IMA VAST preload failed: ${e}`,t)}).finally(()=>{this.preloadingAdUrls.delete(e)})));let t=this.vastToMediaUrlMap.get(e);if(t||(this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Fetching and parsing VAST to extract media URLs: ${e}`),t=await this.fetchAndParseVastXml(e),this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Extracted ${t.length} media URLs:`,t),t.length>0&&this.vastToMediaUrlMap.set(e,t)),t&&t.length>0){const e=t[0];e&&!this.preloadedMediaUrls.has(e)&&await this.preloadMediaFile(e)}}catch(t){this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Failed to preload ad: ${e}`,t)}}findNextPreloadedAd(){var e,t,i;for(let s=0;s<this.adPodQueue.length;s++){const r=this.adPodQueue[s];if(!r)continue;if(this.failedVastUrls.has(r)){console.warn("[AD-ERROR] Skipping failed URL in queue");continue}const n=null!==(i=null===(t=(e=this.ima).hasPreloadedAd)||void 0===t?void 0:t.call(e,r))&&void 0!==i&&i,a=this.vastToMediaUrlMap.get(r),o=!!(a&&a.length>0)&&this.preloadedMediaUrls.has(a[0]);if(n||o)return this.adPodQueue.splice(0,s+1),r}}getRemainingAdMs(){if(null==this.expectedAdBreakDurationMs||null==this.currentAdBreakStartWallClockMs)return 0;const e=Date.now()-this.currentAdBreakStartWallClockMs;return Math.max(0,this.expectedAdBreakDurationMs-e)}findBreakForTime(e){const t=[];for(const i of t){const t=(i.startTimeMs||0)+(i.durationMs||0);if(e>=(i.startTimeMs||0)&&(!i.durationMs||e<t))return i}}toggleMute(){if(this.ima.isAdPlaying()){const e=!this.isMuted();this.ima.updateOriginalMutedState(e,this.video.volume),this.ima.setAdVolume(e?0:1),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:",e)}else this.video.muted=!this.video.muted,this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted:",this.video.muted)}toggleFullscreen(){return new Promise((e,t)=>{if(document.fullscreenElement)document.exitFullscreen().then(()=>{this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Exited fullscreen"),e()}).catch(e=>{this.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Exit fullscreen error:",e),t(e)});else{const i=this.video.parentElement;if(!i)return void t(new Error("No parent container found for fullscreen"));i.requestFullscreen().then(()=>{this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Entered fullscreen"),e()}).catch(e=>{this.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Fullscreen error:",e),t(e)})}})}isMuted(){return this.ima.isAdPlaying()?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] isMuted() override during ad playback -> false"),!1):this.video.muted}setMuted(e){const t=this.ima.isAdPlaying();if(t&&e===this.video.muted)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted reflective update during ad ignored",{muted:e});else{if(this.video.muted=e,t)return this.ima.updateOriginalMutedState(e,this.video.volume),this.ima.setAdVolume(e?0:1),void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted applied during ad",{muted:e}));this.ima.updateOriginalMutedState(e,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted called:",e)}}setVolume(e){const t=Math.max(0,Math.min(1,e));this.ima.isAdPlaying()?(this.ima.setAdVolume(t),this.ima.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume applied during ad",{volume:t})):(this.video.volume=t,this.video.muted=0===t,this.ima.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume called:",t))}isFullscreen(){return!!document.fullscreenElement}isLive(){return this.isLiveStream}get videoElement(){return this.video}resize(){if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing player"),this.ima&&this.ima.isAdPlaying()){const e=this.video.clientWidth||640,t=this.video.clientHeight||360;this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Resizing ads manager to ${e}x${t}`),this.ima.resize(e,t)}}destroy(){var e,t;this.stopContinuousFetching(),this.clearAdStartTimer(),this.clearAdStopTimer(),this.clearAdFailsafeTimer(),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),null===(e=this.hls)||void 0===e||e.destroy(),null===(t=this.ima)||void 0===t||t.destroy(),this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.adPodAllUrls=[],this.adRequestQueue=[],this.successfulAdRequests=[]}}var Nl={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Ul=g.createContext&&g.createContext(Nl),Bl=["attr","size","title"];function $l(e,t){if(null==e)return{};var i,s,r=function(e,t){if(null==e)return{};var i={};for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s)){if(t.indexOf(s)>=0)continue;i[s]=e[s]}return i}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(s=0;s<n.length;s++)i=n[s],t.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}function Vl(){return Vl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},Vl.apply(this,arguments)}function Gl(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function Hl(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Gl(Object(i),!0).forEach(function(t){Kl(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Gl(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function Kl(e,t,i){var s;return(t="symbol"==typeof(s=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t||"default");if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"))?s:s+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function jl(e){return e&&e.map((e,t)=>g.createElement(e.tag,Hl({key:t},e.attr),jl(e.child)))}function Wl(e){return t=>g.createElement(ql,Vl({attr:Hl({},e.attr)},t),jl(e.child))}function ql(e){var t=t=>{var i,{attr:s,size:r,title:n}=e,a=$l(e,Bl),o=r||t.size||"1em";return t.className&&(i=t.className),e.className&&(i=(i?i+" ":"")+e.className),g.createElement("svg",Vl({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,s,a,{className:i,style:Hl(Hl({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),n&&g.createElement("title",null,n),e.children)};return void 0!==Ul?g.createElement(Ul.Consumer,null,e=>t(e)):t(Nl)}function Yl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M436 192H312c-13.3 0-24-10.7-24-24V44c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v84h84c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm-276-24V44c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v84H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24zm0 300V344c0-13.3-10.7-24-24-24H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-84h84c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12H312c-13.3 0-24 10.7-24 24v124c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function zl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M0 180V56c0-13.3 10.7-24 24-24h124c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12H64v84c0 6.6-5.4 12-12 12H12c-6.6 0-12-5.4-12-12zM288 44v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12V56c0-13.3-10.7-24-24-24H300c-6.6 0-12 5.4-12 12zm148 276h-40c-6.6 0-12 5.4-12 12v84h-84c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24V332c0-6.6-5.4-12-12-12zM160 468v-40c0-6.6-5.4-12-12-12H64v-84c0-6.6-5.4-12-12-12H12c-6.6 0-12 5.4-12 12v124c0 13.3 10.7 24 24 24h124c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function Xl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z"},child:[]}]})(e)}function Ql(e){return Wl({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z"},child:[]}]})(e)}function Jl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z"},child:[]}]})(e)}function Zl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 384 512"},child:[{tag:"path",attr:{d:"M215.03 72.04L126.06 161H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V89.02c0-21.47-25.96-31.98-40.97-16.98zm123.2 108.08c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 229.28 336 242.62 336 257c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.87z"},child:[]}]})(e)}function ed(e){return Wl({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zM461.64 256l45.64-45.64c6.3-6.3 6.3-16.52 0-22.82l-22.82-22.82c-6.3-6.3-16.52-6.3-22.82 0L416 210.36l-45.64-45.64c-6.3-6.3-16.52-6.3-22.82 0l-22.82 22.82c-6.3 6.3-6.3 16.52 0 22.82L370.36 256l-45.63 45.63c-6.3 6.3-6.3 16.52 0 22.82l22.82 22.82c6.3 6.3 16.52 6.3 22.82 0L416 301.64l45.64 45.64c6.3 6.3 16.52 6.3 22.82 0l22.82-22.82c6.3-6.3 6.3-16.52 0-22.82L461.64 256z"},child:[]}]})(e)}function td(e){return Wl({tag:"svg",attr:{viewBox:"0 0 576 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zm233.32-51.08c-11.17-7.33-26.18-4.24-33.51 6.95-7.34 11.17-4.22 26.18 6.95 33.51 66.27 43.49 105.82 116.6 105.82 195.58 0 78.98-39.55 152.09-105.82 195.58-11.17 7.32-14.29 22.34-6.95 33.5 7.04 10.71 21.93 14.56 33.51 6.95C528.27 439.58 576 351.33 576 256S528.27 72.43 448.35 19.97zM480 256c0-63.53-32.06-121.94-85.77-156.24-11.19-7.14-26.03-3.82-33.12 7.46s-3.78 26.21 7.41 33.36C408.27 165.97 432 209.11 432 256s-23.73 90.03-63.48 115.42c-11.19 7.14-14.5 22.07-7.41 33.36 6.51 10.36 21.12 15.14 33.12 7.46C447.94 377.94 480 319.54 480 256zm-141.77-76.87c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 228.28 336 241.63 336 256c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.86z"},child:[]}]})(e)}const id=["src","allowNativeHls","licenseKey","lowLatencyMode","driftToleranceMs","vastMode"],sd=g.memo(e=>{const{src:t,autoplay:i,muted:s,lowLatencyMode:r,allowNativeHls:n,driftToleranceMs:a,immediateManifestAds:o,debugAdTiming:l,showCustomControls:d,onVolumeToggle:h,onFullscreenToggle:c,onControlClick:m,onReady:p,wrapperClassName:y,wrapperStyle:v,className:T,style:E,controls:S,playsInline:A,preload:b,poster:L,children:R,licenseKey:I,vastMode:k,vastTagUrl:P,adPlayerType:w,minSegmentsBeforePlay:D,...x}=e,C=f.useRef(null),_=f.useRef(null),M=f.useRef(null),[O,F]=g.useState({showAds:!1,currentIndex:0,totalAds:0}),[N,U]=g.useState(!0),[B,$]=g.useState(!1),[V,G]=g.useState(!1),[H,K]=g.useState(!1),[j,W]=g.useState(0),[q,Y]=g.useState(0),[z,X]=g.useState(1),[Q,J]=g.useState(1),[Z,ee]=g.useState(!1),[te,ie]=g.useState(!1),[se,re]=g.useState(!0),[ne,ae]=g.useState(!1),[oe,le]=g.useState(!1),[de,he]=g.useState(!1),[ce,ue]=g.useState("undefined"!=typeof window?window.innerWidth:1920),[fe,ge]=g.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),me=ce<480?.7:ce<768?.8:ce<1024?.9:1,pe=e=>{if(!isFinite(e))return"0:00:00";const t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=Math.floor(e%60);return`${t}:${i.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`},ye=e=>{if(_.current&&isFinite(e)){const t=Math.max(0,Math.min(1,e));_.current.setVolume(t)}},ve=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),Te=d&&(!ve||n),Ee=f.useMemo(()=>id.map(t=>`${t}:${e[t]}`).join("|"),[t,n,I,r,a,k]);return f.useEffect(()=>{if("undefined"==typeof window)return;const e=C.current;if(!e||!t)return;if(!I)return he(!0),re(!1),void console.warn("StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.");if(he(!1),l&&console.log("[StormcloudUI] Initializing player, isLoading=true"),_.current){try{_.current.destroy()}catch{}_.current=null}const u={src:t,videoElement:e};void 0!==i&&(u.autoplay=i),void 0!==s&&(u.muted=s),void 0!==r&&(u.lowLatencyMode=r),void 0!==n&&(u.allowNativeHls=n),void 0!==a&&(u.driftToleranceMs=a),void 0!==o&&(u.immediateManifestAds=o),void 0!==l&&(u.debugAdTiming=l),void 0!==d&&(u.showCustomControls=d),void 0!==h&&(u.onVolumeToggle=h),void 0!==c&&(u.onFullscreenToggle=c),void 0!==m&&(u.onControlClick=m),void 0!==I&&(u.licenseKey=I),void 0!==k&&(u.vastMode=k),void 0!==P&&(u.vastTagUrl=P),void 0!==w&&(u.adPlayerType=w),void 0!==D&&(u.minSegmentsBeforePlay=D);const f=new Fl(u);return _.current=f,f.load().then(()=>{const e=f.shouldShowNativeControls();U(e),l&&console.log("[StormcloudUI] Player loaded successfully, waiting for video ready"),null==p||p(f)}).catch(e=>{console.error("StormcloudVideoPlayer: Failed to load player:",e),re(!1),null==p||p(f)}),()=>{try{f.destroy()}catch{}_.current=null}},[Ee]),f.useEffect(()=>{if(_.current)try{void 0!==i&&_.current.videoElement&&(_.current.videoElement.autoplay=i),void 0===s||_.current.isShowingAds()||_.current.setMuted(s)}catch(e){console.warn("Failed to update player properties:",e)}},[i,s]),f.useEffect(()=>{if(!_.current)return;const e=setInterval(()=>{if(_.current){const e=_.current.isShowingAds(),t=_.current.getCurrentAdIndex(),i=_.current.getTotalAdsInBreak();F(s=>s.showAds!==e||s.currentIndex!==t||s.totalAds!==i?{showAds:e,currentIndex:t,totalAds:i}:s)}},100);return()=>clearInterval(e)},[]),f.useEffect(()=>{if("undefined"==typeof window||!_.current)return;const e=()=>{_.current&&C.current&&"function"==typeof _.current.resize&&_.current.resize(),ue(window.innerWidth),ge(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),f.useEffect(()=>{if(!_.current||!C.current)return;const e=setInterval(()=>{var e;if(_.current&&C.current){$(_.current.isMuted()),K(!C.current.paused);const e=C.current.currentTime;W(isFinite(e)?e:0);const t=C.current.duration;Y(isFinite(t)?t:0);const i=C.current.volume;X(isFinite(i)?Math.max(0,Math.min(1,i)):1);const s=C.current.playbackRate;J(isFinite(s)&&s>0?s:1)}G(document.fullscreenElement===(null===(e=C.current)||void 0===e?void 0:e.parentElement))},200),t=()=>{var e;G(document.fullscreenElement===(null===(e=C.current)||void 0===e?void 0:e.parentElement))};return document.addEventListener("fullscreenchange",t),()=>{clearInterval(e),document.removeEventListener("fullscreenchange",t)}},[]),f.useEffect(()=>{if(!C.current)return;const e=()=>{var e;if(C.current){C.current.offsetHeight}l&&console.log("[StormcloudUI] Video event: loadedmetadata, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState)},t=()=>{var e;l&&console.log("[StormcloudUI] Video event: loadeddata, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState)},i=()=>{var e;l&&console.log("[StormcloudUI] Video event: loadstart, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState)},s=()=>{var e;re(!1),M.current&&(clearTimeout(M.current),M.current=null),ae(!1),l&&console.log("[StormcloudUI] Video event: canplay, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},r=()=>{var e;re(!1),M.current&&(clearTimeout(M.current),M.current=null),ae(!1),l&&console.log("[StormcloudUI] Video event: canplaythrough, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},n=()=>{var e;M.current&&clearTimeout(M.current),M.current=window.setTimeout(()=>{var e;ae(!0),l&&console.log("[StormcloudUI] Video buffering detected (after 300ms delay), readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- showing spinner, isBuffering=true")},300),l&&console.log("[StormcloudUI] Video event: waiting, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- buffering delay started (300ms)")},a=()=>{var e;re(!1),M.current&&(clearTimeout(M.current),M.current=null),ae(!1),le(!1),l&&console.log("[StormcloudUI] Video event: playing, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- playback started, isLoading=false, isBuffering=false")},o=()=>{_.current&&!_.current.isShowingAds()?le(!0):le(!1)},d=()=>{le(!0)},h=C.current;return h.addEventListener("loadstart",i),h.addEventListener("loadedmetadata",e),h.addEventListener("loadeddata",t),h.addEventListener("canplay",s),h.addEventListener("canplaythrough",r),h.addEventListener("waiting",n),h.addEventListener("playing",a),h.addEventListener("pause",o),h.addEventListener("ended",d),h.paused&&le(!0),()=>{M.current&&(clearTimeout(M.current),M.current=null),h.removeEventListener("loadstart",i),h.removeEventListener("loadedmetadata",e),h.removeEventListener("loadeddata",t),h.removeEventListener("canplay",s),h.removeEventListener("canplaythrough",r),h.removeEventListener("waiting",n),h.removeEventListener("playing",a),h.removeEventListener("pause",o),h.removeEventListener("ended",d)}},[l]),u.jsxs(u.Fragment,{children:[u.jsx("style",{children:"\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n \n .stormcloud-video-wrapper:fullscreen {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n .stormcloud-video-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n *:fullscreen {\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n }\n "}),u.jsxs("div",{className:`stormcloud-video-wrapper ${y||""}`,style:{display:"flex",alignItems:"center",justifyContent:"center",position:V?"fixed":"relative",top:V?0:void 0,left:V?0:void 0,overflow:"hidden",width:V?"100vw":"100%",height:V?"100vh":"auto",minHeight:V?"100vh":"auto",maxWidth:V?"100vw":"100%",maxHeight:V?"100vh":"none",zIndex:V?999999:void 0,backgroundColor:V?"#000":void 0,borderRadius:V?0:void 0,boxShadow:V?"none":void 0,...v},children:[u.jsx("video",{ref:C,className:T,style:{display:"block",width:"100%",height:V?"100%":"auto",maxWidth:"100%",maxHeight:V?"100%":"none",objectFit:V?"cover":"contain",backgroundColor:"#000",aspectRatio:V?"unset":void 0,...E},controls:N&&S&&!d,playsInline:A,preload:b,poster:L,...x,children:R}),(se||ne)&&u.jsx(Jl,{size:42,color:"white",style:{position:"absolute",top:"calc(50% - 21px)",left:"calc(50% - 21px)",zIndex:20,animation:"spin 1s linear infinite",filter:"drop-shadow(0 3px 6px rgba(0, 0, 0, 0.8))"}}),de&&u.jsxs("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:25,background:"linear-gradient(135deg, rgba(220, 38, 38, 0.95) 0%, rgba(185, 28, 28, 0.9) 100%)",color:"white",padding:"24px 32px",borderRadius:"16px",backdropFilter:"blur(20px)",border:"2px solid rgba(255, 255, 255, 0.2)",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.6), inset 0 2px 0 rgba(255, 255, 255, 0.2)",textAlign:"center",maxWidth:"400px",margin:"0 16px"},children:[u.jsx("div",{style:{fontSize:"20px",fontWeight:"bold",marginBottom:"12px",color:"#ffffff",textShadow:"0 2px 4px rgba(0, 0, 0, 0.5)"},children:"License Key Required"}),u.jsxs("div",{style:{fontSize:"14px",lineHeight:"1.5",color:"rgba(255, 255, 255, 0.9)",textShadow:"0 1px 2px rgba(0, 0, 0, 0.3)"},children:["Please provide a valid license key to use the Stormcloud Video Player.",u.jsx("br",{}),"Contact your administrator for licensing information."]})]}),oe&&!se&&!ne&&!de&&!O.showAds&&u.jsx("div",{onClick:()=>{var e;if(C.current&&C.current.paused){C.current.src||C.current.currentSrc&&""!==C.current.currentSrc||C.current.readyState>=1?(null===(e=C.current.play())||void 0===e||e.catch(e=>{console.error("[StormcloudVideoPlayer] Failed to play:",e)}),le(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source")}},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",borderRadius:"50%",width:"100px",height:"100px",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",border:"3px solid rgba(255, 255, 255, 0.8)",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"},onMouseEnter:e=>{const t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.95) 0%, rgba(40, 40, 40, 0.9) 100%)",t.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.borderColor="rgba(255, 255, 255, 0.9)"},onMouseLeave:e=>{const t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",t.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",t.style.borderColor="rgba(255, 255, 255, 0.8)"},title:"Play",children:u.jsx(Ql,{size:36,color:"white",style:{marginLeft:"6px",filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))"}})}),Te&&!de?u.jsx(u.Fragment,{children:u.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.8) 100%)",padding:"20px 16px 16px",zIndex:10},children:[u.jsxs("div",{style:{width:"100%",height:"8px",background:"linear-gradient(90deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%)",borderRadius:"8px",marginBottom:"16px",cursor:"pointer",position:"relative",backdropFilter:"blur(5px)",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"inset 0 2px 4px rgba(0, 0, 0, 0.2)"},onClick:e=>{if(C.current&&q>0&&isFinite(q)){const t=e.currentTarget.getBoundingClientRect(),i=e.clientX-t.left,s=Math.max(0,Math.min(1,i/t.width))*q;isFinite(s)&&s>=0&&s<=q&&(C.current.currentTime=s)}},children:[u.jsx("div",{style:{height:"100%",background:"linear-gradient(90deg, rgba(139, 92, 246, 0.9) 0%, rgba(59, 130, 246, 0.8) 50%, rgba(34, 197, 94, 0.9) 100%)",borderRadius:"8px",width:(q>0?j/q*100:0)+"%",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 2px 8px rgba(139, 92, 246, 0.4)"}}),u.jsx("div",{style:{position:"absolute",top:"-6px",right:(q>0?100-j/q*100:100)+"%",width:"20px",height:"20px",background:"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(240, 240, 240, 0.9) 100%)",borderRadius:"50%",border:"3px solid rgba(139, 92, 246, 0.8)",boxShadow:"0 4px 16px rgba(139, 92, 246, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.8)",transform:"translateX(50%)",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)"}})]}),u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",color:"white",flexWrap:ce<768?"wrap":"nowrap",gap:8*me+"px"},children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12*me+"px",flexWrap:ce<480?"wrap":"nowrap"},children:[u.jsx("button",{onClick:()=>{var e;if(C.current)if(C.current.paused){C.current.src||C.current.currentSrc&&""!==C.current.currentSrc||C.current.readyState>=1?(null===(e=C.current.play())||void 0===e||e.catch(e=>{console.error("[StormcloudVideoPlayer] Failed to play:",e)}),le(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source")}else C.current.pause(),le(!0)},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",backdropFilter:"blur(12px)",border:2*me+"px solid rgba(255, 255, 255, 0.3)",color:"#ffffff",cursor:"pointer",padding:10*me+"px",borderRadius:16*me+"px",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)",minWidth:48*me+"px",minHeight:48*me+"px"},onMouseEnter:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)",t.style.boxShadow="0 12px 48px rgba(0, 0, 0, 0.6), 0 6px 24px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.4)"},onMouseLeave:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",t.style.boxShadow="0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)"},title:H?"Pause":"Play",children:H?u.jsx(Xl,{size:Math.max(16,20*me),style:{filter:"drop-shadow(0 0 0 transparent)"}}):u.jsx(Ql,{size:Math.max(16,20*me),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),u.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1),children:[u.jsx("button",{onClick:()=>{_.current&&_.current.toggleMute(),h&&h()},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:2*me+"px solid rgba(255, 255, 255, 0.3)",color:"#ffffff",cursor:"pointer",padding:8*me+"px",borderRadius:16*me+"px",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:44*me+"px",minHeight:44*me+"px"},onMouseEnter:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:B?"Unmute":"Mute",children:B||0===z?u.jsx(ed,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}}):z<.5?u.jsx(Zl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}}):u.jsx(td,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),Z&&u.jsxs(u.Fragment,{children:[u.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1)}),u.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.88) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(15px)",padding:"10px 14px",borderRadius:"14px",border:"1px solid rgba(255, 255, 255, 0.15)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:e=>{ee(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.6), 0 6px 16px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 0 24px rgba(59, 130, 246, 0.3)",e.currentTarget.style.borderColor="rgba(59, 130, 246, 0.4)"},onMouseLeave:e=>{ee(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.15)"},children:u.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseEnter:e=>{},onMouseLeave:e=>{},onMouseDown:e=>{e.preventDefault();const t=e.currentTarget,i=e=>{if(!t)return;const i=t.getBoundingClientRect(),s=e.clientY-i.top,r=1-Math.max(0,Math.min(1,s/i.height));ye(r)},s=()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",s)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",s);const r=t.getBoundingClientRect(),n=e.clientY-r.top,a=1-Math.max(0,Math.min(1,n/r.height));ye(a)},onClick:e=>{e.stopPropagation();const t=e.currentTarget.getBoundingClientRect(),i=e.clientY-t.top,s=1-Math.max(0,Math.min(1,i/t.height));ye(s)},children:[u.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.15) 100%)",borderRadius:"4px",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.2)"}}),u.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:100*(B?0:z)+"%",background:"linear-gradient(180deg, rgba(96, 165, 250, 1) 0%, rgba(59, 130, 246, 0.95) 50%, rgba(37, 99, 235, 0.9) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 8px rgba(59, 130, 246, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.3)"}}),u.jsx("div",{style:{position:"absolute",bottom:`calc(${100*(B?0:z)}% - 7px)`,left:"50%",transform:"translateX(-50%)",width:"14px",height:"14px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:e=>{e.currentTarget.style.boxShadow="0 3px 10px rgba(0, 0, 0, 0.4), 0 0 0 3px rgba(59, 130, 246, 0.5), 0 0 20px rgba(59, 130, 246, 0.6)",e.currentTarget.style.cursor="grab"},onMouseLeave:e=>{e.currentTarget.style.boxShadow="0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)"},onMouseDown:e=>{e.currentTarget.style.cursor="grabbing"},onMouseUp:e=>{e.currentTarget.style.cursor="grab"}})]})})]})]}),u.jsxs("div",{style:{fontSize:14*me+"px",fontFamily:"monospace",color:"rgba(255, 255, 255, 0.9)",display:ce<480?"none":"block"},children:[pe(j)," / ",pe(q)]})]}),u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12*me+"px"},children:[u.jsxs("div",{style:{position:"relative",display:ce<600?"none":"block"},children:[u.jsxs("button",{onClick:()=>ie(!te),style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:2*me+"px solid rgba(255, 255, 255, 0.3)",color:"#ffffff",cursor:"pointer",padding:`${8*me}px ${14*me}px`,borderRadius:14*me+"px",fontSize:14*me+"px",fontFamily:"monospace",fontWeight:"700",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:56*me+"px",minHeight:40*me+"px"},onMouseEnter:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 32px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:"Playback Speed",children:[Q,"x"]}),te&&u.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,marginBottom:"12px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.95) 100%)",backdropFilter:"blur(20px)",borderRadius:"12px",border:"1px solid rgba(255, 255, 255, 0.1)",overflow:"hidden",minWidth:"90px",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.1)"},children:[.25,.5,.75,1,1.25,1.5,1.75,2].map(e=>u.jsxs("button",{onClick:()=>{return t=e,C.current&&isFinite(t)&&t>0&&(C.current.playbackRate=t),void ie(!1);var t},style:{display:"block",width:"100%",padding:"10px 16px",background:Q===e?"linear-gradient(135deg, rgba(99, 102, 241, 0.8) 0%, rgba(139, 92, 246, 0.6) 100%)":"transparent",border:"none",color:"white",cursor:"pointer",fontSize:"13px",fontFamily:"monospace",fontWeight:"600",textAlign:"center",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",borderBottom:2!==e?"1px solid rgba(255, 255, 255, 0.05)":"none"},onMouseEnter:t=>{Q!==e&&(t.target.style.background="linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%)")},onMouseLeave:t=>{Q!==e&&(t.target.style.background="transparent")},children:[e,"x"]},e))})]}),u.jsx("button",{onClick:()=>{c?c():_.current&&_.current.toggleFullscreen().catch(e=>{console.error("Fullscreen error:",e)})},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:2*me+"px solid rgba(255, 255, 255, 0.3)",color:"#ffffff",cursor:"pointer",padding:8*me+"px",borderRadius:16*me+"px",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:44*me+"px",minHeight:44*me+"px"},onMouseEnter:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:V?"Exit Fullscreen":"Enter Fullscreen",children:V?u.jsx(Yl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}}):u.jsx(zl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}})})]})]})]})}):d&&!de&&u.jsxs("div",{style:{position:"absolute",bottom:10*me+"px",right:10*me+"px",transform:"none",display:"flex",flexDirection:fe?"column":"row",gap:10*me+"px",zIndex:10},children:[u.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1),children:[u.jsx("button",{onClick:()=>{_.current&&_.current.toggleMute(),h&&h()},onMouseEnter:e=>{const t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:e=>{const t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:18*me+"px",padding:8*me+"px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:46*me+"px",minHeight:46*me+"px"},title:B?"Unmute":"Mute",children:B||0===z?u.jsx(ed,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):z<.5?u.jsx(Zl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):u.jsx(td,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})}),Z&&u.jsxs(u.Fragment,{children:[u.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1)}),u.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.96) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(20px)",padding:"10px 14px",borderRadius:"14px",border:"2px solid rgba(255, 255, 255, 0.7)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:e=>{ee(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), 0 6px 16px rgba(0, 0, 0, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 0 24px rgba(96, 165, 250, 0.4)",e.currentTarget.style.borderColor="rgba(96, 165, 250, 0.8)"},onMouseLeave:e=>{ee(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.7)"},children:u.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseDown:e=>{e.preventDefault();const t=e.currentTarget,i=e=>{if(!t)return;const i=t.getBoundingClientRect(),s=e.clientY-i.top,r=1-Math.max(0,Math.min(1,s/i.height));ye(r)},s=()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",s)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",s);const r=t.getBoundingClientRect(),n=e.clientY-r.top,a=1-Math.max(0,Math.min(1,n/r.height));ye(a)},onClick:e=>{e.stopPropagation();const t=e.currentTarget.getBoundingClientRect(),i=e.clientY-t.top,s=1-Math.max(0,Math.min(1,i/t.height));ye(s)},children:[u.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.85) 0%, rgba(255, 255, 255, 0.5) 100%)",borderRadius:"4px",border:"1px solid rgba(255, 255, 255, 0.4)",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.3)"}}),u.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:100*(B?0:z)+"%",background:"linear-gradient(180deg, rgba(125, 211, 252, 1) 0%, rgba(96, 165, 250, 0.98) 50%, rgba(59, 130, 246, 0.95) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 12px rgba(96, 165, 250, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.4)"}}),u.jsx("div",{style:{position:"absolute",bottom:`calc(${100*(B?0:z)}% - 8px)`,left:"50%",transform:"translateX(-50%)",width:"16px",height:"16px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",border:"2px solid rgba(96, 165, 250, 0.9)",boxShadow:"0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:e=>{e.currentTarget.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.6), 0 0 0 3px rgba(96, 165, 250, 0.6), 0 0 24px rgba(96, 165, 250, 0.7)",e.currentTarget.style.cursor="grab"},onMouseLeave:e=>{e.currentTarget.style.boxShadow="0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)"},onMouseDown:e=>{e.currentTarget.style.cursor="grabbing"},onMouseUp:e=>{e.currentTarget.style.cursor="grab"}})]})})]})]}),u.jsx("button",{onClick:()=>{c?c():_.current&&_.current.toggleFullscreen().catch(e=>{console.error("Fullscreen error:",e)})},onMouseEnter:e=>{const t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:e=>{const t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:18*me+"px",padding:8*me+"px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:46*me+"px",minHeight:46*me+"px"},title:V?"Exit Fullscreen":"Enter Fullscreen",children:V?u.jsx(Yl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):u.jsx(zl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})})]}),m&&u.jsx("div",{onClick:m,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},(e,t)=>{for(const i of id)if(e[i]!==t[i])return!1;const i=["autoplay","muted","controls","showCustomControls","className","style","wrapperClassName","wrapperStyle","playsInline","preload","poster","children"];for(const s of i)if(e[s]!==t[s])return!1;const s=["onReady","onVolumeToggle","onFullscreenToggle","onControlClick"];for(const i of s)if(e[i]!==t[i])return!1;return!0}),rd=()=>{},nd={playing:!1,loop:!1,controls:!0,volume:1,muted:!1,playbackRate:1,width:"100%",height:"auto",style:{},progressInterval:1e3,playsInline:!1,autoplay:!1,preload:"metadata",poster:"",className:"",wrapperClassName:"",wrapperStyle:{},allowNativeHls:!1,lowLatencyMode:!1,driftToleranceMs:1e3,immediateManifestAds:!0,debugAdTiming:!1,showCustomControls:!1,licenseKey:"",adFailsafeTimeoutMs:1e4,minSegmentsBeforePlay:2,onStart:rd,onPlay:rd,onPause:rd,onBuffer:rd,onBufferEnd:rd,onEnded:rd,onError:rd,onDuration:rd,onSeek:rd,onProgress:rd,onVolumeToggle:rd,onFullscreenToggle:rd,onControlClick:rd},ad=f.lazy,od=(e,t)=>{const i={...e};return t.forEach(e=>{delete i[e]}),i},ld=e=>"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream,dd=(e,...t)=>{if(!t.length)return e;const i=t.shift();if(hd(e)&&hd(i))for(const t in i)hd(i[t])?(e[t]||Object.assign(e,{[t]:{}}),dd(e[t],i[t])):Object.assign(e,{[t]:i[t]});return dd(e,...t)},hd=e=>e&&"object"==typeof e&&!Array.isArray(e),cd="undefined"!=typeof window&&window.document,ud="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,fd=cd&&/iPad|iPhone|iPod/.test(navigator.userAgent),gd=cd&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),md=/\.(m3u8)($|\?)/i,pd=/\/hls\//i,yd=/\.(mpd)($|\?)/i,vd=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,Td=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,Ed={hls:e=>!(!e||"string"!=typeof e)&&(md.test(e)||pd.test(e)),dash:e=>!(!e||"string"!=typeof e)&&yd.test(e),video:e=>!(!e||"string"!=typeof e)&&vd.test(e),audio:e=>!(!e||"string"!=typeof e)&&Td.test(e),file:e=>!(!e||"string"!=typeof e)&&(vd.test(e)||Td.test(e))};class Sd extends f.Component{constructor(){super(...arguments),this.player=null,this.mounted=!1,this.load=async()=>{var e,t,i,s,r,n;if(this.props.videoElement&&this.props.src)try{this.player&&(this.player.destroy(),this.player=null);const r={src:this.props.src,videoElement:this.props.videoElement};void 0!==this.props.autoplay&&(r.autoplay=this.props.autoplay),void 0!==this.props.muted&&(r.muted=this.props.muted),void 0!==this.props.lowLatencyMode&&(r.lowLatencyMode=this.props.lowLatencyMode),void 0!==this.props.allowNativeHls&&(r.allowNativeHls=this.props.allowNativeHls),void 0!==this.props.driftToleranceMs&&(r.driftToleranceMs=this.props.driftToleranceMs),void 0!==this.props.immediateManifestAds&&(r.immediateManifestAds=this.props.immediateManifestAds),void 0!==this.props.debugAdTiming&&(r.debugAdTiming=this.props.debugAdTiming),void 0!==this.props.showCustomControls&&(r.showCustomControls=this.props.showCustomControls),void 0!==this.props.onVolumeToggle&&(r.onVolumeToggle=this.props.onVolumeToggle),void 0!==this.props.onFullscreenToggle&&(r.onFullscreenToggle=this.props.onFullscreenToggle),void 0!==this.props.onControlClick&&(r.onControlClick=this.props.onControlClick),void 0!==this.props.licenseKey&&(r.licenseKey=this.props.licenseKey),void 0!==this.props.adFailsafeTimeoutMs&&(r.adFailsafeTimeoutMs=this.props.adFailsafeTimeoutMs),void 0!==this.props.minSegmentsBeforePlay&&(r.minSegmentsBeforePlay=this.props.minSegmentsBeforePlay),this.player=new Fl(r),null===(t=(e=this.props).onMount)||void 0===t||t.call(e,this),await this.player.load(),this.mounted&&(null===(s=(i=this.props).onReady)||void 0===s||s.call(i))}catch(e){this.mounted&&(null===(n=(r=this.props).onError)||void 0===n||n.call(r,e))}},this.play=()=>{var e,t,i;if(this.props.videoElement){const s=this.props.videoElement;s.src||s.currentSrc&&""!==s.currentSrc||s.readyState>=1?(null===(e=s.play())||void 0===e||e.catch(e=>{var t,i;console.error("[HlsPlayer] Failed to play:",e),null===(i=(t=this.props).onError)||void 0===i||i.call(t,e)}),null===(i=(t=this.props).onPlay)||void 0===i||i.call(t)):console.warn("[HlsPlayer] Cannot play: video has no valid source")}},this.pause=()=>{var e,t;this.props.videoElement&&(this.props.videoElement.pause(),null===(t=(e=this.props).onPause)||void 0===t||t.call(e))},this.stop=()=>{this.pause(),this.props.videoElement&&(this.props.videoElement.currentTime=0)},this.seekTo=(e,t)=>{this.props.videoElement&&(this.props.videoElement.currentTime=e,t||this.pause())},this.setVolume=e=>{this.props.videoElement&&(this.props.videoElement.volume=Math.max(0,Math.min(1,e)))},this.mute=()=>{this.props.videoElement&&(this.props.videoElement.muted=!0)},this.unmute=()=>{this.props.videoElement&&(this.props.videoElement.muted=!1)},this.setPlaybackRate=e=>{this.props.videoElement&&e>0&&(this.props.videoElement.playbackRate=e)},this.getDuration=()=>this.props.videoElement&&isFinite(this.props.videoElement.duration)?this.props.videoElement.duration:null,this.getCurrentTime=()=>this.props.videoElement&&isFinite(this.props.videoElement.currentTime)?this.props.videoElement.currentTime:null,this.getSecondsLoaded=()=>this.props.videoElement&&this.props.videoElement.buffered.length>0?this.props.videoElement.buffered.end(this.props.videoElement.buffered.length-1):null,this.getInternalPlayer=(e="player")=>"player"===e?this.player:"video"===e?this.props.videoElement:"hls"===e&&this.player?this.player.hls:null}componentDidMount(){this.mounted=!0,this.load()}componentWillUnmount(){this.mounted=!1,this.player&&(this.player.destroy(),this.player=null)}componentDidUpdate(e){e.src!==this.props.src&&this.load()}render(){return null}}Sd.displayName="HlsPlayer",Sd.canPlay=Ed.hls;class Ad extends f.Component{constructor(){super(...arguments),this.mounted=!1,this.ready=!1,this.load=()=>{var e,t;if(!this.props.videoElement||!this.props.src)return;const i=this.props.videoElement,s=()=>{var e,t;this.mounted&&!this.ready&&(this.ready=!0,null===(t=(e=this.props).onReady)||void 0===t||t.call(e))},r=()=>{var e,t;this.mounted&&(null===(t=(e=this.props).onPlay)||void 0===t||t.call(e))},n=()=>{var e,t;this.mounted&&(null===(t=(e=this.props).onPause)||void 0===t||t.call(e))},a=()=>{var e,t;this.mounted&&(null===(t=(e=this.props).onEnded)||void 0===t||t.call(e))},o=e=>{var t,i;this.mounted&&(null===(i=(t=this.props).onError)||void 0===i||i.call(t,e))},l=()=>{var e,t;this.mounted&&(null===(t=(e=this.props).onLoaded)||void 0===t||t.call(e))};return i.addEventListener("loadedmetadata",s),i.addEventListener("play",r),i.addEventListener("pause",n),i.addEventListener("ended",a),i.addEventListener("error",o),i.addEventListener("loadeddata",l),i.src=this.props.src,void 0!==this.props.autoplay&&(i.autoplay=this.props.autoplay),void 0!==this.props.muted&&(i.muted=this.props.muted),void 0!==this.props.loop&&(i.loop=this.props.loop),void 0!==this.props.controls&&(i.controls=this.props.controls),void 0!==this.props.playsInline&&(i.playsInline=this.props.playsInline),void 0!==this.props.preload&&(i.preload=this.props.preload),void 0!==this.props.poster&&(i.poster=this.props.poster),null===(t=(e=this.props).onMount)||void 0===t||t.call(e,this),()=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("play",r),i.removeEventListener("pause",n),i.removeEventListener("ended",a),i.removeEventListener("error",o),i.removeEventListener("loadeddata",l)}},this.play=()=>{var e;if(this.props.videoElement){const t=this.props.videoElement;t.src||t.currentSrc&&""!==t.currentSrc||t.readyState>=1?null===(e=t.play())||void 0===e||e.catch(e=>{var t,i;console.error("[FilePlayer] Failed to play:",e),null===(i=(t=this.props).onError)||void 0===i||i.call(t,e)}):console.warn("[FilePlayer] Cannot play: video has no valid source")}},this.pause=()=>{this.props.videoElement&&this.props.videoElement.pause()},this.stop=()=>{this.pause(),this.props.videoElement&&(this.props.videoElement.currentTime=0)},this.seekTo=(e,t)=>{this.props.videoElement&&(this.props.videoElement.currentTime=e,t||this.pause())},this.setVolume=e=>{this.props.videoElement&&(this.props.videoElement.volume=Math.max(0,Math.min(1,e)))},this.mute=()=>{this.props.videoElement&&(this.props.videoElement.muted=!0)},this.unmute=()=>{this.props.videoElement&&(this.props.videoElement.muted=!1)},this.setPlaybackRate=e=>{this.props.videoElement&&e>0&&(this.props.videoElement.playbackRate=e)},this.setLoop=e=>{this.props.videoElement&&(this.props.videoElement.loop=e)},this.getDuration=()=>this.props.videoElement&&isFinite(this.props.videoElement.duration)?this.props.videoElement.duration:null,this.getCurrentTime=()=>this.props.videoElement&&isFinite(this.props.videoElement.currentTime)?this.props.videoElement.currentTime:null,this.getSecondsLoaded=()=>this.props.videoElement&&this.props.videoElement.buffered.length>0?this.props.videoElement.buffered.end(this.props.videoElement.buffered.length-1):null,this.getInternalPlayer=(e="player")=>"video"===e?this.props.videoElement:null,this.enablePIP=async()=>{if(this.props.videoElement&&"requestPictureInPicture"in this.props.videoElement)try{await this.props.videoElement.requestPictureInPicture()}catch(e){console.warn("Picture-in-Picture failed:",e)}},this.disablePIP=async()=>{if(document.pictureInPictureElement)try{await document.exitPictureInPicture()}catch(e){console.warn("Exit Picture-in-Picture failed:",e)}}}componentDidMount(){this.mounted=!0,this.load()}componentWillUnmount(){this.mounted=!1}componentDidUpdate(e){e.src!==this.props.src&&this.load()}render(){return null}}Ad.displayName="FilePlayer",Ad.canPlay=Ed.file;const bd=[{key:"hls",name:"HLS Player",canPlay:Ed.hls,lazyPlayer:ad(()=>Promise.resolve({default:Sd}))},{key:"file",name:"File Player",canPlay:Ed.file,canEnablePIP:e=>Ed.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode),lazyPlayer:ad(()=>Promise.resolve({default:Ad}))}];class Ld extends f.Component{constructor(){super(...arguments),this.mounted=!1,this.isReady=!1,this.isPlaying=!1,this.isLoading=!0,this.loadOnReady=null,this.startOnPlay=!0,this.seekOnPlay=null,this.onDurationCalled=!1,this.handlePlayerMount=e=>{this.player||(this.player=e,this.player.load(this.props.src)),this.progress()},this.getInternalPlayer=e=>this.player?this.player.getInternalPlayer(e):null,this.progress=()=>{var e,t;if(this.props.src&&this.player&&this.isReady){const i=this.getCurrentTime()||0,s=this.getSecondsLoaded(),r=this.getDuration();if(r){const n={playedSeconds:i,played:i/r,loaded:0,loadedSeconds:0};null!==s&&(n.loadedSeconds=s,n.loaded=s/r),n.playedSeconds===this.prevPlayed&&n.loadedSeconds===this.prevLoaded||null===(t=(e=this.props).onProgress)||void 0===t||t.call(e,n),this.prevPlayed=n.playedSeconds,this.prevLoaded=n.loadedSeconds}}this.progressTimeout=window.setTimeout(this.progress,this.props.progressInterval||1e3)},this.handleReady=()=>{if(!this.mounted)return;this.isReady=!0,this.isLoading=!1;const{onReady:e,playing:t,volume:i,muted:s}=this.props;e(),s||null===i||this.player.setVolume(i),this.loadOnReady?(this.player.load(this.loadOnReady,!0),this.loadOnReady=null):t&&this.player.play(),this.handleDurationCheck()},this.handlePlay=()=>{this.isPlaying=!0,this.isLoading=!1;const{onStart:e,onPlay:t,playbackRate:i}=this.props;this.startOnPlay&&(this.player.setPlaybackRate&&1!==i&&this.player.setPlaybackRate(i),null==e||e(),this.startOnPlay=!1),null==t||t(),this.seekOnPlay&&(this.seekTo(this.seekOnPlay),this.seekOnPlay=null),this.handleDurationCheck()},this.handlePause=e=>{var t,i;this.isPlaying=!1,this.isLoading||null===(i=(t=this.props).onPause)||void 0===i||i.call(t,e)},this.handleEnded=()=>{const{activePlayer:e,loop:t,onEnded:i}=this.props;e.loopOnEnded&&t&&this.seekTo(0),t||(this.isPlaying=!1,null==i||i())},this.handleError=(...e)=>{var t,i;this.isLoading=!1,null===(i=(t=this.props).onError)||void 0===i||i.call(t,e[0],e[1],e[2],e[3])},this.handleDurationCheck=()=>{var e,t;clearTimeout(this.durationCheckTimeout);const i=this.getDuration();i?this.onDurationCalled||(null===(t=(e=this.props).onDuration)||void 0===t||t.call(e,i),this.onDurationCalled=!0):this.durationCheckTimeout=window.setTimeout(this.handleDurationCheck,100)},this.handleLoaded=()=>{this.isLoading=!1}}componentDidMount(){this.mounted=!0}componentWillUnmount(){clearTimeout(this.progressTimeout),clearTimeout(this.durationCheckTimeout),this.mounted=!1}componentDidUpdate(e){if(!this.player)return;const{src:t,playing:i,volume:s,muted:r,playbackRate:n,loop:a,activePlayer:o}=this.props;if(e.src!==t){if(this.isLoading&&!o.forceLoad&&!ld(t))return console.warn(`StormcloudPlayer: the attempt to load ${t} is being deferred until the player has loaded`),void(this.loadOnReady=t||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(t,this.isReady)}e.playing||!i||this.isPlaying||this.player.play(),e.playing&&!i&&this.isPlaying&&this.player.pause(),e.volume!==s&&null!==s&&this.player.setVolume(s),e.muted!==r&&(r?this.player.mute():(this.player.unmute(),null!==s&&setTimeout(()=>this.player.setVolume(s)))),e.playbackRate!==n&&this.player.setPlaybackRate&&this.player.setPlaybackRate(n),e.loop!==a&&this.player.setLoop&&this.player.setLoop(a)}getDuration(){return this.isReady?this.player.getDuration():null}getCurrentTime(){return this.isReady?this.player.getCurrentTime():null}getSecondsLoaded(){return this.isReady?this.player.getSecondsLoaded():null}seekTo(e,t,i){if(!this.isReady)return void(0!==e&&(this.seekOnPlay=e,setTimeout(()=>{this.seekOnPlay=null},5e3)));if(t?"fraction"===t:e>0&&e<1){const t=this.player.getDuration();return t?void this.player.seekTo(t*e,i):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,i)}render(){const e=this.props.activePlayer;return e?g.createElement(e,{...this.props,onMount:this.handlePlayerMount,onReady:this.handleReady,onPlay:this.handlePlay,onPause:this.handlePause,onEnded:this.handleEnded,onLoaded:this.handleLoaded,onError:this.handleError}):null}}Ld.displayName="Player",Ld.defaultProps=nd;const Rd="undefined"!=typeof window&&window.document,Id="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,kd=Rd||Id?f.Suspense:()=>null,Pd=["src","playing","loop","controls","volume","muted","playbackRate","width","height","style","progressInterval","playsInline","autoplay","preload","poster","className","wrapperClassName","wrapperStyle","allowNativeHls","lowLatencyMode","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","licenseKey","adFailsafeTimeoutMs","minSegmentsBeforePlay","onReady","onStart","onPlay","onPause","onBuffer","onBufferEnd","onEnded","onError","onDuration","onSeek","onProgress","onVolumeToggle","onFullscreenToggle","onControlClick"],wd=[],Dd=(e,t)=>{var i;return i=class extends f.Component{constructor(){super(...arguments),this.state={showPreview:!1},this.references={wrapper:e=>{this.wrapper=e},player:e=>{this.player=e}},this.getActivePlayer=i=>{if(!i)return null;for(const t of[...wd,...e])if(t.canPlay(i))return t;return t||null},this.getAttributes=e=>od(this.props,Pd),this.handleReady=()=>{var e,t;null===(t=(e=this.props).onReady)||void 0===t||t.call(e,this)},this.seekTo=(e,t,i)=>{if(!this.player)return null;this.player.seekTo(e,t,i)},this.getCurrentTime=()=>this.player?this.player.getCurrentTime():null,this.getSecondsLoaded=()=>this.player?this.player.getSecondsLoaded():null,this.getDuration=()=>this.player?this.player.getDuration():null,this.getInternalPlayer=(e="player")=>this.player?this.player.getInternalPlayer(e):null,this.renderActivePlayer=e=>{if(!e)return null;const t=this.getActivePlayer(e);return t?g.createElement(Ld,{...this.props,key:t.key,ref:this.references.player,activePlayer:t.lazyPlayer||t,onReady:this.handleReady}):null}}render(){const{src:e,style:t,width:i,height:s,fallback:r,wrapper:n}=this.props,a=this.getAttributes(e),o="string"==typeof n?this.references.wrapper:void 0;return g.createElement(n,{ref:o,style:{...t,width:i,height:s},...a},g.createElement(kd,{fallback:r},this.renderActivePlayer(e)))}},i.displayName="StormcloudPlayer",i.defaultProps={...nd,fallback:null,wrapper:"div"},i.addCustomPlayer=e=>{wd.push(e)},i.removeCustomPlayers=()=>{wd.length=0},i.canPlay=t=>{for(const i of[...wd,...e])if(i.canPlay(t))return!0;return!1},i.canEnablePIP=t=>{for(const i of[...wd,...e])if(i.canEnablePIP&&i.canEnablePIP(t))return!0;return!1},i},xd=Dd(bd,bd[bd.length-1]);e.IS_BROWSER=cd,e.IS_GLOBAL=ud,e.IS_IOS=fd,e.IS_SAFARI=gd,e.SUPPORTS_DASH=()=>{if(!cd)return!1;const e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=()=>{if(!cd)return!1;const e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=xd,e.StormcloudVideoPlayer=Fl,e.StormcloudVideoPlayerComponent=sd,e.canPlay=Ed,e.createHlsAdPlayer=wl,e.createImaController=Pl,e.createStormcloudPlayer=Dd,e.default=sd,e.detectBrowser=Ll,e.getBrowserConfigOverrides=kl,e.getBrowserID=Cl,e.getClientInfo=xl,e.getRecommendedAdPlayer=function(){return Ll().recommendedAdPlayer},e.initializePolyfills=Ol,e.isMediaStream=ld,e.lazy=ad,e.logBrowserInfo=Il,e.merge=dd,e.omit=od,e.parseQuery=e=>{const t={},i=e.split("?")[1]||"";if(!i)return t;const s=e=>{e.split("&").forEach(e=>{const[i,s]=e.split("=");if(i)try{t[decodeURIComponent(i)]=s?decodeURIComponent(s.replace(/\+/g," ")):""}catch(e){t[i]=s||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(i).forEach((e,i)=>{t[i]=e}),t}catch(e){s(i)}else s(i);return t},e.players=bd,e.randomString=()=>Math.random().toString(36).substr(2,9),e.sendHeartbeat=Ml,e.sendInitialTracking=_l,e.supportsFeature=function(e){switch(e){case"ima":return Rl();case"urlsearchparams":return"undefined"!=typeof URLSearchParams;case"textencoder":return"undefined"!=typeof TextEncoder;case"promises":return"undefined"!=typeof Promise;case"fetch":return"undefined"!=typeof fetch;case"crypto":return"undefined"!=typeof crypto&&void 0!==crypto.subtle;default:return!1}},e.supportsGoogleIMA=Rl,e.supportsModernJS=function(){try{return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set&&void 0!==Array.from&&void 0!==Object.assign&&void 0!==Array.prototype.forEach&&void 0!==String.prototype.includes}catch(e){return!1}},e.supportsWebKitPresentationMode=()=>{if("undefined"==typeof window)return!1;return"webkitSupportsPresentationMode"in document.createElement("video")},Object.defineProperty(e,"__esModule",{value:!0})});
|
|
10
|
+
*/var c;s.exports;var u=(c||(c=1,s.exports=function(){if(i)return r;i=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function s(t,i,s){var r=null;if(void 0!==s&&(r=""+s),void 0!==i.key&&(r=""+i.key),"key"in i)for(var n in s={},i)"key"!==n&&(s[n]=i[n]);else s=i;return i=s.ref,{$$typeof:e,type:t,key:r,ref:void 0!==i?i:null,props:s}}return r.Fragment=t,r.jsx=s,r.jsxs=s,r}()),s.exports),f=h(),g=t(f);const m=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},p=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=y},y=Number.MAX_SAFE_INTEGER||9007199254740991;let v=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}({}),T=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.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_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.UNKNOWN="unknown",e}({}),E=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}({});var S="manifest",A="level",b="audioTrack",L="subtitleTrack",R="main",I="audio",k="subtitle";class P{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 w{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 P(e),this.fast_=new P(t),this.defaultTTFB_=s,this.ttfb_=new P(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new P(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new P(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new P(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,s=8*t/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}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(){}}function D(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function x(){return x=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},x.apply(null,arguments)}function C(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function _(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?C(Object(i),!0).forEach(function(t){D(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):C(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class M{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=O,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 O=function(){},F={trace:O,debug:O,log:O,warn:O,info:O,error:O};function U(){return x({},F)}function N(e,t,i){return t[e]?t[e].bind(t):function(e,t){const i=self.console[e];return i?i.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):O}(e,i)}const B=U();const $=B;function V(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function G(e,t){const i=Object.keys(e),s=Object.keys(t),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(e=>-1===s.indexOf(e))}function H(e,t=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(e);if(t){const e=i.indexOf("\0");return-1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}const i=e.length;let s,r,n,a="",o=0;for(;o<i;){if(s=e[o++],0===s&&t)return a;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((31&s)<<6|63&r);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((15&s)<<12|(63&r)<<6|63&n)}}return a}function K(e){let t="";for(let i=0;i<e.length;i++){let s=e[i].toString(16);s.length<2&&(s="0"+s),t+=s}return t}function j(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function W(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var q,Y={exports:{}};var z=(q||(q=1,function(e){var t,i,s,r,n;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var r=n.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return s.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):t;var o=n.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var h=o.path,c=h.substring(0,h.lastIndexOf("/")+1)+a.path;d.path=n.normalizePath(c)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=s.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(d)},parseURL:function(e){var i=t.exec(e);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(r,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=n}(Y)),Y.exports);class X{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}}}var Q="audio",J="video",Z="audiovideo";class ee{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const i=re(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let s;s=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Q]:null,[J]:null,[Z]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new X),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=z.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Q]=null,e[J]=null,e[Z]=null}}function te(e){return"initSegment"!==e.sn}class ie extends ee{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(m(e)&&m(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/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(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const i=this._decryptdata=t[e[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=m(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),i=e.length;if(i>1||1===i&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){m(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return te(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||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:n}}}class se extends ee{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function re(e,t){const i=Object.getPrototypeOf(e);if(i){const e=Object.getOwnPropertyDescriptor(i,t);return e||re(i,t)}}const ne=Math.pow(2,32)-1,ae=[].push,oe={video:1,audio:2,id3:3,text:4};function le(e){return String.fromCharCode.apply(null,e)}function de(e,t){const i=e[t]<<8|e[t+1];return i<0?65536+i:i}function he(e,t){const i=ue(e,t);return i<0?4294967296+i:i}function ce(e,t){let i=he(e,t);return i*=Math.pow(2,32),i+=he(e,t+4),i}function ue(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function fe(e,t){const i=[];if(!t.length)return i;const s=e.byteLength;for(let r=0;r<s;){const n=he(e,r),a=n>1?r+n:s;if(le(e.subarray(r+4,r+8))===t[0])if(1===t.length)i.push(e.subarray(r+8,a));else{const s=fe(e.subarray(r+8,a),t.slice(1));s.length&&ae.apply(i,s)}r=a}return i}function ge(e){const t=[],i=e[0];let s=8;const r=he(e,s);s+=4;let n=0,a=0;0===i?(n=he(e,s),a=he(e,s+4),s+=8):(n=ce(e,s),a=ce(e,s+8),s+=16),s+=2;let o=e.length+a;const l=de(e,s);s+=2;for(let i=0;i<l;i++){let i=s;const n=he(e,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return $.warn("SIDX has hierarchical references (not supported)"),null;const l=he(e,i);i+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:t}}function me(e){const t=[],i=fe(e,["moov","trak"]);for(let e=0;e<i.length;e++){const s=i[e],r=fe(s,["tkhd"])[0];if(r){let e=r[0];const i=he(r,0===e?12:20),n=fe(s,["mdia","mdhd"])[0];if(n){e=n[0];const r=he(n,0===e?12:20),a=fe(s,["mdia","hdlr"])[0];if(a){const e=le(a.subarray(8,12)),n={soun:Q,vide:J}[e],o=pe(fe(s,["mdia","minf","stbl","stsd"])[0]);n?(t[i]={timescale:r,type:n,stsd:o},t[n]=_({timescale:r,id:i},o)):t[i]={timescale:r,type:e,stsd:o}}}}}return fe(e,["moov","mvex","trex"]).forEach(e=>{const i=he(e,4),s=t[i];s&&(s.default={duration:he(e,12),flags:he(e,20)})}),t}function pe(e){const t=e.subarray(8),i=t.subarray(86),s=le(t.subarray(4,8));let r,n=s;const a="enca"===s||"encv"===s;if(a){const e=fe(t,[s])[0];fe(e.subarray("enca"===s?28:78),["sinf"]).forEach(e=>{const t=fe(e,["schm"])[0];if(t){const i=le(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=fe(e,["frma"])[0];t&&(n=le(t))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=fe(i,["avcC"])[0];e&&e.length>3&&(n+="."+Te(e[1])+Te(e[2])+Te(e[3]),r=ye("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const e=fe(t,[s])[0],i=fe(e.subarray(28),["esds"])[0];if(i&&i.length>7){let e=4;if(3!==i[e++])break;e=ve(i,e),e+=2;const t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=ve(i,e);const s=i[e++];if(64!==s)break;if(n+="."+Te(s),e+=12,5!==i[e++])break;e=ve(i,e);const r=i[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=fe(i,["hvcC"])[0];if(e&&e.length>12){const t=e[1],i=["","A","B","C"][t>>6],s=31&t,r=he(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+i+s,n+="."+function(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let e=l.length;e--;){const t=l[e];if(t||d){d="."+t.toString(16).toUpperCase()+d}}n+=d}r=ye("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ye(n,i)||n;break;case"vp09":{const e=fe(i,["vpcC"])[0];if(e&&e.length>6){const t=e[4],i=e[5],s=e[6]>>4&15;n+="."+Ee(t)+"."+Ee(i)+"."+Ee(s)}break}case"av01":{const e=fe(i,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,s=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,d=2===t&&o?l?12:10:o?10:8,h=(16&e[2])>>4,c=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],g=1,m=1,p=1,y=0;n+="."+t+"."+Ee(s)+a+"."+Ee(d)+"."+h+"."+c+u+f+"."+Ee(g)+"."+Ee(m)+"."+Ee(p)+"."+y,r=ye("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:r}}function ye(e,t){const i=fe(t,["dvvC"]),s=i.length?i[0]:fe(t,["dvcC"])[0];if(s){const t=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return e+"."+Ee(t)+"."+Ee(i)}}function ve(e,t){const i=t+5;for(;128&e[t++]&&t<i;);return t}function Te(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Ee(e){return(e<10?"0":"")+e}function Se(e,t){fe(e,["moov","trak"]).forEach(e=>{const i=fe(e,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let r=fe(s,["enca"]);const n=r.length>0;n||(r=fe(s,["encv"])),r.forEach(e=>{fe(n?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const i=Ae(e);i&&t(i,n)})})})}function Ae(e){const t=fe(e,["schm"])[0];if(t){const i=le(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=fe(e,["schi","tenc"])[0];if(t)return t}}}function be(e,t){const i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function Le(e,t){const i=[],s=t.samples,r=t.timescale,n=t.id;let a=!1;return fe(s,["moof"]).map(o=>{const l=o.byteOffset-8;fe(o,["traf"]).map(o=>{const d=fe(o,["tfdt"]).map(e=>{const t=e[0];let i=he(e,4);return 1===t&&(i*=Math.pow(2,32),i+=he(e,8)),i/r})[0];return void 0!==d&&(e=d),fe(o,["tfhd"]).map(d=>{const h=he(d,4),c=16777215&he(d,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;h===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=he(d,p),p+=4),f&&(g=he(d,p),p+=4),m&&(p+=4),"video"===t.type&&(a=Re(t.codec)),fe(o,["trun"]).map(n=>{const o=n[0],d=16777215&he(n,0),h=!!(1&d);let c=0;const f=!!(4&d),m=!!(256&d);let p=0;const y=!!(512&d);let v=0;const T=!!(1024&d),E=!!(2048&d);let S=0;const A=he(n,4);let b=8;h&&(c=he(n,b),b+=4),f&&(b+=4);let L=c+l;for(let l=0;l<A;l++){if(m?(p=he(n,b),b+=4):p=u,y?(v=he(n,b),b+=4):v=g,T&&(b+=4),E&&(S=0===o?he(n,b):ue(n,b),b+=4),t.type===J){let t=0;for(;t<v;){const n=he(s,L);if(L+=4,Ie(a,s[L])){ke(s.subarray(L,L+n),a?2:1,e+S/r,i)}L+=n,t+=n+4}}e+=p/r}}))})})}),i}function Re(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Ie(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function ke(e,t,i,s){const r=Pe(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){$.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=de(r,t);if(t+=2,49===e){const e=he(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let e=1;e<l;e++)d[e]=r[t++]}s.push({type:e,payloadType:a,pts:i,bytes:d})}}}}}else if(5===a&&o>16){const e=[];for(let i=0;i<16;i++){const s=r[t++].toString(16);e.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=r[t++];s.push({payloadType:a,pts:i,uuid:e.join(""),userData:H(l),userDataBytes:l})}}}function Pe(e){const t=e.byteLength,i=[];let s=1;for(;s<t-2;)0===e[s]&&0===e[s+1]&&3===e[s+2]?(i.push(s+2),s+=2):s++;if(0===i.length)return e;const r=t-i.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===i[0]&&(a++,i.shift()),n[s]=e[a];return n}function we(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");let s,r,n;s=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){const i=t.length;let s=8,r=i;for(;r--;)s+=t[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),r=0,s=8;r<i;r++)n.set(t[r],s),s+=t[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,i)}function De(e){const t=e.getUint32(0),i=e.byteOffset,s=e.byteLength;if(s<t)return{offset:i,size:s};if(1886614376!==e.getUint32(4))return{offset:i,size:t};const r=e.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:t};const n=e.buffer,a=K(new Uint8Array(n,i+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=e.getUint32(28);if(!r||s<32+16*r)return{offset:i,size:t};o=[];for(let e=0;e<r;e++)o.push(new Uint8Array(n,i+32+16*e,16));d=32+16*r}if(!d)return{offset:i,size:t};const h=e.getUint32(d);return t-32<h?{offset:i,size:t}:(l=new Uint8Array(n,i+d+4,h),{version:r,systemId:a,kids:o,data:l,offset:i,size:t})}const xe=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ce={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function _e(e,t){const i=Ce[t];return!!i&&!!i[e.slice(0,4)]}function Me(e,t,i=!0){return!e.split(",").some(e=>!Oe(e,t,i))}function Oe(e,t,i=!0){var s;const r=V(i);return null!=(s=null==r?void 0:r.isTypeSupported(Fe(e,t)))&&s}function Fe(e,t){return`${t}/mp4;codecs=${e}`}function Ue(e){if(e){const t=e.substring(0,4);return Ce.video[t]}return 2}function Ne(e){const t=xe();return e.split(",").reduce((e,i)=>{const s=t&&Re(i)?9:Ce.video[i];return s?(2*s+e)/(e?3:2):(Ce.audio[i]+e)/(e?2:1)},0)}const Be={};const $e=/flac|opus|mp4a\.40\.34/i;function Ve(e,t=!0){return e.replace($e,e=>function(e,t=!0){if(Be[e])return Be[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<i.length;r++){var s;if(Oe(i[r],"audio",t))return Be[e]=i[r],i[r];if("mp3"===i[r]&&null!=(s=V(t))&&s.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function Ge(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(He(e,"audio")||He(e,"video")))return e;if(t){const i=t.split(",");if(i.length>1){if(e)for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t];return i[0]}}return t||e}function He(e,t){return _e(e,t)&&Oe(e,t)}function Ke(e){if(e.startsWith("av01.")){const t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}function je(e){const t=V(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function We(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const qe={supported:!1,smooth:!1,powerEfficient:!1},Ye={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function ze(e,t){return{supported:!1,configurations:t,decodingInfoResults:[qe],error:e}}function Xe(e,t,i,s,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,h=d?parseInt(d):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,i)=>{if(i){const s=t.groups[i];if(!s)throw new Error(`Audio track group ${i} not found`);Object.keys(s.channels).forEach(t=>{e[t]=(e[t]||0)+s.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some(e=>Re(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(s,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(r,8e6))||!!c&&m(h)&&Object.keys(c).some(e=>parseInt(e)>h)}function Qe(e,t,i,s={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!i)return Promise.resolve(Ye);const n=[],a=function(e){var t;const i=null==(t=e.videoCodec)?void 0:t.split(","),s=Ze(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return i?i.map(e=>{const t={contentType:Fe(Ke(e),"video"),width:r,height:n,bitrate:s,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,i){var s;const r=null==(s=e.audioCodec)?void 0:s.split(","),n=Ze(e);if(r&&e.audioGroups)return e.audioGroups.reduce((e,s)=>{var a;const o=s?null==(a=t.groups[s])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===s){const s=parseFloat(t.channels||"");r.forEach(t=>{const r={contentType:Fe(t,"audio"),bitrate:i?Je(t,n):n};s&&(r.channels=""+s),e.push(r)})}return e},e):e},[]);return[]}(e,t,o>0),d=l.length;for(let e=o||1*d||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),d){t.audio=l[e%d];const i=t.audio.bitrate;t.video&&i&&(t.video.bitrate-=i)}n.push(t)}if(r){const e=navigator.userAgent;if(r.split(",").some(e=>Re(e))&&xe())return Promise.resolve(ze(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map(e=>{const t=function(e){let t="";const{audio:i,video:s}=e;if(s){t+=`${We(s.contentType)}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){t+=`${s?"_":""}${We(i.contentType)}_c${i.channels}`}return t}(e);return s[t]||(s[t]=i.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:n,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e}))}function Je(e,t){if(t<=1)return 1;let i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}function Ze(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}const et=["NONE","TYPE-0","TYPE-1",null];const tt=["SDR","PQ","HLG"];var it="",st="YES",rt="v2";function nt(e){const{canSkipUntil:t,canSkipDateRanges:i,age:s}=e;return t&&s<t/2?i?rt:st:it}class at{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 void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class ot{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return lt(this._audioGroups,e)}hasSubtitleGroup(e){return lt(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.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 null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function lt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function dt(e,t){let i=!1,s=[];if(e&&(i="SDR"!==e,s=[e]),t){s=t.allowedVideoRanges||tt.slice(0);const e="SDR"!==s.join("")&&!t.videoCodec;i=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}const ht=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(i,s)=>{if(e&&(s=e(i,s)),"object"==typeof s&&null!==s){if(t.has(s))return;t.add(s)}return s}})(t));function ct(e,t){$.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function ut(e){return e.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 ft(e){if(!e)return e;const{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}=e;return{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function gt(e,t,i){if("attrs"in e){const i=t.indexOf(e);if(-1!==i)return i}for(let s=0;s<t.length;s++){if(mt(e,t[s],i))return s}return-1}function mt(e,t,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===s||t.groupId===s)&&(void 0===r||t.name===r)&&(void 0===n||function(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const i=e.split(","),s=t.split(",");return i.length===s.length&&!i.some(e=>-1===s.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function pt(e,t){const{audioCodec:i,channels:s}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(t.channels||"2"))}function yt(e,t,i){for(let s=t;s>-1;s--)if(i(e[s]))return s;for(let s=t+1;s<e.length;s++)if(i(e[s]))return s;return-1}function vt(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}const Tt=function(e,t){let i=0,s=e.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=e[r];const a=t(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function Et(e,t,i=0,s=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const s=e.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===St(i,s,n)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const s=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),i);return e.start<=s}return!1}(n,e,Math.min(r,s))))return n;const a=Tt(t,St.bind(null,i,s));return!a||a===e&&n?n:a}function St(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=e?1:i.start-s>e&&i.start?-1:0}function At(e,t,i){const s=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>e}function bt(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){let s=e.fragments;const{fragmentHint:r}=e;let n;return r&&(s=s.concat(r)),Tt(s,e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=i?1:e.start>i?-1:0)),n||null}return null}function Lt(e){switch(e.details){case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_TIMEOUT:case T.LEVEL_LOAD_TIMEOUT:case T.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Rt(e){return e.details.startsWith("key")}function It(e){return Rt(e)&&!!e.frag&&!e.frag.decryptdata}function kt(e,t){const i=Lt(t);return e.default[(i?"timeout":"error")+"Retry"]}function Pt(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function wt(e){return _(_({},e),{errorRetry:null,timeoutRetry:null})}function Dt(e,t,i,s){if(!e)return!1;const r=null==s?void 0:s.code,n=t<e.maxNumRetry&&(function(e){return xt(e)||!!e&&(e<400||e>499)}(r)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,s,n):n}function xt(e){return 0===e&&!1===navigator.onLine}var Ct=0,_t=2,Mt=3,Ot=5,Ft=0,Ut=1,Nt=2,Bt=4;function $t(e){const t={action:Ct,flags:Ft};return e&&(t.resolved=!0),t}var Vt="NOT_LOADED",Gt="APPENDING",Ht="PARTIAL",Kt="OK";class jt{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.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 t=i.length;t--;){const s=i[t];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){const a=s[r[n]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,s,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(s=>{const a=this.fragments[s];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===i&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some(e=>{const i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(a.body),i}):this.removeFragment(a.body))})}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const i=e.frag,s=qt(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const n=!i.relurl;if(Object.keys(t).forEach(s=>{const a=i.elementaryStreams[s];if(!a)return;const o=t[s],l=n||!0===a.partial;r.range[s]=this.getBufferedTimes(i,e.part,l,o)}),r.loaded=null,Object.keys(r.range).length){r.buffered=!0;(r.body.endList=i.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),Wt(r)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(r.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=Yt(i,t=>t.fragment.sn>=e))}fragBuffered(e,t){const i=qt(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const r={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<s.length;e++){const t=s.start(e)-this.bufferPadding,i=s.end(e)+this.bufferPadding;if(l>=t&&o<=i){r.time.push({startPTS:Math.max(n,s.start(e)),endPTS:Math.min(a,s.end(e))});break}if(n<i&&a>t){const t=Math.max(n,s.start(e)),i=Math.min(a,s.end(e));i>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:i}))}else if(a<=t)break}return r}getPartialFragment(e){let t,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&Wt(d)&&(i=d.body.start-a,s=d.body.end+a,e>=i&&e<=s&&(t=Math.min(e-i,s-e),n<=t&&(r=d.body,n=t)))}),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||Wt(t))}getState(e){const t=qt(e),i=this.fragments[t];return i?i.buffered?Wt(i)?Ht:Kt:Gt:Vt}isTimeBuffered(e,t,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,r=qt(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:r,type:n}=t;if("initSegment"===i.sn)return;const a=i.type;if(s){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(s)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=qt(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 r=t[i[s]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=qt(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const t=e.sn;this.activePartLists[e.type]=Yt(i,e=>e.fragment.sn!==t)}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=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function Wt(e){var t,i,s;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(s=e.range.audiovideo)&&s.partial)}function qt(e){return`${e.type}_${e.level}_${e.sn}`}function Yt(e,t){return e.filter(e=>{const i=t(e);return i||e.clearElementaryStreamInfo(),i})}var zt=0,Xt=1;class Qt{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 zt:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Xt:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Jt{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 e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;const o=u[f],m=u[o],p=u[m];let y=257*u[i]^16843008*i;s[f]=y<<24|y>>>8,r[f]=y<<16|y>>>16,n[f]=y<<8|y>>>24,a[f]=y,y=16843009*p^65537*m^257*o^16843008*f,l[i]=y<<24|y>>>8,d[i]=y<<16|y>>>16,h[i]=y<<8|y>>>24,c[i]=y,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=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 r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let y,v;for(a=0;a<n;a++)a<r?y=l[a]=t[a]:(v=y,a%r===0?(v=v<<8|v>>>24,v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[255&v],v^=c[a/r|0]<<24):r>6&&a%r===4&&(v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[255&v]),l[a]=y=(l[a-r]^v)>>>0);for(o=0;o<n;o++)a=n-o,v=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?v:f[h[v>>>24]]^g[h[v>>>16&255]]^m[h[v>>>8&255]]^p[h[255&v]],d[o]=d[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],c=this.uint8ArrayToUint32Array_(i);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(e),y=new Int32Array(p.length);let v,T,E,S,A,b,L,R,I,k,P,w,D,x;const C=this.networkToHostOrderSwap;for(;t<p.length;){for(I=C(p[t]),k=C(p[t+1]),P=C(p[t+2]),w=C(p[t+3]),A=I^r[0],b=w^r[1],L=P^r[2],R=k^r[3],D=4,x=1;x<s;x++)v=o[A>>>24]^l[b>>16&255]^d[L>>8&255]^h[255&R]^r[D],T=o[b>>>24]^l[L>>16&255]^d[R>>8&255]^h[255&A]^r[D+1],E=o[L>>>24]^l[R>>16&255]^d[A>>8&255]^h[255&b]^r[D+2],S=o[R>>>24]^l[A>>16&255]^d[b>>8&255]^h[255&L]^r[D+3],A=v,b=T,L=E,R=S,D+=4;v=n[A>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&R]^r[D],T=n[b>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[255&A]^r[D+1],E=n[L>>>24]<<24^n[R>>16&255]<<16^n[A>>8&255]<<8^n[255&b]^r[D+2],S=n[R>>>24]<<24^n[A>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^r[D+3],y[t]=C(v^u),y[t+1]=C(S^f),y[t+2]=C(E^g),y[t+3]=C(T^m),u=I,f=k,g=P,m=w,t+=4}return y.buffer}}class Zt{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=function(e){switch(e){case zt:return"AES-CBC";case Xt:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class ei{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}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);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?e.slice(0,t-i):e}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==zt||16!==t.byteLength)return $.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=be(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Jt),l.expandKey(t);const d=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new Zt(this.subtle,t,s)}return this.fastAesKey.expandKey().then(t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Qt(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,t)}).catch(r=>($.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&($.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const ti=Math.pow(2,17);class ii{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){const i=e.url;if(!i)return Promise.reject(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void o(ri(e));e.gap=!1}const l=this.loader=r?new r(s):new n(s),d=si(e);e.loader=l;const h=wt(s.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:ti};e.stats=l.stats;const u={onSuccess:(t,i,s,r)=>{this.resetLoader(e,l);let n=t.data;s.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,s,r,n)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:_({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:n}))},onAbort:(t,i,s)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:(t,i,s)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:s,stats:t}))}};t&&(u.onProgress=(i,s,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})),l.load(d,c,u)})}loadPart(e,t,i){this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(ri(e,t));const l=this.loader=r?new r(s):new n(s),d=si(e,t);e.loader=l;const h=wt(s.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ti};t.stats=l.stats,l.load(d,c,{onSuccess:(s,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const d={frag:e,part:t,payload:s.data,networkDetails:o};i(d),a(d)},onError:(i,s,r,n)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:_({url:d.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:r,stats:n}))},onAbort:(i,s,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:i}))},onTimeout:(i,s,r)=>{this.resetLoader(e,l),o(new ni({type:v.NETWORK_ERROR,details:T.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:i}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(e.duration/t.duration),n=Math.min(Math.round(i.loaded/r),s),a=(s-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function si(e,t=null){const i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(m(r)&&m(n)){var a;let t=r,i=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-r;e%16&&(i=n+(16-e%16)),0!==r&&(s.resetIV=!0,t=r-16)}s.rangeStart=t,s.rangeEnd=i}var o;return s}function ri(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:v.MEDIA_ERROR,details:T.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(s.part=t),(t||e).stats.aborted=!0,new ni(s)}class ni extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class ai extends M{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&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class oi{constructor(e,t,i,s=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=n}}const li={length:0,start:()=>0,end:()=>0};class di{static isBuffered(e,t){if(e){const i=di.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=di.getBuffered(e);return di.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=di.bufferedRanges(e);if(s.length)return di.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((e,t)=>e.start-t.start||t.end-e.end);let s=-1,r=[];if(i)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(s=n);const a=r.length;if(a){const t=r[a-1].end;e[n].start-t<i?e[n].end>t&&(r[a-1].end=e[n].end):r.push(e[n])}else r.push(e[n])}else r=e;let n,a=0,o=t,l=t;for(let e=0;e<r.length;e++){const d=r[e].start,h=r[e].end;if(-1===s&&t>=d&&t<=h&&(s=e),t+i>=d&&t<h)o=d,l=h,a=l-t;else if(t+i<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||li}catch(e){return $.log("failed to get media.buffered",e),li}}}const hi=/\{\$([a-zA-Z0-9-_]+)\}/g;function ci(e){return hi.test(e)}function ui(e,t){if(null!==e.variableList||e.hasVariableRefs){const i=e.variableList;return t.replace(hi,t=>{const s=t.substring(2,t.length-1),r=null==i?void 0:i[s];return void 0===r?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),t):r})}return t}function fi(e,t,i){let s,r,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){s=t.QUERYPARAM;try{const e=new self.URL(i).searchParams;if(!e.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=e.get(s)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else s=t.NAME,r=t.VALUE;s in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function gi(e,t,i){const s=t.IMPORT;if(i&&s in i){let t=e.variableList;t||(e.variableList=t={}),t[s]=i[s]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const mi=/^(\d+)x(\d+)$/,pi=/(.+?)=(".*?"|.*?)(?:,|$)/g;class yi{constructor(e,t){"string"==typeof e&&(e=yi.parseAttrList(e,t)),x(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}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=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+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((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=mi.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const s={};for(pi.lastIndex=0;null!==(i=pi.exec(e));){const r=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=ui(t,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":$.warn(`${e}: attribute ${r} is missing quotes`)}s[r]=n}return s}}function vi(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function Ti(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class Ei{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=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(s=null==t?void 0:t.tagOrder)?s:i,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){$.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=x(new yi({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);m(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const 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}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?($.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 null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(m(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"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&m(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class Si{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);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||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):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&&m(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&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 null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&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 Ai(e,t){return e.length===t.length&&!e.some((e,i)=>e!==t[i])}function bi(e,t){return!e&&!t||!(!e||!t)&&Ai(e,t)}function Li(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Ri(e){switch(e){case"AES-128":case"AES-256":return zt;case"AES-256-CTR":return Xt;default:throw new Error(`invalid full segment method ${e}`)}}function Ii(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function ki(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function Pi(e){const t=function(e,t,i){const s=e[t];e[t]=e[i],e[i]=s};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function wi(e){const t=e.split(":");let i=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),s=e[e.length-1].split(",");if(2===s.length){const t="base64"===s[0],r=s[1];t?(e.splice(-1,1),i=Ii(r)):i=function(e){const t=ki(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(r)}}return i}const Di="undefined"!=typeof self?self:void 0;var xi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ci="org.w3.clearkey",_i="com.apple.streamingkeydelivery",Mi="com.microsoft.playready",Oi="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Fi(e){switch(e){case _i:return xi.FAIRPLAY;case Mi:return xi.PLAYREADY;case Oi:return xi.WIDEVINE;case Ci:return xi.CLEARKEY}}function Ui(e){switch(e){case xi.FAIRPLAY:return _i;case xi.PLAYREADY:return Mi;case xi.WIDEVINE:return Oi;case xi.CLEARKEY:return Ci}}function Ni(e){const{drmSystems:t,widevineLicenseUrl:i}=e,s=t?[xi.FAIRPLAY,xi.WIDEVINE,xi.PLAYREADY,xi.CLEARKEY].filter(e=>!!t[e]):[];return!s[xi.WIDEVINE]&&i&&s.push(xi.WIDEVINE),s}const Bi=null!=Di&&null!=($i=Di.navigator)&&$i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var $i;function Vi(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),s=i.substring(i.indexOf("<"),i.length),r=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(e){const t=Ii(e).subarray(0,16);return Pi(t),t}}return null}let Gi={};class Hi{static clearKeyUriToKeyIdMap(){Gi={}}static setKeyIdForUri(e,t){Gi[e]=t}constructor(e,t,i,s=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!Li(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(j(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Ai(e.keyFormatVersions,this.keyFormatVersions)&&bi(e.iv,this.iv)&&bi(e.keyId,this.keyId)}isSupported(){if(this.method){if(Li(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case _i:case Oi:case Mi:case Ci:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Li(this.method)){let t=this.iv;t||("number"!=typeof e&&($.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e));return new Hi(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){const e=Gi[this.uri];if(e&&!Ai(this.keyId,e)&&Hi.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=wi(this.uri);if(i)switch(this.keyFormat){case Oi:if(this.pssh=i,!this.keyId){const e=function(e){const t=[];if(e instanceof ArrayBuffer){const i=e.byteLength;let s=0;for(;s+32<i;){const i=De(new DataView(e,s));t.push(i),s+=i.size}}return t}(i.buffer);if(e.length){var s;const t=e[0];this.keyId=null!=(s=t.kids)&&s.length?t.kids[0]:null}}this.keyId||(this.keyId=Ki(t));break;case Mi:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=we(e,0,i),this.keyId=Vi(i);break}default:{let e=i.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=function(e){const t=null==e?void 0:e[Oi];if(t)return t.keyId;return null}(t),e||(e=Ki(t),e||(e=Gi[this.uri])),e&&(this.keyId=e,Hi.setKeyIdForUri(this.uri,e))}return this}}function Ki(e){const t=null==e?void 0:e[Mi];if(t){const e=wi(t.uri);if(e)return Vi(e)}return null}const ji=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Wi=/#EXT-X-MEDIA:(.*)/g,qi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Yi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),zi=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Xi{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 z.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return qi.test(e)}static parseMasterPlaylist(e,t){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:ci(e)},s=[];if(ji.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=ji.exec(e));)if(r[1]){var n;const e=new yi(r[1],i),a=ui(i,r[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Xi.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),ts(e.CODECS,o);const d=e["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},ts(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||s.push(o),i.levels.push(o)}else if(r[3]){const e=r[3],s=r[4];switch(e){case"SESSION-DATA":{const e=new yi(s,i),t=e["DATA-ID"];t&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[t]=e);break}case"SESSION-KEY":{const e=Zi(s,t,i);e.encrypted&&e.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(e)):$.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${s}"`);break}case"DEFINE":fi(i,new yi(s,i),t);break;case"CONTENT-STEERING":{const e=new yi(s,i);i.contentSteering={uri:Xi.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=es(s)}}const a=s.length>0&&s.length<i.levels.length;return i.levels=a?s:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,i){let s;const r={},n=i.levels,a={AUDIO:n.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:n.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(Wi.lastIndex=0;null!==(s=Wi.exec(e));){const e=new yi(s[1],i),n=e.TYPE;if(n){const i=a[n],s=r[n]||[];r[n]=s;const l=e.LANGUAGE,d=e["ASSOC-LANGUAGE"],h=e.CHANNELS,c=e.CHARACTERISTICS,u=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?Xi.resolve(e.URI,t):""};if(d&&(f.assocLang=d),h&&(f.channels=h),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=i&&i.length){const e=Xi.findGroup(i,f.groupId)||i[0];is(f,e,"audioCodec"),is(f,e,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(e,t,i,s,r,n){var a;const o={url:t},l=new Si(t),d=l.fragments,h=[];let c,u,f,g,p=null,y=0,v=0,T=0,E=0,S=0,A=null,b=new ie(s,o),L=-1,R=!1,I=null;if(Yi.lastIndex=0,l.m3u8=e,l.hasVariableRefs=ci(e),"#EXTM3U"!==(null==(a=Yi.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=Yi.exec(e));){R&&(R=!1,b=new ie(s,o),b.playlistOffset=T,b.setStart(T),b.sn=y,b.cc=E,S&&(b.bitrate=S),b.level=i,p&&(b.initSegment=p,p.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),I&&(b.setByteRange(I),I=null)));const e=c[1];if(e){b.duration=parseFloat(e);const t=(" "+c[2]).slice(1);b.title=t||null,b.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(m(b.duration)){b.playlistOffset=T,b.setStart(T),f&&ns(b,f,l),b.sn=y,b.level=i,b.cc=E,d.push(b);const e=(" "+c[3]).slice(1);b.relurl=ui(l,e),ss(b,A,h),A=b,T+=b.duration,y++,v=0,R=!0}}else{if(c=c[0].match(zi),!c){$.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const e=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(e){case"BYTERANGE":A?b.setByteRange(r,A):b.setByteRange(r);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=r,b.tagList.push(["PROGRAM-DATE-TIME",r]),-1===L&&(L=d.length);break;case"PLAYLIST-TYPE":l.type&&as(l,e,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?as(l,e,c):d.length>0&&os(l,e,c),y=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&as(l,e,c);const t=new yi(r,l),i=t.decimalInteger("SKIPPED-SEGMENTS");if(m(i)){l.skippedSegments+=i;for(let e=i;e--;)d.push(null);y+=i}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&as(l,e,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&as(l,e,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||as(l,e,c),l.live=!1;break;case"#":(r||a)&&b.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":E++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([e]);break;case"BITRATE":b.tagList.push([e,r]),S=1e3*parseInt(r),m(S)?b.bitrate=S:S=0;break;case"DATERANGE":{const e=new yi(r,l),t=new Ei(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:$.warn(`Ignoring invalid DATERANGE tag: "${r}"`),b.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const e=new yi(r,l);"IMPORT"in e?gi(l,e,n):fi(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?as(l,e,c):d.length>0&&os(l,e,c),l.startCC=E=parseInt(r);break;case"KEY":{const e=Zi(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=x({},f)),f[e.keyFormat]=e)}else $.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=es(r);break;case"MAP":{const e=new yi(r,l);if(b.duration){const t=new ie(s,o);rs(t,e,i,f),p=t,b.initSegment=p,p.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime)}else{const t=b.byteRangeEndOffset;if(t){const e=b.byteRangeStartOffset;I=`${t-e}@${e}`}else I=null;rs(b,e,i,f),p=b,R=!0}p.cc=E;break}case"SERVER-CONTROL":g&&as(l,e,c),g=new yi(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&as(l,e,c);const t=new yi(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,i=v++,s=new yi(r,l),n=new se(s,b,o,i,t);e.push(n),b.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new yi(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new yi(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:$.warn(`line parsed but not handled: ${c}`)}}}A&&!A.relurl?(d.pop(),T-=A.duration,l.partList&&(l.fragmentHint=A)):l.partList&&(ss(b,A,h),b.cc=E,l.fragmentHint=b,f&&ns(b,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const k=d.length,P=d[0],w=d[k-1];if(T+=l.skippedSegments*l.targetduration,T>0&&k&&w){l.averagetargetduration=T/k;const e=w.sn;l.endSN="initSegment"!==e?e:0,l.live||(w.endList=!0),L>0&&(!function(e,t){let i=e[t];for(let s=t;s--;){const t=e[s];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(d,L),P&&h.unshift(P))}return l.fragmentHint&&(T+=l.fragmentHint.duration),l.totalduration=T,h.length&&l.dateRangeTagCount&&P&&Qi(h,l),l.endCC=E,l}}function Qi(e,t){let i=e.length;if(!i){if(!t.hasProgramDateTime)return;{const s=t.fragments[t.fragments.length-1];e.push(s),i++}}const s=e[i-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let s=i;s--;){var a;if((null==(a=e[s])?void 0:a.sn)<t.startSN)break;const i=Ji(t,d,e,s,r);if(-1!==i){l.tagAnchor=t.fragments[i].ref;break}}}}function Ji(e,t,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(t>=o||0===s){var a;if(t<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||r)-n.start)){const r=i[s].sn-e.startSN;if(r<0)return-1;const n=e.fragments;if(n.length>i.length){for(let a=(i[s+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return r}}}return-1}function Zi(e,t,i){var s,r;const n=new yi(e,i),a=null!=(s=n.METHOD)?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&$.error(`Invalid IV: ${n.IV}`);const c=o?Xi.resolve(o,t):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Hi(a,c,h,u,l,n.KEYID)}function es(e){const t=new yi(e).decimalFloatingPoint("TIME-OFFSET");return m(t)?t:null}function ts(e,t){let i=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{const s=i.filter(t=>_e(t,e));s.length&&(t[`${e}Codec`]=s.map(e=>e.split("/")[0]).join(","),i=i.filter(e=>-1===s.indexOf(e)))}),t.unknownCodecs=i}function is(e,t,i){const s=t[i];s&&(e[i]=s)}function ss(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function rs(e,t,i,s){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",s&&(e.levelkeys=s),e.initSegment=null}function ns(e,t,i){e.levelkeys=t;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||s.push(e)}function as(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function os(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function ls(e,t){const i=t.startPTS;if(m(i)){let s,r=0;t.sn>e.sn?(r=i-e.start,s=e):(r=e.start-i,s=t),s.duration!==r&&s.setDuration(r)}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 ds(e,t,i,s,r,n,a){s-i<=0&&(a.warn("Fragment should have a positive duration",t),s=i+t.duration,n=r+t.duration);let o=i,l=s;const d=t.startPTS,h=t.endPTS;if(m(d)){const c=Math.abs(d-i);e&&c>e.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${t.level} ${e.url}`):m(t.deltaPTS)?t.deltaPTS=Math.max(c,t.deltaPTS):t.deltaPTS=c,o=Math.max(i,d),i=Math.min(i,d),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,l=Math.min(s,h),s=Math.max(s,h),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const c=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(s-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=r,t.endPTS=s,t.minEndPTS=l,t.endDTS=n;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let f;const g=u-e.startSN,p=e.fragments;for(p[g]=t,f=g;f>0;f--)ls(p[f],p[f-1]);for(f=g;f<p.length-1;f++)ls(p[f],p[f+1]);return e.fragmentHint&&ls(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function hs(e,t,i){if(e===t)return;let s=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){s=t;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){const s=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(s?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=r;d<=n;d++){const r=l[a+d];let n=o[d];if(s&&!n&&r&&(n=t.fragments[d]=r),r&&n){i(r,n,d,o);const s=r.relurl,a=n.relurl;if(s&&Ts(s,a))return void(t.playlistParsingError=cs(`media sequence mismatch ${n.sn}:`,e,t,r,n));if(r.cc!==n.cc)return void(t.playlistParsingError=cs(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,e,t,r,n))}}}(e,t,(e,i,r,a)=>{if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){const s=e.cc-i.cc;for(let e=r;e<a.length;e++)a[e].cc+=s;t.endCC=a[a.length-1].cc}m(e.startPTS)&&m(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(n=i),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.initSegment=e.initSegment,s=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(s&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=s)?void 0:t.relurl)||(e.initSegment=s)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){const{dateRanges:s,recentlyRemovedDateranges:r}=t,n=x({},e);r&&r.forEach(e=>{delete n[e]});const a=Object.keys(n).length;if(!a)return s;return Object.keys(s).forEach(e=>{const t=n[e],r=new Ei(s[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ht(s[e].attr)}"`)}),n}(e.dateRanges,t,i));const s=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&ss(o[e],o[e-1],s);Qi(s,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const i=ms(e,t.startSN-1);t.startCC=null!=(l=null==i?void 0:i.cc)?l:a[0].cc}!function(e,t,i){if(e&&t){let s=0;for(let r=0,n=e.length;r<=n;r++){const n=e[r],a=t[r+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):s--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),n?ds(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,i):us(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const e=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=e),t.driftEndTime=d,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function cs(e,t,i,s,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function us(e,t,i=!0){const s=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+s*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}fs(t,a)}function fs(e,t){if(t){const i=e.fragments;for(let s=e.skippedSegments;s<i.length;s++)i[s].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function gs(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const s=e.fragments,r=4;if(s.length&&i*r>t){const e=1e3*s[s.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}function ms(e,t,i){if(!e)return null;let s=e.fragments[t-e.startSN];return s||(s=e.fragmentHint,s&&s.sn===t?s:t<e.startSN&&i&&i.sn===t?i:null)}function ps(e,t,i){return e?ys(e.partList,t,i):null}function ys(e,t,i){if(e)for(let s=e.length;s--;){const r=e[s];if(r.index===i&&r.fragment.sn===t)return r}return null}function vs(e){e.forEach((e,t)=>{var i;null==(i=e.details)||i.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function Ts(e,t){return!(e===t||!t)&&Es(e)!==Es(t)}function Es(e){return e.replace(/\?[^?]*$/,"")}function Ss(e,t){for(let s=0,r=e.length;s<r;s++){var i;if((null==(i=e[s])?void 0:i.cc)===t)return e[s]}return null}function As(e,t){const i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function bs(e,t){const i=t.fragments;for(let t=0,s=i.length;t<s;t++)As(i[t],e);t.fragmentHint&&As(t.fragmentHint,e),t.alignedSliding=!0}function Ls(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const i=Math.min(t.endCC,e.endCC),s=Ss(t.fragments,i),r=Ss(e.fragments,i);if(!s||!r)return;$.log(`Aligning playlist at start of dicontinuity sequence ${i}`);bs(s.start-r.start,e)}function Rs(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,s=t.fragments;if(!i.length||!s.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=Ss(s,a),n=Ss(i,a)),r&&n||(r=s[Math.floor(s.length/2)],n=Ss(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;bs((l-o)/1e3-(n.start-r.start),e)}function Is(e,t,i){ks(e,t,i),e.addEventListener(t,i)}function ks(e,t,i){e.removeEventListener(t,i)}const Ps=function(e){let t="";const i=e.length;for(let s=0;s<i;s++)t+=`[${e.start(s).toFixed(3)}-${e.end(s).toFixed(3)}]`;return t},ws="STOPPED",Ds="IDLE",xs="KEY_LOADING",Cs="FRAG_LOADING",_s="FRAG_LOADING_WAITING_RETRY",Ms="WAITING_TRACK",Os="PARSING",Fs="PARSED",Us="ENDED",Ns="ERROR",Bs="WAITING_INIT_PTS",$s="WAITING_LEVEL";class Vs extends ai{constructor(e,t,i,s,r){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ws,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:r}=this,n=i?i.currentTime:0,a=di.bufferInfo(s||i,n,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${m(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===Us)this.resetLoadingState();else if(t){const i=e.maxFragLookUpTolerance,s=t.start-i,r=t.start+t.duration+i;if(o||r<a.start||s>a.end){const e=n>r;(n<s||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===Ds&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new ii(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ei(e.config)}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===ws)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const 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=ws}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=di.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>s&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return di.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;Is(i,"seeking",this.onMediaSeeking),Is(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===ws&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(null!==s){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ks(s,"seeking",this.onMediaSeeking),ks(s,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ws,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){this._doFragLoad(e,t,i,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,i=e.frag;this.fragContextChanged(i)?(t===Cs||!this.fragCurrent&&t===Os)&&(this.fragmentTracker.removeFragment(i),this.state=Ds):("payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(E.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==ws&&this.state!==Ns&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Gt){const t=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,s?s.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ht&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(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(E.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e}).then(e=>{const{hls:t}=this,{frag:i,payload:s}=e,r=i.decryptdata;if(s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&Li(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,Ri(r.method)).catch(e=>{throw t.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e}).then(s=>{const r=self.performance.now();return t.trigger(E.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:n,tdecrypt:r}}),e.payload=s,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==ws&&this.state!==Ns&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==ws&&(this.state=Ds),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,s;const r=e.tracks;if(r&&!t.encrypted&&(null!=(i=r.audio)&&i.encrypted||null!=(s=r.video)&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(i.message),!e||e.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}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?Ps(di.getBuffered(i)):"(detached)"})`),te(e)){var s;if(e.type!==k){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=Ds)}const t=null==(s=this.levels)?void 0:s[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=Ds}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:r}=e,n=!r||0===r.length||r.some(e=>!e),a=new oi(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=xs,this.fragCurrent=e,a=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(E.KEY_LOADED,e),this.state===xs&&(this.state=Ds),e}),this.hls.trigger(E.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(te(e)&&(!o||e.sn!==o.sn)){const i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts&&te(e)){const r=n.partList;if(r&&s){i>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(r,e,i);if(o>-1){const l=r[o];let d;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Cs,d=a?a.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,s)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,l,t,s).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(r,i))return Promise.resolve(null)}}var l;if(te(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),m(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Cs;const d=this.config.progressive;let h;return h=d&&a?a.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,s)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,d?s:void 0),a]).then(([e])=>(!d&&s&&s(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,i,s){return new Promise((r,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,d=t=>{this.fragmentLoader.loadPart(e,t,s).then(s=>{o[t.index]=s;const n=s.part;this.hls.trigger(E.FRAG_LOADED,s);const a=ps(i.details,e.sn,t.index+1)||ys(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});d(a)}).catch(n)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===T.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===v.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Os)return void(this.fragCurrent||this.state===ws||this.state===Ns||(this.state=Ds));const{frag:i,part:s,level:r}=t,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,s,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===k)return!1;if(t>=r.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)){var s;if((this.hls.hasEnoughToStart?(null==(s=this.media)?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:n}=e;if(null==t||!t[s])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=t[s],o=a.details,l=n>-1?ps(o,r,n):null,d=l?l.fragment:ms(o,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(e,t,i,s,r){if(this.state!==Os)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=be(n,a)),!o.length)return;const l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,h={type:e.type,frag:t,part:i,chunkMeta:s,offset:d,parent:t.type,data:o};if(this.hls.trigger(E.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!di.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const i=t.currentTime,s=di.bufferInfo(t,i,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,s.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const s=this.getLoadPosition();if(!m(s))return null;const r=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,r)}getFwdBufferInfoAtPos(e,t,i,s){const r=di.bufferInfo(e,t,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(r.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(r.nextStart,n.end)-t,s);return di.bufferInfo(e,t,i)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return i=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-3*t,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=R){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=i[0].start,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const i=r.initialLiveManifestSize;if(s<i)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${i})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const i=this.hls.startPosition,s=this.hls.liveSyncPosition,r=o?(-1!==i&&i>=n?i:s)||o.start:e;this.log(`Setting startPosition to ${r} to match start frag at live edge. mainStart: ${i} liveSyncPosition: ${s} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=r}}else e<=n&&(o=i[0]);if(!o){const i=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,i,t)}let d=this.filterReplacedPrimary(o,t);if(!d&&o){const e=o.sn-t.startSN;d=this.filterReplacedPrimary(i[e+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Kt||i===Ht&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&i.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==e&&i.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Gs(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Gs(this.config)&&e.type!==k){const i=this.hls.interstitialsManager,s=null==i?void 0:i.bufferingItem;if(s){const i=s.event;if(i){if(i.appendInPlace||Math.abs(e.start-s.start)>1||0===s.start)return null}else{if(e.end<=s.start&&!1===(null==t?void 0:t.live))return null;if(e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}}const r=null==i?void 0:i.playerQueue;if(r)for(let t=r.length;t--;){const i=r[t].interstitial;if(i.appendInPlace&&e.start>=i.startTime&&e.end<=i.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let s=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,s>-1&&i<o.start)break;const l=o.loaded;l?s=-1:(r||(o.independent||n)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${o.start}`),s=a),r=l}return s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!m(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let s=0;s<e.length;++s){const r=e[s];if(At(t,i,r))return r}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=bt(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(s=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let c;if(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var u;c=Et(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const e=c.sn-i.startSN,t=this.fragmentTracker.getState(c);if((t===Kt||t===Ht&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!h||d[0].fragment.sn>c.sn||!i.live)){if(c.level===r.level){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Kt?t:null}}}return c}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&m(r);if(n||!a&&!r){!function(e,t){e&&(Ls(t,e),t.alignedSliding||Rs(t,e),t.alignedSliding||t.skippedSegments||us(e,t,!1))}(i,e);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const s=this.timelineOffset;if(-1===i){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;null!==n&&m(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;const{media:t}=this;let i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&te(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===_s)||(this.state=Ds)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=t.details===T.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const a=t.errorAction;if(!a)return void(this.state=Ns);const{action:o,flags:l,retryCount:d=0,retryConfig:h}=a,c=!!h,u=c&&o===Ot,f=c&&!a.resolved&&l===Ut,g=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!u&&f&&te(s)&&!s.endList&&g&&!It(t))this.resetFragmentErrors(e),this.treatAsGap(s),a.resolved=!0;else if((u||f)&&d<h.maxNumRetry){var m;const i=xt(null==(m=t.response)?void 0:m.code),r=Pt(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=_s,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${d+1}/${h.maxNumRetry} in ${r}ms`)}else if(h){if(this.resetFragmentErrors(e),!(d<h.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${d})`);n||o===Mt||(a.resolved=!0)}else this.state=o===_t?$s:Ns;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!xt(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Ds)}reduceLengthAndFlushBuffer(e){if(this.state===Os||this.state===Fs){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==t?void 0:t.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===I&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ws&&(this.state=Ds)}afterBufferFlushed(e,t,i){if(!e)return;const s=di.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===Us&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ws&&(this.state=Ds)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<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 r=i.details;if(!r)return void this.warn("level.details undefined");var n;if(!Object.keys(e.elementaryStreams).reduce((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=s?0:ds(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:r,level:i,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(n=this.transmuxer)?void 0:n.error))){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Fs,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===R?"level":"track"}fragInfo(e,t=!0,i){var s,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(null!=(s=t&&!i?e.startPTS:(i||e).start)?s:NaN).toFixed(3)}-${(null!=(r=t&&!i?e.endPTS:(i||e).end)?r:NaN).toFixed(3)}]${i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(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}}function Gs(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class Hs{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;return e.length?(i=1===e.length?e[0]:function(e,t){const i=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}(e,t),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Ks,js={exports:{}};var Ws=(Ks||(Ks=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||e,a),l=i?i+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 a(e,t){0===--e._eventsCount?e._events=new s:delete e._events[t]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,s,r=[];if(0===this._eventsCount)return r;for(s in e=this._events)t.call(e,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=i?i+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r<n;r++)a[r]=s[r].fn;return a},o.prototype.listenerCount=function(e){var t=i?i+e:e,s=this._events[t];return s?s.fn?1:s.length:0},o.prototype.emit=function(e,t,s,r,n,a){var o=i?i+e:e;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(e,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,t),!0;case 3:return h.fn.call(h.context,t,s),!0;case 4:return h.fn.call(h.context,t,s,r),!0;case 5:return h.fn.call(h.context,t,s,r,n),!0;case 6:return h.fn.call(h.context,t,s,r,n,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var u,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(e,h[d].fn,void 0,!0),c){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,t);break;case 3:h[d].fn.call(h[d].context,t,s);break;case 4:h[d].fn.call(h[d].context,t,s,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(e,t,i){return n(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return n(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,s,r){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||s&&o.context!==s||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==t||r&&!o[l].once||s&&o[l].context!==s)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(js)),js.exports),qs=W(Ws);const Ys="1.6.14",zs={};function Xs(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 Qs(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 Js(e,t){let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i}function Zs(e,t){const i=t;let s=0;for(;Qs(e,t);){s+=10;s+=Js(e,t+6),Xs(e,t+10)&&(s+=10),t+=s}if(s>0)return e.subarray(i,i+s)}function er(e,t){return 255===e[t]&&240==(246&e[t+1])}function tr(e,t){return 1&e[t+1]?7:9}function ir(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function sr(e,t){return t+1<e.length&&er(e,t)}function rr(e,t){if(sr(e,t)){const i=tr(e,t);if(t+i>=e.length)return!1;const s=ir(e,t);if(s<=i)return!1;const r=t+s;return r===e.length||sr(e,r)}return!1}function nr(e,t,i,s,r){if(!e.samplerate){const n=function(e,t,i,s){const r=t[i+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(E.ERROR,E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[i+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let h=n;5!==a&&29!==a||(h-=3);const c=[a<<3|(14&h)>>1,(1&h)<<7|o<<3];return $.log(`manifest codec:${s}, parsed codec:${l}, channels:${o}, rate:${d} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:d,channelCount:o,codec:l,parsedCodec:l,manifestCodec:s}}(t,i,s,r);if(!n)return;x(e,n)}}function ar(e){return 9216e4/e}function or(e,t,i,s,r){const n=s+r*ar(e.samplerate),a=function(e,t){const i=tr(e,t);if(t+i<=e.length){const s=ir(e,t)-i;if(s>0)return{headerLength:i,frameLength:s}}}(t,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,d=Math.max(0,i+l-t.length);d?(o=new Uint8Array(l-r),o.set(t.subarray(i+r,t.length),0)):o=t.subarray(i+r,i+l);const h={unit:o,pts:n};return d||e.samples.push(h),{sample:h,length:l,missing:d}}const l=t.length-i;o=new Uint8Array(l),o.set(t.subarray(i,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function lr(e,t){return Qs(e,t)&&Js(e,t+6)+10<=e.length-t}function dr(e,t=0,i=1/0){return function(e,t,i,s){const r=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=(c=e,c&&c.buffer instanceof ArrayBuffer&&void 0!==c.byteLength&&void 0!==c.byteOffset?e.byteOffset:0),o=(a+e.byteLength)/n,l=(a+t)/n,d=Math.floor(Math.max(0,Math.min(l,o))),h=Math.floor(Math.min(d+Math.max(i,0),o));var c;return new s(r,d,h-d)}(e,t,i,Uint8Array)}function hr(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=e.data.subarray(1).indexOf(0);if(-1===i)return;const s=H(dr(e.data,1,i)),r=e.data[2+i],n=e.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=H(dr(e.data,3+i,n));let o;return o="--\x3e"===s?H(dr(e.data,4+i+n)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+i+n)),t.mimeType=s,t.pictureType=r,t.description=a,t.data=o,t}function cr(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=H(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const i=H(e.data.subarray(t),!0);t+=i.length+1;const s=H(e.data.subarray(t));return{key:e.type,info:i,data:s}}const t=H(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?hr(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const i=H(e.data.subarray(t),!0);t+=i.length+1;const s=H(e.data.subarray(t));return{key:e.type,info:i,data:s}}const t=H(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function ur(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Js(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}function fr(e){let t=0;const i=[];for(;Qs(e,t);){const s=Js(e,t+6);e[t+5]>>6&1&&(t+=10),t+=10;const r=t+s;for(;t+10<r;){const s=ur(e.subarray(t)),r=cr(s);r&&i.push(r),t+=s.size+10}Xs(e,t)&&(t+=10)}return i}function gr(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function mr(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),i=1&t[3];let s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}function pr(e){const t=fr(e);for(let e=0;e<t.length;e++){const i=t[e];if(gr(i))return mr(i)}}let yr=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 vr(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Tr{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=be(this.cachedData,e),this.cachedData=null);let i,s=Zs(e,0),r=s?s.length:0;const n=this._audioTrack,a=this._id3Track,o=s?pr(s):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&m(o))&&(this.basePTS=Er(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:yr.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=l}else lr(e,r)?(s=Zs(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:yr.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,i=r):r++;if(r===l&&i!==l){const t=e.slice(i);this.cachedData?this.cachedData=be(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:vr(),id3Track:a,textTrack:vr()}}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:vr(),id3Track:this._id3Track,textTrack:vr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Er=(e,t,i)=>{if(m(e))return 90*e;return 9e4*t+(i?9e4*i.baseTime/i.timescale:0)};let Sr=null;const Ar=[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],br=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Lr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Rr=[0,1,1,4];function Ir(e,t,i,s,r){if(i+24>t.length)return;const n=kr(t,i);if(n&&i+n.frameLength<=t.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function kr(e,t){const i=e[t+1]>>3&3,s=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Ar[14*(3===i?3-s:3===s?3:4)+r-1],d=br[3*(3===i?0:2===i?1:2)+n],h=3===o?1:2,c=Lr[i][s],u=Rr[s],f=8*c*u,g=Math.floor(c*l/d+a)*u;if(null===Sr){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Sr=e?parseInt(e[1]):0}return!!Sr&&Sr<=87&&2===s&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function Pr(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function wr(e,t){return t+1<e.length&&Pr(e,t)}function Dr(e,t){if(t+1<e.length&&Pr(e,t)){const i=4,s=kr(e,t);let r=i;null!=s&&s.frameLength&&(r=s.frameLength);const n=t+r;return n===e.length||wr(e,n)}return!1}const xr=(e,t)=>{let i=0,s=5;t+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=e[t];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,i=i?i<<o|r[0]:r[0],t+=1,s-=o}return i};class Cr extends Tr{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=_r(e,t,i,this.basePTS,this.frameIndex);if(-1!==s){return{sample:e.samples[e.samples.length-1],length:s,missing:0}}}static probe(e){if(!e)return!1;const t=Zs(e,0);if(!t)return!1;const i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==pr(t)&&xr(e,i)<16}}function _r(e,t,i,s,r){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>t.length)return-1;const d=t[i+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(t[i+6]<<8|t[i+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|c<<2|o>>4,o<<4&224]),p=s+r*(1536/a*9e4),y=t.subarray(i,i+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:y,pts:p}),l}const Mr=/\/emsg[-/]ID3/i;function Or(e,t){return m(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class Fr{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ei(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,zt)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);s.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t);let s=0;for(let t=32;t<e.length-16;t+=160,s+=16)i.set(e.subarray(t,t+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let t=32;t<e.length-16;t+=160,s+=16)e.set(i.subarray(s,s+16),t);return e}decryptAvcSample(e,t,i,s,r){const n=Pe(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),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)return void s();const r=e[t].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,s,n),this.decrypter.isSync())))return}}}}class Ur{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,s=this.VideoSample;if(s&&0!==s.units.length||(s=e[e.length-1]),null!=(t=s)&&t.units){const e=s.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const i=t.samples,s=i.length;if(!s)return void t.dropped++;{const t=i[s-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o,l,d,h=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(t,0),r=0,h=1);h<s;)if(o=t[h++],r)if(1!==r)if(o)if(1===o){if(l=h-r-1,c>=0){const e={data:t.subarray(c,l),type:u};a.push(e)}else{const i=this.getLastNalUnit(e.samples);i&&(n&&h<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=be(i.data,t.subarray(0,l)),i.state=0))}h<s?(d=this.getNALuType(t,h),c=h,u=d,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(c>=0&&r>=0){const e={data:t.subarray(c,s),type:u,state:r};a.push(e)}if(0===a.length){const i=this.getLastNalUnit(e.samples);i&&(i.data=be(i.data,t))}return e.naluState=r,a}}class Nr{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),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>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&&$.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,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){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 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Br extends Ur{parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 1:{let t=!1;n=!0;const r=s.data;if(o&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;if(t)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,ke(s.data,1,i.pts,t.samples);break;case 7:{var h,c;n=!0,o=!0;const t=s.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(h=e.pixelRatio)?void 0:h[0])!==i.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];const s=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:n=!0,e.pps=[s.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Nr(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i,s=8,r=8;for(let n=0;n<e;n++)0!==r&&(i=t.readEG(),r=(s+i+256)%256),s=0===r?s:r}readSPS(e){const t=new Nr(e);let i,s,r,n=0,a=0,o=0,l=0;const d=t.readUByte.bind(t),h=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),p=this.skipScalingList.bind(this);d();const y=d();if(h(5),f(3),d(),m(),100===y||110===y||122===y||244===y||44===y||83===y||86===y||118===y||128===y){const e=c();if(3===e&&f(1),m(),m(),f(1),u())for(s=3!==e?8:12,r=0;r<s;r++)u()&&p(r<6?16:64,t)}m();const v=c();if(0===v)c();else if(1===v)for(f(1),g(),g(),i=c(),r=0;r<i;r++)g();m(),f(1);const T=c(),E=c(),S=h(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let A=[1,1];if(u()&&u()){switch(d()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(T+1)-2*n-2*a),height:(2-S)*(E+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}class $r extends Ur{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var d;if(n=!0,o)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,ke(s.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=x(e.params,this.readVPS(s.data)),this.initVPS=s.data),e.vps=[s.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],s.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(s.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const i in t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,s.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(s.data);for(const i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,s.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s<e.byteLength;s++)s>=2&&3===e[s]&&0===e[s-1]&&0===e[s-2]||(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 Nr(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new Nr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),h=t.readUByte(),c=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),y=[],v=[];for(let e=0;e<i;e++)y.push(t.readBoolean()),v.push(t.readBoolean());if(i>0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e<i;e++)y[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[e]&&t.readUByte();t.readUEG();const T=t.readUEG();3==T&&t.skipBits(1);const E=t.readUEG(),S=t.readUEG(),A=t.readBoolean();let b=0,L=0,R=0,I=0;A&&(b+=t.readUEG(),L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG());const k=t.readUEG(),P=t.readUEG(),w=t.readUEG();for(let e=t.readBoolean()?0:i;e<=i;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++){if(t.readBoolean()){const i=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<i;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const D=t.readUEG();let x=0;for(let e=0;e<D;e++){let i=!1;if(0!==e&&(i=t.readBoolean()),i){e===D&&t.readUEG(),t.readBoolean(),t.readUEG();let i=0;for(let e=0;e<=x;e++){const e=t.readBoolean();let s=!1;e||(s=t.readBoolean()),(e||s)&&i++}x=i}else{const e=t.readUEG(),i=t.readUEG();x=e+i;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let e=0;e<i;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let i=0;i<e;i++){for(let e=0;e<w+4;e++)t.readBits(1);t.readBits(1)}}let C=0,_=1,M=1,O=!0,F=1,U=0;t.readBoolean(),t.readBoolean();let N=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(_=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(_=t.readBits(16),M=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(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(),N=t.readBoolean(),N&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG());if(t.readBoolean()){F=t.readBits(32),U=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),s=t.readBoolean();let r=!1;(e||s)&&(r=t.readBoolean(),r&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),r&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=i;n++){O=t.readBoolean();let i=!1;O||t.readBoolean()?t.readEG():i=t.readBoolean();const n=i?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(s)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),C=t.readUEG())}let B=E,$=S;if(A){let e=1,t=1;1===T?e=t=2:2==T&&(e=2),B=E-e*L-e*b,$=S-t*I-t*R}const V=s?["A","B","C"][s]:"",G=a<<24|o<<16|l<<8|d;let H=0;for(let e=0;e<32;e++)H=(H|(G>>e&1)<<31-e)>>>0;let K=H.toString(16);1===n&&"2"===K&&(K="6");return{codecString:`hvc1.${V}${n}.${K}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[h,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:P,min_spatial_segmentation_idc:C,chroma_format_idc:T,frame_rate:{fixed:O,fps:U/F}},width:B,height:$,pixelRatio:[_,M]}}readPPS(e){const t=new Nr(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 i=t.readBoolean(),s=t.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Vr=188;class Gr{constructor(e,t,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){const i=Gr.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){const t=e.length;let i=Math.min(940,t-Vr)+1,s=0;for(;s<i;){let r=!1,n=-1,a=0;for(let o=s;o<t;o+=Vr){if(71!==e[o]||t-o!==Vr&&71!==e[o+Vr]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,e.length-Vr)+1)),r||(r=0===Hr(e,o)),r&&a>1&&(0===n&&a>2||o+Vr>i))return n}s++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:oe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Gr.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=Gr.createTrack("audio",s),this._id3Track=Gr.createTrack("id3"),this._txtTrack=Gr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}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=!1,s=!1){let r;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,h=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(v=(e=be(this.remainderData,e)).length,this.remainderData=null),v<Vr&&!s)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const T=Math.max(0,Gr.syncOffset(e));v-=(v-T)%Vr,v<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,v,e.buffer.byteLength-v));let E=0;for(let t=T;t<v;t+=Vr)if(71===e[t]){const s=!!(64&e[t+1]),v=Hr(e,t);let E;if((48&e[t+3])>>4>1){if(E=t+5+e[t+4],E===t+Vr)continue}else E=t+4;switch(v){case d:s&&(h&&(r=Yr(h,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)),h={data:[],size:0}),h&&(h.data.push(e.subarray(E,t+Vr)),h.size+=t+Vr-E);break;case c:if(s){if(f&&(r=Yr(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(e.subarray(E,t+Vr)),f.size+=t+Vr-E);break;case u:s&&(g&&(r=Yr(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(E,t+Vr)),g.size+=t+Vr-E);break;case 0:s&&(E+=e[E]+1),y=this._pmtId=Kr(e,E);break;case y:{s&&(E+=e[E]+1);const r=jr(e,E,this.typeSupported,i,this.observer,this.logger);d=r.videoPid,d>0&&(n.pid=d,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),u=r.id3Pid,u>0&&(o.pid=u),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${T} to parse all TS packets.`),m=null,t=T-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=v}}else E++;E>0&&Wr(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=h,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return s&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:r}=e,n=i.pesData,a=t.pesData,o=s.pesData;let l;if(n&&(l=Yr(n,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,r,l,!0),i.pesData=null)):i.pesData=n,a&&(l=Yr(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Yr(o,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=o}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new Fr(this.observer,this.config,t);return this.decrypt(s,r)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new Br:"hevc"===e&&(this.videoParser=new $r))}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=e;s.samples&&"aac"===s.segmentCodec?t.decryptAacSamples(s.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let r,n,a,o=t.data;if(s){this.aacOverFlow=null;const t=s.missing,r=s.sample.unit.byteLength;if(-1===t)o=be(s.sample.unit,o);else{const n=r-t;s.sample.unit.set(o.subarray(0,t),n),e.samples.push(s.sample),i=s.missing}}for(r=i,n=o.length;r<n-1&&!sr(o,r);r++);if(r!==i){let e;const t=r<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",Wr(this.observer,new Error(e),t,this.logger),!t)return}if(nr(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=ar(e.samplerate);a=s.sample.pts+t}}let l,d=0;for(;r<n;){if(l=or(e,o,r,a,d),r+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;r<n-1&&!sr(o,r);r++);}}parseMPEGPES(e,t){const i=t.data,s=i.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<s;)if(wr(i,n)){const t=Ir(e,i,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const i=t.data,s=t.pts;if(void 0===s)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=i.length;let n,a=0,o=0;for(;o<r&&(n=_r(e,i,o,s,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=x({},t,{type:this._videoTrack?yr.emsg:yr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Hr(e,t){return((31&e[t+1])<<8)+e[t+2]}function Kr(e,t){return(31&e[t+10])<<8|e[t+11]}function jr(e,t,i,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=Hr(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!s){qr("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!s){qr("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){qr("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let s=t+5,r=l;for(;r>2;){if(106===e[s])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[s+1]+2;s+=t,r-=t}}break;case 194:case 135:return Wr(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=l+5}return a}function Wr(e,t,i,s){s.warn(`parsing error: ${t.message}`),e.emit(E.ERROR,E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function qr(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Yr(e,t){let i,s,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=be(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>e.size-6)return null;const d=i[7];192&d&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&d?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=i[8];let h=r+9;if(e.size<=h)return null;e.size-=h;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){i=l[e];let t=i.byteLength;if(h){if(h>t){h-=t;continue}i=i.subarray(h),t-=h,h=0}c.set(i,o),o+=t}return s&&(s-=r+3),{data:c,pts:n,dts:a,len:s}}return null}class zr{static getSilentFrame(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])}}}const Xr=Math.pow(2,32)-1;class Qr{static init(){let e;for(e in Qr.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Qr.types)Qr.types.hasOwnProperty(e)&&(Qr.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Qr.HDLR_TYPES={video:t,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Qr.STTS=Qr.STSC=Qr.STCO=r,Qr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Qr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Qr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Qr.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Qr.FTYP=Qr.box(Qr.types.ftyp,n,o,n,a),Qr.DINF=Qr.box(Qr.types.dinf,Qr.box(Qr.types.dref,s))}static box(e,...t){let i=8,s=t.length;const r=s;for(;s--;)i+=t[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]=255&i,n.set(e,4),s=0,i=8;s<r;s++)n.set(t[s],i),i+=t[s].byteLength;return n}static hdlr(e){return Qr.box(Qr.types.hdlr,Qr.HDLR_TYPES[e])}static mdat(e){return Qr.box(Qr.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(Xr+1)),s=Math.floor(t%(Xr+1));return Qr.box(Qr.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(e){return Qr.box(Qr.types.mdia,Qr.mdhd(e.timescale||0,e.duration||0),Qr.hdlr(e.type),Qr.minf(e))}static mfhd(e){return Qr.box(Qr.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Qr.box(Qr.types.minf,Qr.box(Qr.types.smhd,Qr.SMHD),Qr.DINF,Qr.stbl(e)):Qr.box(Qr.types.minf,Qr.box(Qr.types.vmhd,Qr.VMHD),Qr.DINF,Qr.stbl(e))}static moof(e,t,i){return Qr.box(Qr.types.moof,Qr.mfhd(e),Qr.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Qr.trak(e[t]);return Qr.box.apply(null,[Qr.types.moov,Qr.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(Qr.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Qr.trex(e[t]);return Qr.box.apply(null,[Qr.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Xr+1)),s=Math.floor(t%(Xr+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,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 Qr.box(Qr.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,r;for(s=0;s<t.length;s++)r=t[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Qr.box(Qr.types.sdtp,i)}static stbl(e){return Qr.box(Qr.types.stbl,Qr.stsd(e),Qr.box(Qr.types.stts,Qr.STTS),Qr.box(Qr.types.stsc,Qr.STSC),Qr.box(Qr.types.stsz,Qr.STSZ),Qr.box(Qr.types.stco,Qr.STCO))}static avc1(e){let t,i,s,r=[],n=[];for(t=0;t<e.sps.length;t++)i=e.sps[t],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(t=0;t<e.pps.length;t++)i=e.pps[t],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=Qr.box(Qr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return Qr.box(Qr.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Qr.box(Qr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Qr.box(Qr.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){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,255&t,0,0])}static mp4a(e){return Qr.box(Qr.types.mp4a,Qr.audioStsd(e),Qr.box(Qr.types.esds,Qr.esds(e)))}static mp3(e){return Qr.box(Qr.types[".mp3"],Qr.audioStsd(e))}static ac3(e){return Qr.box(Qr.types["ac-3"],Qr.audioStsd(e),Qr.box(Qr.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.mp4a(e));if("ac3"===t&&e.config)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.ac3(e));if("mp3"===t&&"mp3"===e.codec)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.avc1(e));if("hevc"===t&&e.vps)return Qr.box(Qr.types.stsd,Qr.STSD,Qr.hvc1(e))}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,r=e.height||0,n=Math.floor(i/(Xr+1)),a=Math.floor(i%(Xr+1));return Qr.box(Qr.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,255&s,0,0,r>>8&255,255&r,0,0]))}static traf(e,t){const i=Qr.sdtp(e),s=e.id,r=Math.floor(t/(Xr+1)),n=Math.floor(t%(Xr+1));return Qr.box(Qr.types.traf,Qr.box(Qr.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Qr.box(Qr.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Qr.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Qr.box(Qr.types.trak,Qr.tkhd(e),Qr.mdia(e))}static trex(e){const t=e.id;return Qr.box(Qr.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,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,r=12+16*s,n=new Uint8Array(r);let a,o,l,d,h,c;for(t+=8+r,n.set(["video"===e.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<s;a++)o=i[a],l=o.duration,d=o.size,h=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Qr.box(Qr.types.trun,n)}static initSegment(e){Qr.types||Qr.init();const t=Qr.moov(e);return be(Qr.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],s=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),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let r=s.length;for(let e=0;e<i.length;e+=1){r+=3;for(let t=0;t<i[e].length;t+=1)r+=2+i[e][t].length}const n=new Uint8Array(r);n.set(s,0),r=s.length;const a=i.length-1;for(let e=0;e<i.length;e+=1){n.set(new Uint8Array([32+e|(e===a?128:0),0,i[e].length]),r),r+=3;for(let t=0;t<i[e].length;t+=1)n.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),r),r+=2,n.set(i[e][t],r),r+=i[e][t].length}const o=Qr.box(Qr.types.hvcC,n),l=e.width,d=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return Qr.box(Qr.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,d>>8&255,255&d,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,Qr.box(Qr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Qr.box(Qr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}}Qr.types=void 0,Qr.HDLR_TYPES=void 0,Qr.STTS=void 0,Qr.STSC=void 0,Qr.STCO=void 0,Qr.STSZ=void 0,Qr.VMHD=void 0,Qr.SMHD=void 0,Qr.STSD=void 0,Qr.FTYP=void 0,Qr.DINF=void 0;function Jr(e,t,i=1,s=!1){const r=e*t*i;return s?Math.round(r):r}function Zr(e,t=!1){return Jr(e,1e3,1/9e4,t)}function en(e){const{baseTime:t,timescale:i,trackId:s}=e;return`${t/i} (${t}/${i}) trackId: ${s}`}let tn,sn=null,rn=null;function nn(e,t,i,s){return{duration:t,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class an extends M{constructor(e,t,i,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===sn){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);sn=e?parseInt(e[1]):0}if(null===rn){const e=navigator.userAgent.match(/Safari\/(\d+)/i);rn=e?parseInt(e[1]):0}}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?en(t):t} > ${e?en(e):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((e,s)=>{let r=s.pts,n=r-e;return n<-4294967296&&(t=!0,r=on(r,i),n=r-e),n>0?e:r},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,r,n,a,o){let l,d,h,c,u,f,g=r,m=r;const p=e.pid>-1,y=t.pid>-1,v=t.samples.length,T=e.samples.length>0,E=a&&v>0||v>1;if((!p||T)&&(!y||E)||this.ISGenerated||a){if(this.ISGenerated){var S,A,b,L;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(A=e.pixelRatio)?void 0:A[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(L=e.pixelRatio)?void 0:L[1]))||!e&&E||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,r,n));const i=this.isVideoContiguous;let s,a=-1;if(E&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${v} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,s=m}else-1===a&&(this.warn(`No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(T&&E){const i=this.getVideoStartPts(t.samples),s=(on(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,s),m+=Math.max(0,-s)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,r,n)),d=this.remuxAudio(e,g,this.isAudioContiguous,n,y||E||o===I?m:void 0),E){const s=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,m,i,s)}}else E&&(l=this.remuxVideo(t,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=ln(i,r,this._initPTS,this._initDTS)),s.samples.length&&(c=dn(s,r,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:c,id3:u}}computeInitPts(e,t,i,s){const r=Math.round(i*t);let n=on(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${s}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,i,s){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let d,h,c,u=!l||s,f="audio/mp4",g=-1;if(u&&(d=h=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Qr.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.id,c=e.inputTimeScale,l&&c===l.timescale?u=!1:d=h=this.computeInitPts(r[0].pts,c,i,"audio"))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Qr.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.id,c=t.inputTimeScale,l&&c===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=on(n[0].dts,e),s=this.computeInitPts(t,c,i,"video"),r=this.computeInitPts(e,c,i,"video");h=Math.min(h,s),d=Math.min(d,r)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${d/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${d/c} (${d}/${c}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:c,trackId:g},this._initDTS={baseTime:h,timescale:c,trackId:g}):d=c=void 0,{tracks:o,initPTS:d,timescale:c,trackId:g}}remuxVideo(e,t,i,s){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*r/l.timescale;let h,c,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,y=!1;if(!i||null===u){const e=d+t*r,s=n[0].pts-on(n[0].dts,n[0].pts);sn&&null!==u&&Math.abs(e-s-(u+d))<15e3?i=!0:u=e-s-d}const S=u+d;for(let e=0;e<o;e++){const t=n[e];t.pts=on(t.pts,S),t.dts=on(t.dts,S),t.dts<n[e>0?e-1:e].dts&&(y=!0)}y&&n.sort(function(e,t){const i=e.dts-t.dts,s=e.pts-t.pts;return i||s}),h=n[0].dts,c=n[n.length-1].dts;const A=c-h,b=A?Math.round(A/(o-1)):g||e.inputTimeScale/30;if(i){const i=h-S,s=i>b,r=i<-1;if((s||r)&&(s?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Zr(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Zr(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||S>=n[0].pts||sn)){h=S;const e=n[0].pts-i;if(s)n[0].dts=h,n[0].pts=e;else{let t=!0;for(let s=0;s<n.length&&!(n[s].dts>e&&t);s++){const e=n[s].pts;if(n[s].dts-=i,n[s].pts-=i,s<n.length-1){const i=n[s+1].pts;t=i<=n[s].pts==i<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${Zr(e,!0)}/${Zr(h,!0)}, delta: ${Zr(i,!0)} ms`)}}h=Math.max(0,h);let L=0,R=0,I=h;for(let e=0;e<o;e++){const t=n[e],i=t.units,s=i.length;let r=0;for(let e=0;e<s;e++)r+=i[e].data.length;R+=r,L+=s,t.length=r,t.dts<I?(t.dts=I,I+=b/4|0||1):I=t.dts,m=Math.min(t.pts,m),p=Math.max(t.pts,p)}c=n[o-1].dts;const k=R+4*L+8;let P;try{P=new Uint8Array(k)}catch(e){return void this.observer.emit(E.ERROR,E.ERROR,{type:v.MUX_ERROR,details:T.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:k,reason:`fail allocating video mdat ${k}`})}const w=new DataView(P.buffer);w.setUint32(0,k),P.set(Qr.types.mdat,4);let D=!1,C=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=n[e],i=t.units;let l,h=0;for(let e=0,t=i.length;e<t;e++){const t=i[e],s=t.data,r=t.data.byteLength;w.setUint32(f,r),f+=4,P.set(s,f),f+=r,h+=4+r}if(e<o-1)g=n[e+1].dts-t.dts,l=n[e+1].pts-t.pts;else{const i=this.config,a=e>0?t.dts-n[e-1].dts:b;if(l=e>0?t.pts-n[e-1].pts:b,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(i.maxBufferHole*r),n=(s?m+s*r:this.nextAudioTs+d)-t.pts;n>e?(g=n-a,g<0?g=a:D=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const c=Math.round(t.pts-t.dts);C=Math.min(C,g),M=Math.max(M,g),_=Math.min(_,l),O=Math.max(O,l),a.push(nn(t.key,g,h,c))}if(a.length)if(sn){if(sn<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(rn&&O-_<M-C&&b/M<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=h;for(let t=0,i=a.length;t<i;t++){const s=e+a[t].duration,r=e+a[t].cts;if(t<i-1){const e=s+a[t+1].cts;a[t].duration=e-r}else a[t].duration=t?a[t-1].duration:b;a[t].cts=0,e=s}}g=D||!g?b:g;const F=c+g;this.nextVideoTs=u=F-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const U={data1:Qr.moof(e.sequenceNumber++,h,x(e,{samples:a})),data2:P,startPTS:(m-d)/r,endPTS:(p+g-d)/r,startDTS:(h-d)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,U}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,i,s,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,d=this._initPTS,h="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=e.samples,g=h?0:8,m=this.nextAudioTs||-1;const p=d.baseTime*n/d.timescale,y=p+t*n;if(this.isAudioContiguous=i=i||f.length&&m>0&&(s&&Math.abs(y-(m+p))<9e3||Math.abs(on(f[0].pts,y)-(m+p))<20*l),f.forEach(function(e){e.pts=on(e.pts,y)}),!i||m<0){const e=f.length;if(f=f.filter(e=>e.pts>=0),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${p} / ${n})`),!f.length)return;m=0===r?0:s&&!u?Math.max(0,y-p):f[0].pts-p}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let i=0,s=m+p;i<f.length;i++){const r=f[i],a=r.pts,o=a-s,d=Math.abs(1e3*o/n);if(o<=-t*l&&u)0===i&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=m=a-p,s=a);else if(o>=t*l&&d<1e4&&u){let t=Math.round(o/l);for(s=a-t*l;s<0&&t&&l;)t--,s+=l;0===i&&(this.nextAudioTs=m=s-p),this.warn(`Injecting ${t} audio frames @ ${((s-p)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=zr.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),f.splice(i,0,{unit:t,pts:s}),s+=l,i++}}r.pts=s,s+=l}}let S,A=null,b=null,L=0,R=f.length;for(;R--;)L+=f[R].unit.byteLength;for(let t=0,s=f.length;t<s;t++){const s=f[t],r=s.unit;let n=s.pts;if(null!==b){c[t-1].duration=Math.round((n-b)/a)}else{if(i&&"aac"===e.segmentCodec&&(n=m+p),A=n,!(L>0))return;L+=g;try{S=new Uint8Array(L)}catch(e){return void this.observer.emit(E.ERROR,E.ERROR,{type:v.MUX_ERROR,details:T.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:L,reason:`fail allocating audio mdat ${L}`})}if(!h){new DataView(S.buffer).setUint32(0,L),S.set(Qr.types.mdat,4)}}S.set(r,g);const l=r.byteLength;g+=l,c.push(nn(!0,o,l,0)),b=n}const I=c.length;if(!I)return;const k=c[c.length-1];m=b-p,this.nextAudioTs=m+a*k.duration;const P=h?new Uint8Array(0):Qr.moof(e.sequenceNumber++,A/a,x({},e,{samples:c}));e.samples=[];const w=(A-p)/n,D=m/n,C={data1:P,data2:S,startPTS:w,endPTS:D,startDTS:w,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,C}}function on(e,t){let i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function ln(e,t,i,s){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let a=0;a<r;a++){const r=e.samples[a];r.pts=on(r.pts-i.baseTime*n/i.timescale,t*n)/n,r.dts=on(r.dts-s.baseTime*n/s.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function dn(e,t,i){const s=e.samples.length;if(!s)return;const r=e.inputTimeScale;for(let n=0;n<s;n++){const s=e.samples[n];s.pts=on(s.pts-i.baseTime*r/i.timescale,t*r)/r}e.samples.sort((e,t)=>e.pts-t.pts);const n=e.samples;return e.samples=[],{samples:n}}function hn(e,t,i=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(i?e.duration:0))/e.timescale:t}function cn(e,t,i){const s=e.codec;if(s&&s.length>4)return s;if(t===Q){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return Ve(s,!1)}return i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}return i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}try{tn=self.performance.now.bind(self.performance)}catch(e){tn=Date.now}const un=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const r=this.videoTrack=vr("video",1),n=this.audioTrack=vr("audio",1),a=this.txtTrack=vr("text",1);if(this.id3Track=vr("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=me(e);if(o.video){const{id:e,timescale:t,codec:i,supplemental:s}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=i,r.supplemental=s}if(o.audio){const{id:e,timescale:t,codec:i}=o.audio;n.id=e,n.timescale=t,n.codec=i}a.id=oe.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let i=0;i<t;){const s=he(e,i);if(s>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=s>1?i+s:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=be(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},i=fe(e,["moof"]);if(i.length<2)return t.remainder=e,t;const s=i[i.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}(i);this.remainderData=t.remainder,s.samples=t.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,t);return r.samples=Le(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=Le(e,t),{videoTrack:t,audioTrack:vr(),id3Track:s,textTrack:vr()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=fe(e.samples,["emsg"]);s&&s.forEach(e=>{const s=function(e){const t=e[0];let i="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(0===t){for(;"\0"!==le(e.subarray(d,d+1));)i+=le(e.subarray(d,d+1)),d+=1;for(i+=le(e.subarray(d,d+1)),d+=1;"\0"!==le(e.subarray(d,d+1));)s+=le(e.subarray(d,d+1)),d+=1;s+=le(e.subarray(d,d+1)),d+=1,r=he(e,12),n=he(e,16),o=he(e,20),l=he(e,24),d=28}else if(1===t){d+=4,r=he(e,d),d+=4;const t=he(e,d);d+=4;const n=he(e,d);for(d+=4,a=2**32*t+n,p(a)||(a=Number.MAX_SAFE_INTEGER,$.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=he(e,d),d+=4,l=he(e,d),d+=4;"\0"!==le(e.subarray(d,d+1));)i+=le(e.subarray(d,d+1)),d+=1;for(i+=le(e.subarray(d,d+1)),d+=1;"\0"!==le(e.subarray(d,d+1));)s+=le(e.subarray(d,d+1)),d+=1;s+=le(e.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(d,e.byteLength)}}(e);if(Mr.test(s.schemeIdUri)){const e=Or(s,t);let r=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=s.payload;i.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:yr.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=Or(s,t);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:e,pts:e,type:yr.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}},remux:class extends M{constructor(e,t,i,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;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.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:s}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=me(e);if(t)!function(e,t){if(!e||!t)return;const i=t.keyId;i&&t.isCommonEncryption&&Se(e,(e,t)=>{const s=e.subarray(8,24);s.some(e=>0!==e)||($.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${K(s)} -> ${K(i)}`),e.set(i,8))})}(e,t);else{const e=r||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}r&&(i=cn(r,Q,this)),n&&(s=cn(n,J,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,i,s,r,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};m(d)||(d=this.lastEndTime=r||0);const c=t.samples;if(!c.length)return h;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t,i){const s={},r=fe(e,["moof","traf"]);for(let e=0;e<r.length;e++){const n=r[e],a=fe(n,["tfhd"])[0],o=he(a,4),l=t[o];if(!l)continue;s[o]||(s[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=s[o],h=fe(n,["tfdt"])[0];if(h){const e=h[0];let t=he(h,4);1===e&&(t===ne?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=ne+1,t+=he(h,8))),m(t)&&(!m(d.start)||t<d.start)&&(d.start=t)}const c=l.default,u=he(a,0)|(null==c?void 0:c.flags);let f=(null==c?void 0:c.duration)||0;8&u&&(f=he(a,2&u?12:8));const g=fe(n,["trun"]);let p=d.start||0,y=0,v=f;for(let e=0;e<g.length;e++){const t=g[e],i=he(t,4),s=d.sampleCount;d.sampleCount+=i;const r=1&t[3],n=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],h=8&t[2];let c=8,u=i;for(r&&(c+=4),n&&i&&(1&t[c+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=s),c+=4,a?(v=he(t,c),c+=4):v=f,o&&(c+=4),h&&(c+=4),p+=v,y+=v,u--);u--;)a?(v=he(t,c),c+=4):v=f,o&&(c+=4),l&&(1&t[c+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(u+1),d.keyFrameStart=p),c+=4),h&&(c+=4),p+=v,y+=v;!y&&f&&(y+=f*i)}d.duration+=y}if(!Object.keys(s).some(e=>s[e].duration)){let t=1/0,i=0;const r=fe(e,["sidx"]);for(let e=0;e<r.length;e++){const s=ge(r[e]);if(null!=s&&s.references){t=Math.min(t,s.earliestPresentationTime/s.timescale);const e=s.references.reduce((e,t)=>e+t.info.duration||0,0);i=Math.max(i,e+s.earliestPresentationTime/s.timescale)}}i&&m(i)&&Object.keys(s).forEach(e=>{s[e].duration||(s[e].duration=i*s[e].timescale-s[e].start)})}return s}(c,f,this),p=f.audio?g[f.audio.id]:null,y=f.video?g[f.video.id]:null,v=hn(y,1/0),T=hn(p,1/0),E=hn(y,0,!0),S=hn(p,0,!0);let A=r,b=0;const L=p&&(!y||!l&&T<v||l&&l.trackId===f.audio.id),R=L?p:y;if(R){const e=R.timescale,t=R.start-r*e,i=L?f.audio.id:f.video.id;A=R.start/e,b=L?S-T:E-v,!n&&l||!function(e,t,i,s){if(null===e)return!0;const r=Math.max(s,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>r}(l,A,r,b)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${A-r} (${t}/${e}) trackId: ${i}`),l=null,u.initPTS=t,u.timescale=e,u.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):(u.timescale&&void 0!==u.trackId&&void 0!==u.initPTS||(this.warn("Could not set initPTS"),u.initPTS=A,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const I=A-l.baseTime/l.timescale,k=I+b;b>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const P=!!f.audio,w=!!f.video;let D="";P&&(D+="audio"),w&&(D+="video");const x={data1:c,startPTS:I,startDTS:I,endPTS:k,endDTS:k,type:D,hasAudio:P,hasVideo:w,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};h.audio=P&&!w?x:void 0,h.video=w?x:void 0;const C=null==y?void 0:y.sampleCount;if(C){const e=y.keyFrameIndex,t=-1!==e;x.nb=C,x.dropped=0===e||this.isVideoContiguous?0:t?e:C,x.independent=t,x.firstKeyFrame=e,t&&y.keyFrameStart&&(x.firstKeyFramePTS=(y.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),x.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${C} dropped: ${x.dropped} start: ${x.firstKeyFramePTS||"NA"}`)}return h.initSegment=u,h.id3=ln(i,r,l,l),s.samples.length&&(h.text=dn(s,r,l)),h}}},{demux:Gr,remux:an},{demux:class extends Tr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Zs(e,0);let s=(null==i?void 0:i.length)||0;if(Dr(e,s))return!1;for(let i=e.length;s<i;s++)if(rr(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&er(e,t)&&ir(e,t)<=e.length-t}(e,t)}appendFrame(e,t,i){nr(e,this.observer,t,i,e.manifestCodec);const s=or(e,t,i,this.basePTS,this.frameIndex);if(s&&0===s.missing)return s}},remux:an},{demux:class extends Tr{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=Zs(e,0);let i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==pr(t)&&xr(e,i)<=16)return!1;for(let t=e.length;i<t;i++)if(Dr(e,i))return $.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return Pr(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,i){if(null!==this.basePTS)return Ir(e,t,i,this.basePTS,this.frameIndex)}},remux:an}];un.splice(2,0,{demux:Cr,remux:an});class fn{constructor(e,t,i,s,r,n){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=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const r=i.transmuxing;r.executeStart=tn();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=s||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:y,initSegmentData:S}=o,A=function(e,t){let i=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(n,t);if(A&&Li(A.method)){const e=this.getDecrypter(),t=Ri(A.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,A.key.buffer,A.iv.buffer,t).then(e=>{const t=this.push(e,null,i);return this.decryptionPromise=null,t}),this.decryptionPromise;{let s=e.softwareDecrypt(n,A.key.buffer,A.iv.buffer,t);if(i.part>-1){const t=e.flush();s=t?t.buffer:t}if(!s)return r.executeEnd=tn(),gn(i);n=new Uint8Array(s)}}const b=this.needsProbing(d,h);if(b){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=tn(),gn(i)}(d||h||f||b)&&this.resetInitSegment(S,g,m,y,t),(d||f||b)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const L=this.transmux(n,A,u,c,i);this.asyncResult=mn(L);const R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,r.executeEnd=tn(),L}flush(e){const t=e.transmuxing;t.executeStart=tn();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=s;if(i){const t=i.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=tn();const i=[gn(e)];return this.asyncResult?Promise.resolve(i):i}const d=o.flush(a);return mn(d)?(this.asyncResult=!0,d.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,d,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===R?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=tn()}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,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,i,s),a.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,r){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,s,r):this.transmuxUnencrypted(e,i,s,r),n}transmuxUnencrypted(e,t,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer.demuxSampleAes(e,t,i).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;let r;for(let t=0,i=un.length;t<i;t++){var n;if(null!=(n=un[t].demux)&&n.probe(e,this.logger)){r=un[t];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,d=r.demux;o&&o instanceof l||(this.remuxer=new l(i,t,s,this.logger)),a&&a instanceof d||(this.demuxer=new d(i,t,s,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ei(this.config)),e}}const gn=e=>({remuxResult:{},chunkMeta:e});function mn(e){return"then"in e&&e.then instanceof Function}class pn{constructor(e,t,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class yn{constructor(e,t,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}let vn=0;class Tn{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=vn++,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=e=>{const t=e.data,i=this.hls;if(i&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var s;const e=null==(s=this.workerContext)?void 0:s.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===E.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new qs,this.observer.on(E.FRAG_DECRYPTED,n),this.observer.on(E.ERROR,n);const a=je(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(i.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=zs[e];if(t)return t.clientCount++,t;const i=new self.URL(e,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return zs[e]=s,s}(r.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=zs[Ys];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return zs[Ys]=s,s}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:ht(r)})}catch(s){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new fn(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new fn(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=vn++;const t=this.hls.config,i=je(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:ht(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=zs[e||Ys];if(t&&1===t.clientCount--){const{worker:i,objectURL:s}=t;delete zs[e||Ys],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.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,r,n,a,o,l,d){var h,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,y=!(p&&r.cc===p.cc),v=!(p&&l.level===p.level),T=p?l.sn-p.sn:-1,E=this.part?l.part-this.part.index:-1,S=0===T&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),A=!v&&(1===T||0===T&&(1===E||S&&E<=0)),b=self.performance.now();(v||T||0===r.stats.parsing.start)&&(r.stats.parsing.start=b),!n||!E&&A||(n.stats.parsing.start=b);const L=!(p&&(null==(h=r.initSegment)?void 0:h.url)===(null==(c=p.initSegment)?void 0:c.url)),I=new yn(y,A,o,v,g,L);if(!A||y||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===R?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${y}\n trackSwitch: ${v}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${L}`);const e=new pn(i,s,t,a,d);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,m,l,I);mn(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}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 t=i.flush(e);mn(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.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(e=>{this.handleTransmuxComplete(e)}),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)}}class En extends M{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(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=null==t?void 0:t.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=i;break}a===e.substring(0,a.length)&&(r=i)}if(-1!==r){const e=s[r],n=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=i&&nt(i);return new at(n,a>=0?a:void 0,o)}}}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(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;s.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==s.appliedTimelineOffset){const e=Math.max(o||0,0);s.appliedTimelineOffset=e,s.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(s.live||null!=i&&i.live){const o="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){hs(i,s,this);const e=s.playlistParsingError;if(e){this.warn(e);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void i.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:T.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=s.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=r.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,c=gs(s,1e3*(s.edge-h));if(s.requestScheduled+c<n?s.requestScheduled=n:s.requestScheduled+=c,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let u,f,g;if(s.canBlockReload&&s.endSN&&s.advanced){const e=this.hls.config.lowLatencyMode,r=s.lastPartSn,a=s.endSN,l=s.lastPartIndex,d=r===a;-1!==l?d?(f=a+1,g=e?0:l):(f=r,g=e?l+1:s.maxPartIndex):f=a+1;const h=s.age,c=h+s.ageHeader;let m=Math.min(c-s.partTarget,1.5*s.targetduration);if(m>0){if(c>3*s.targetduration)this.log(`Playlist last advanced ${h.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=i&&i.tuneInGoal&&c-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${m} with playlist age: ${s.age}`),m=0;else{const e=Math.floor(m/s.targetduration);if(f+=e,void 0!==g){g+=Math.round(m%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${m} skip sn ${e} to part ${g}`)}s.tuneInGoal=m}if(u=this.getDeliveryDirectives(s,t.deliveryDirectives,f,g),e||!d)return s.requestScheduled=n,void this.loadingPlaylist(o,u)}else(s.canBlockReload||s.canSkipUntil)&&(u=this.getDeliveryDirectives(s,t.deliveryDirectives,f,g));u&&void 0!==f&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=s.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,s){let r=nt(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=it),new at(i,s,r)}checkRetry(e){const t=e.details,i=Lt(e),s=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===Ot||!s.resolved&&r===_t);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Pt(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,s.resolved=!0}return o}}function Sn(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!An(e[i].attrs,t[i].attrs))return!1;return!0}function An(e,t,i){const s=e["STABLE-RENDITION-ID"];return s&&!i?s===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>e[i]!==t[i])}function bn(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class Ln{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(null===this.queues||null===this.tracks)return;const s=this.queues[t];s.push(e),1!==s.length||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(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(t){var i;if(s.onError(t),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[e])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=null==(t=this.tracks)?void 0:t[e],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}const Rn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,In="HlsJsTrackRemovedError";class kn extends Error{constructor(e){super(e),this.name=In}}function Pn(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function wn(e){return"audio"===e?1:0}class Dn{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){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){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&m(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){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}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((t,i)=>this.isLevelAllowed(t)&&i<=e);return this.clientRect=null,Dn.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;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.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;const s=(e,t)=>!t||(e.width!==t.width||e.height!==t.height);let r=e.length-1;const n=Math.max(t,i);for(let t=0;t<e.length;t+=1){const i=e[t];if((i.width>=n||i.height>=n)&&s(i,e[t+1])){r=t;break}}return r}}const xn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Cn={HLS:"h"};class _n{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof _n?e:new _n(e))),this.value=e,this.params=t}}function Mn(e,t,i,s){return new Error(`failed to ${e} "${r=t,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${i}`,{cause:s});var r}function On(e,t,i){return Mn("serialize",e,t,i)}class Fn{constructor(e){this.description=e}}const Un="Bare Item";function Nn(e){if(!1===ArrayBuffer.isView(e))throw On(e,"Byte Sequence");return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function Bn(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw On(e,"Integer");return e.toString()}function $n(e,t){if(e<0)return-$n(-e,t);const i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){const t=Math.floor(e*i);return(t%2==0?t:t+1)/i}return Math.round(e*i)/i}function Vn(e){const t=$n(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw On(e,"Decimal");const i=t.toString();return i.includes(".")?i:`${i}.0`}const Gn=/[\x00-\x1f\x7f]+/;function Hn(e){const t=(i=e).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw On(t,"Token");return t}function Kn(e){switch(typeof e){case"number":if(!m(e))throw On(e,Un);return Number.isInteger(e)?Bn(e):Vn(e);case"string":return function(e){if(Gn.test(e))throw On(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Hn(e);case"boolean":return function(e){if("boolean"!=typeof e)throw On(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Bn(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return Nn(e);if(e instanceof Fn)return Hn(e);default:throw On(e,Un)}}function jn(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw On(e,"Key");return e}function Wn(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${jn(e)}`:`;${jn(e)}=${Kn(t)}`).join("")}function qn(e){return e instanceof _n?`${Kn(e.value)}${Wn(e.params)}`:Kn(e)}function Yn(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw On(e,"Dict");const i=e instanceof Map?e.entries():Object.entries(e),s=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map(([e,t])=>{t instanceof _n==!1&&(t=new _n(t));let i=jn(e);var s;return!0===t.value?i+=Wn(t.params):(i+="=",Array.isArray(t.value)?i+=`(${(s=t).value.map(qn).join(" ")})${Wn(s.params)}`:i+=qn(t)),i}).join(`,${s}`)}function zn(e,t){return Yn(e,t)}const Xn="CMCD-Object",Qn="CMCD-Request",Jn="CMCD-Session",Zn="CMCD-Status",ea={br:Xn,ab:Xn,d:Xn,ot:Xn,tb:Xn,tpb:Xn,lb:Xn,tab:Xn,lab:Xn,url:Xn,pb:Qn,bl:Qn,tbl:Qn,dl:Qn,ltc:Qn,mtp:Qn,nor:Qn,nrr:Qn,rc:Qn,sn:Qn,sta:Qn,su:Qn,ttfb:Qn,ttfbb:Qn,ttlb:Qn,cmsdd:Qn,cmsds:Qn,smrt:Qn,df:Qn,cs:Qn,ts:Qn,cid:Jn,pr:Jn,sf:Jn,sid:Jn,st:Jn,v:Jn,msd:Jn,bs:Zn,bsd:Zn,cdn:Zn,rtp:Zn,bg:Zn,pt:Zn,ec:Zn,e:Zn},ta=Qn;function ia(e,t){const i={};if(!e)return i;const s=Object.keys(e),r=t?(n=t,Object.keys(n).reduce((e,t)=>{var i;return null===(i=n[t])||void 0===i||i.forEach(i=>e[i]=t),e},{})):{};var n;return s.reduce((t,i)=>{var s;const n=ea[i]||r[i]||ta;return(null!==(s=t[n])&&void 0!==s?s:t[n]={})[i]=e[i],t},i)}const sa="event";const ra=e=>Math.round(e),na=(e,t)=>Array.isArray(e)?e.map(e=>na(e,t)):e instanceof _n&&"string"==typeof e.value?new _n(na(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){const i=new URL(e),s=new URL(t);if(i.origin!==s.origin)return e;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),aa=e=>100*ra(e/100),oa={br:ra,d:ra,bl:aa,dl:aa,mtp:aa,nor:(e,t)=>{let i=e;return t.version>=2&&(e instanceof _n&&"string"==typeof e.value?i=new _n([e]):"string"==typeof e&&(i=[e])),na(i,t)},rtp:aa,tb:ra},la="request",da="response",ha=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],ca=["e"],ua=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function fa(e){return ua.test(e)}const ga=["d","dl","nor","ot","rtp","su"];const ma=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const pa=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ya(e){return pa.includes(e)||fa(e)}const va={[da]:function(e){return ha.includes(e)||ga.includes(e)||ma.includes(e)||fa(e)},[sa]:function(e){return ha.includes(e)||ca.includes(e)||fa(e)},[la]:function(e){return ha.includes(e)||ga.includes(e)||fa(e)}};function Ta(e,t={}){const i={};if(null==e||"object"!=typeof e)return i;const s=t.version||e.v||1,r=t.reportingMode||la,n=1===s?ya:va[r];let a=Object.keys(e).filter(n);const o=t.filter;"function"==typeof o&&(a=a.filter(o));const l=r===da||r===sa;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const d=x({},oa,t.formatters),h={version:s,reportingMode:r,baseUrl:t.baseUrl};return a.sort().forEach(t=>{let r=e[t];const n=d[t];if("function"==typeof n&&(r=n(r,h)),"v"===t){if(1===s)return;r=s}"pr"==t&&1===r||(l&&"ts"===t&&!m(r)&&(r=Date.now()),function(e){return"number"==typeof e?m(e):null!=e&&""!==e&&!1!==e}(r)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof r&&(r=new Fn(r)),i[t]=r))}),i}function Ea(e,t,i){return x(e,function(e,t={}){const i={};if(!e)return i;const s=ia(Ta(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(s).reduce((e,[t,i])=>{const s=zn(i,{whitespace:!1});return s&&(e[t]=s),e},i)}(t,i))}function Sa(e,t={}){if(!e)return"";const i=function(e,t={}){return e?zn(Ta(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(i)}const Aa=/CMCD=[^&#]+/;function ba(e,t,i){const s=function(e,t={}){return e?`CMCD=${Sa(e,t)}`:""}(t,i);if(!s)return e;if(Aa.test(e))return e.replace(Aa,s);const r=e.includes("?")?"&":"?";return`${e}${r}${s}`}function La(e,t,i,s){e&&Object.keys(t).forEach(r=>{const n=e.filter(e=>e.groupId===r).map(e=>{const n=x({},e);return n.details=void 0,n.attrs=new yi(n.attrs),n.url=n.attrs.URI=Ra(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=s,n});e.push(...n)})}function Ra(e,t,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(e=>{e&&l.searchParams.set(e,n[e])}),l.href}class Ia extends M{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Ia.CDMCleanupPromise?[Ia.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{const{initDataType:t,initData:i}=e,s=`"${e.type}" event: init data type: "${t}"`;if(this.debug(s),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Ni(this.config));const t=e.map(Ui).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(r=>{const n=Fi(r);if("sinf"!==t||n!==xi.FAIRPLAY)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);let a;try{const e=le(new Uint8Array(i)),t=Ae(Ii(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24))}catch(e){return void this.warn(`${s} Failed to parse sinf: ${e}`)}const o=K(a),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this;let h=l[o];for(let e=0;e<d.length;e++){const s=d[e],r=s.decryptdata;if(!r.keyId)continue;const n=K(r.keyId);if(Ai(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(o)){if(h=l[n],!h)continue;if(r.pssh)break;delete l[n],r.pssh=new Uint8Array(i),r.keyId=a,h=l[o]=h.then(()=>this.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-key-match")),h.catch(e=>this.handleError(e));break}}h||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.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=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(E.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(E.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=null==t?void 0:t[e];return s?s.licenseUrl:e===xi.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=null==t?void 0:t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,s=t.map(e=>e.audioCodec).filter(i),r=t.map(e=>e.videoCodec).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise((t,i)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,s,r).then(e=>t({keySystem:a,mediaKeys:e})).catch(t=>{e.length?n(e):i(t instanceof wa?t:new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};n(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Bi&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){var s;const r=function(e,t,i,s){let r;switch(e){case xi.FAIRPLAY:r=["cenc","sinf"];break;case xi.WIDEVINE:case xi.PLAYREADY:r=["cenc"];break;case xi.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,s){return[{initDataTypes:e,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}(r,t,i,s)}(e,t,i,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],a=null==(s=n)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ht(r)}`),a=this.requestMediaKeySystemAccess(e,r);const t=n=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const r=t.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,s.then(t=>t?this.setMediaKeysServerCertificate(i,e,t):i)));return r.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${K(e.keyId||[])} keyUri: ${e.uri}`);const s=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=ka(t),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${K(e.decryptdata.keyId||[])}\n } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Ui(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{const s=Ui(e);s?t(s):i(new Error(`Unable to find format for key-system "${e}"`))}).catch(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=Ni(this.config),i=e.map(Fi).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(i)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){const s=Pa(e,t[i]);if(s)return s}}loadKey(e){const t=e.keyInfo.decryptdata,i=ka(t),s=this.bannedKeyIds[i];if(s||"internal-error"===this.getKeyStatus(t)){const i=Da(s||"internal-error",t);return this.handleError(i,e.frag),Promise.reject(i)}const r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[i];if(!n){const s=this.getKeySystemForKeyPromise(t).then(({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t}))))).then(e=>{const i=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")});return s.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[i]=s,s}return n.catch(i=>{if(i instanceof wa){const s=_({},i.data);"internal-error"===this.getKeyStatus(t)&&(s.decryptdata=t);const r=new wa(s,i.message);this.handleError(r,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof wa){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${K(i.keyId||[])})`:""}`),this.hls.trigger(E.ERROR,e.data)}else this.error(e.message),this.hls.trigger(E.ERROR,{type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=ka(e),i=this.keyIdToKeySessionPromise[t];if(!i){const t=Fi(e.keyFormat),i=t?[t]:Ni(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Ni(this.config)),0===e.length)throw new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ht({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}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((e,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(i)}}));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(e=>-1===i.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,i,s){var r;const n=null==(r=this.config.drmSystems)||null==(r=r[e.keySystem])?void 0:r.generateRequest;if(n)try{const s=n.call(this.hls,t,i,e);if(!s)throw new Error("Invalid response from configured generateRequest filter");t=s.initDataType,i=s.initData?s.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const a=ka(e.decryptdata),o=e.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${a} URI: ${o} (init data type: ${t} length: ${i.byteLength})`);const l=new qs,d=e._onmessage=t=>{const i=e.mediaKeysSession;if(!i)return void l.emit("error",new Error("invalid state"));const{messageType:s,message:r}=t;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(e,r).catch(e=>{l.eventNames().length?l.emit("error",e):this.handleError(e)}):"license-release"===s?e.keySystem===xi.FAIRPLAY&&this.updateKeySession(e,ki("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${s}"`)},h=(e,t)=>{let i;t.keyStatus=e,e.startsWith("usable")?l.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=Da(e,t.decryptdata):"expired"===e?i=new Error(`key expired (keyId: ${a})`):"released"===e?i=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${a})`),i&&(l.eventNames().length?l.emit("error",i):this.handleError(i))},c=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const i=this.getKeyStatuses(e);if(!Object.keys(i).some(e=>"status-pending"!==i[e]))return;if("expired"===i[a])return this.log(`Expired key ${ht(i)} in key-session "${e.mediaKeysSession.sessionId}"`),void this.renewKeySession(e);let s=i[a];if(s)h(s,e);else{var r;const t=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(r=e.keyStatusTimeouts)[a]||(r[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const i=this.getKeyStatus(e.decryptdata);if(i&&"status-pending"!==i)return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${i} from other session.`),h(i,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),s="internal-error",h(s,e)},t)),this.log(`No status for keyId ${a} (${ht(i)}).`)}};Is(e.mediaKeysSession,"message",d),Is(e.mediaKeysSession,"keystatuseschange",c);const u=new Promise((e,t)=>{l.on("error",t),l.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(t=>{throw new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>u).catch(t=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((i,s)=>{if("string"==typeof s&&"object"==typeof i){const e=s;s=i,i=e}const r="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);e.keySystem===xi.PLAYREADY&&16===r.length&&Pi(r);const n=K(r);"internal-error"===i&&(this.bannedKeyIds[n]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=i}),t}fetchServerCertificate(e){const t=this.config,i=new(0,t.loader)(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((r,n)=>{const a={responseType:"arraybuffer",url:s},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,i,s)=>{r(e.data)},onError:(t,i,r,o)=>{n(new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:_({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${s}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,r)=>{n(new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(e,t,i)=>{n(new Error("aborted"))}};i.load(a,l,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,r)=>{e.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(e=>{r(new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,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"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let t;for(let i=0,s=r.length;i<s;i++){var n,a;t=r[i];const s=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;s&&o&&e.setRequestHeader(s,o)}}const o=s.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ki(atob(l))}setupLicenseXHR(e,t,i,s){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,s)}).catch(n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,i,s)}).then(i=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:i||s}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((s,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,a,n,e)}catch(e){this.error(e)}s(t)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new wa({type:v.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(s,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then(({xhr:t,licenseChallenge:i})=>{e.keySystem==xi.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,Is(i,"encrypted",this.onMediaEncrypted),Is(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(ks(e,"encrypted",this.onMediaEncrypted),ks(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};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,Hi.clearKeyUriToKeyIdMap();const r=s.length;Ia.CDMCleanupPromise=Promise.all(s.map(e=>this.removeSession(e)).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i,decryptdata:s}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${K((null==s?void 0:s.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(e=>self.clearTimeout(n[e]));const{drmSystemOptions:a}=this.config,o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(e=>"persistent-license"===e)))}(a)?new Promise((e,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(i)}):Promise.resolve();return o.catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function ka(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return K(e.keyId)}function Pa(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}Ia.CDMCleanupPromise=void 0;class wa extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Da(e,t){const i="output-restricted"===e,s=i?T.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:T.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new wa({type:v.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:t},i?"HDCP level output restricted":`key status changed to "${e}"`)}function xa(e,t){let i;try{i=new Event("addtrack")}catch(e){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function Ca(e,t){const i=e.mode;if("disabled"===i&&(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: ${t}`)}catch(i){$.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){$.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function _a(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===i&&(e.mode=i)}function Ma(e,t,i,s){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,i){const s=[],r=function(e,t){if(t<=e[0].startTime)return 0;const i=e.length-1;if(t>e[i].endTime)return-1;let s,r=0,n=i;for(;r<=n;)if(s=Math.floor((n+r)/2),t<e[s].startTime)n=s-1;else{if(!(t>e[s].startTime&&r<i))return s;r=s+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(e.cues,t,i);for(let t=0;t<r.length;t++)s&&!s(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function Oa(e){const t=[];for(let i=0;i<e.length;i++){const s=e[i];"subtitles"!==s.kind&&"captions"!==s.kind||!s.label||t.push(e[i])}return t}function Fa(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}const Ua=.025;let Na=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Ba(e,t,i){return`${e.identifier}-${i+1}-${Fa(t)}`}class $a{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,null==(e=this.assetListLoader)||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;if(e<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(t=this.assetList[e])?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 Va(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-Va(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=m(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 Va(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Ua))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration: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"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Na.Range:Na.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}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||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function Va(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Ua)?t.start:t.start+t.duration}function Ga(e,t,i){const s=new self.URL(e,i);return"data:"!==s.protocol&&s.searchParams.set("_HLS_primary_id",t),s}function Ha(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function Ka(e){const t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}class ja{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(E.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(E.LEVEL_LOADED,n),r.once(E.AUDIO_TRACK_LOADED,n),r.once(E.SUBTITLE_TRACK_LOADED,n),r.on(E.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(E.BUFFER_APPENDED,()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,r.trigger(E.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=Ga(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,r=di.bufferInfo(e,s,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=di.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(null==(e=this.hls)?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(){var e;this.mediaAttached&&(null!=(e=this.hls)&&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(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;null==(s=this.hls)||s.on(e,t)}once(e,t,i){var s;null==(s=this.hls)||s.once(e,t)}off(e,t,i){var s;null==(s=this.hls)||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Ka(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class Wa extends M{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]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(t&&"primary"!==t&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return s}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){const e=i[s].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return s}return-1}findEventIndex(e){const t=this.items;if(t)for(let s=t.length;s--;){var i;if((null==(i=t[s].event)?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){const i=e.assetList,s=i.length;if(s>1)for(let e=0;e<s;e++){const r=i[e];if(!r.error){const i=r.timelineStart;if(t===i||t>i&&(t<i+(r.duration||0)||e===s-1))return e}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,i=e[e.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:s}=i,r=this.events,n=this.parseDateRanges(s,{url:i.url},t),a=Object.keys(s),o=r?r.filter(e=>!a.includes(e.identifier)):[];n.length&&n.sort((e,t)=>{const i=e.cue.pre,s=e.cue.post,r=t.cue.pre,n=t.cue.post;if(i&&!r)return-1;if(r&&!i)return 1;if(s&&!n)return 1;if(n&&!s)return-1;if(!(i||r||s||n)){const i=e.startTime,s=t.startTime;if(i!==s)return i-s}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=n,o.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],i=!1){const s=this.events||[];if(s.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(s,e);(i||t.length||(null==r?void 0:r.length)!==n.length||n.some((e,t)=>Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const s=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new $a(o,t),this.eventMap[a]=e,!1===i&&(e.appendInPlace=i)),s.push(e)}}return s}parseSchedule(e,t){const i=[],s=t.main.details,r=s.live?1/0:s.edge;let n=0;if((e=e.filter(e=>!(e.error||e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let s=0,o=0;if(e.forEach((t,a)=>{const l=t.cue.pre,d=t.cue.post,h=e[a-1]||null,c=t.appendInPlace,u=d?r:t.startOffset,f=t.duration,g=t.timelineOccupancy===Na.Range?f:0,m=t.resumptionOffset,p=(null==h?void 0:h.startTime)===u,y=u+t.cumulativeDuration;let v=c?y+f:u+m;if(l||!d&&u<=0){const e=o;o+=g,t.timelineStart=y;const s=n;n+=f,i.push({event:t,start:y,end:v,playout:{start:s,end:n},integrated:{start:e,end:o}})}else{if(!(u<=r))return;{if(!p){const r=u-s;if(r>.033){const l=s,d=o;o+=r;const h=n;n+=r;const c={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+r,playout:{start:h,end:n},integrated:{start:d,end:o}};i.push(c)}else r>0&&h&&(h.cumulativeDuration+=r,i[i.length-1].end=u)}d&&(v=y),t.timelineStart=y;const r=o;o+=g;const l=n;n+=f,i.push({event:t,start:y,end:v,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const T=t.resumeTime;s=d||T>r?r:T}),s<r){var a;const e=s,t=o,l=r-s;o+=l;const d=n;n+=l,i.push({previousEvent:(null==(a=i[i.length-1])?void 0:a.event)||null,nextEvent:null,start:s,end:e+l,playout:{start:d,end:n},integrated:{start:t,end:o}})}this.setDurations(r,n,o)}else{const e=0;i.push({previousEvent:null,nextEvent:null,start:e,end:r,playout:{start:e,end:r},integrated:{start:e,end:r}}),this.setDurations(r,r,r)}return i}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 r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,h=l?0:d?s:a.startTime;this.updateAssetDurations(a);if(n===h?a.cumulativeDuration=r:(r=0,n=h),!d&&a.snapOptions.in&&(a.resumeAnchor=Et(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const c=m(a.resumeOffset)?a.resumeOffset:a.duration;r+=c})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,s=e.startTime+e.resumptionOffset;if(Math.abs(i-s)>Ua)return this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1;return!Object.keys(t).some(s=>{const r=t[s].details,n=r.edge;if(i>=n)return this.log(`"${e.identifier}" resumption ${i} past ${s} playlist end ${n}`),!1;const a=Et(null,r.fragments,i);if(!a)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===s?.175:0;return!(Math.abs(a.start-i)<Ua+o||Math.abs(a.end-i)<Ua+o)&&(this.log(`"${e.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}e.duration=s&&!r?Math.max(i,e.duration):i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function qa(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class Ya{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=Ga(i,this.hls.sessionId,e.baseUrl)}catch(t){const s=this.assignAssetListError(e,T.ASSET_LIST_LOAD_ERROR,t,i);return void this.hls.trigger(E.ERROR,s)}t&&"data:"!==s.protocol&&s.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:s.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,i,s,r)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const t=this.assignAssetListError(e,T.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,r);return void this.hls.trigger(E.ERROR,t)}e.assetListResponse=n,this.hls.trigger(E.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:r})},onError:(t,i,s,r)=>{const n=this.assignAssetListError(e,T.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,r,s);this.hls.trigger(E.ERROR,n)},onTimeout:(t,i,s)=>{const r=this.assignAssetListError(e,T.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,s);this.hls.trigger(E.ERROR,r)}};return n.load(a,l,d),this.hls.trigger(E.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,i,s,r,n){return e.error=i,{type:v.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:n,stats:r}}}function za(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function Xa(e,t){return`[${e}] Advancing timeline position to ${t}`}class Qa{constructor(e){this.buffered=void 0;const t=(t,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}const Ja={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},Za=e=>String.fromCharCode(Ja[e]||e),eo=15,to=100,io={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},so={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ro={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},no={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ao=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class oo{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i="function"==typeof t?t():t;$.log(`${this.time} [${e}] ${i}`)}}}const lo=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class ho{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class co{constructor(){this.uchar=" ",this.penState=new ho}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class uo{constructor(e){this.chars=[],this.pos=0,this.currPenState=new ho,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<to;e++)this.chars.push(new co);this.logger=e}equals(e){for(let t=0;t<to;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<to;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<to;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>to&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=to)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].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=Za(e);this.pos>=to?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<to;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<to;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 fo{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<eo;t++)this.rows.push(new uo(e));this.logger=e}reset(){for(let e=0;e<eo;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<eo;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<eo;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<eo;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 = "+ht(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<eo;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[e].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[t-this.nrRollUpRows+s+1].copy(i.rows[e+s])}}this.currRow=t;const i=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,s=Math.max(t-1,0);i.setCursor(e.indent),e.color=i.chars[s].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 = "+ht(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const 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 i=0;i<eo;i++){const r=this.rows[i].getTextString();r&&(s=i+1,e?t.push("Row "+s+": '"+r+"'"):t.push(r.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class go{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 fo(i),this.nonDisplayedMemory=new fo(i),this.lastOutputScreen=new fo(i),this.currRollUpRow=this.displayedMemory.rows[14],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[14],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),"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)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(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"),"MODE_POP-ON"===this.mode){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: "+ht(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const 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))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class mo{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new oo;this.channels=[null,new go(e,t,s),new go(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const i=127&t[e],s=127&t[e+1];let r=!1,n=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+lo([t[e],t[e+1]])+"] -> ("+lo([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(yo(i,s,a)){po(null,null,a),this.logger.log(3,()=>"Repeated command ("+lo([i,s])+") is dropped");continue}po(i,s,this.cmdHistory),r=this.parseCmd(i,s),r||(r=this.parseMidrow(i,s)),r||(r=this.parsePAC(i,s)),r||(r=this.parseBackgroundAttributes(i,s))}else po(null,null,a);if(!r&&(n=this.parseChars(i,s),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+lo([i,s])+" orig: "+lo([t[e],t[e+1]]))}}parseCmd(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;const i=20===e||21===e||23===e?1:2,s=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1: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 ("+lo([e,t])+")"),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const s=e<=23?1:2;i=t>=64&&t<=95?1===s?io[e]:ro[e]:1===s?so[e]:no[e];const r=this.channels[s];return!!r&&(r.setPAC(this.interpretPAC(i,t)),this.currentChannel=s,!0)}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,s.underline=!(1&~i),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=4*Math.floor((i-16)/2),s}parseChars(e,t){let i,s=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let e;e=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,()=>"Special char '"+Za(e)+"' in channel "+i),s=[e]}else e>=32&&e<=127&&(s=0===t?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+lo(s).join(",")),s}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let i;const s={};16===e||24===e?(i=Math.floor((t-32)/2),s.background=ao[i],t%2==1&&(s.background=s.background+"_semi")):45===t?s.background="transparent":(s.foreground="black",47===t&&(s.underline=!0));const r=e<=23?1:2;return this.channels[r].setBkgData(s),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}po(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 po(e,t,i){i.a=e,i.b=t}function yo(e,t,i){return i.a===e&&i.b===t}var vo=function(){if(null!=Di&&Di.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const i=t.toLowerCase();return!!~e.indexOf(i)&&i}function s(e){return i(t,e)}function r(e,...t){let i=1;for(;i<arguments.length;i++){const t=arguments[i];for(const i in t)e[i]=t[i]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=t,u=n,f=a,g=null,m="",p=!0,y="auto",v="start",T=50,E="middle",S=50,A="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(e){d=""+e}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return h},set:function(e){h=!!e}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(t){const s=function(t){return i(e,t)}(t);if(!1===s)throw new SyntaxError("An invalid or illegal string was specified.");m=s,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},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",r({},l,{get:function(){return v},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return E},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},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",r({},l,{get:function(){return A},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");A=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class To{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Eo(e){function t(e,t,i,s){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(s||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class So{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 Ao(e,t,i,s){const r=s?e.split(s):[e];for(const e in r){if("string"!=typeof r[e])continue;const s=r[e].split(i);if(2!==s.length)continue;t(s[0],s[1])}}const bo=new vo(0,0,""),Lo="middle"===bo.align?"middle":"center";function Ro(e,t,i){const s=e;function r(){const t=Eo(e);if(null===t)throw new Error("Malformed timestamp: "+s);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=r(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);e=e.slice(3),n(),t.endTime=r(),n(),function(e,t){const s=new So;Ao(e,function(e,t){let r;switch(e){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===t){s.set(e,i[r].region);break}break;case"vertical":s.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),s.integer(e,r[0]),s.percent(e,r[0])&&s.set("snapToLines",!1),s.alt(e,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",Lo,"end"]);break;case"position":r=t.split(","),s.percent(e,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",Lo,"end","line-left","line-right","auto"]);break;case"size":s.percent(e,t);break;case"align":s.alt(e,t,["start",Lo,"end","left","right"])}},/:/,/\s/),t.region=s.get("region",null),t.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===bo.line&&(r=-1),t.line=r,t.lineAlign=s.get("lineAlign","start"),t.snapToLines=s.get("snapToLines",!0),t.size=s.get("size",100),t.align=s.get("align",Lo);let n=s.get("position","auto");"auto"===n&&50===bo.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function Io(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class ko{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new To,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function i(){let e=t.buffer,i=0;for(e=Io(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;const s=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),s}function s(e){Ao(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=i();const s=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=i(),t.state){case"HEADER":/:/.test(e)?s(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new vo(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Ro(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==e.indexOf("--\x3e");if(!e||i&&(r=!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+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const 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}}const Po=/\r\n|\n\r|\n|\r/g,wo=function(e,t,i=0){return e.slice(i,i+t.length)===t};function Do(e,t,i){return Fa(e.toString())+Fa(t.toString())+Fa(i)}function xo(e,t,i,s,r,n,a){const o=new ko,l=H(new Uint8Array(e)).trim().replace(Po,"\n").split("\n"),d=[],h=t?function(e,t=1){return Jr(e,9e4,1/t)}(t.baseTime,t.timescale):0;let c,u="00:00.000",f=0,g=0,p=!0;o.oncue=function(e){const n=i[s];let a=i.ccOffset;const o=(f-h)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(e,t,i){let s=e[t],r=e[s.prevCC];if(!r||!r.new&&s.new)return e.ccOffset=e.presentationOffset=s.start,void(s.new=!1);for(;null!=(n=r)&&n.new;){var n;e.ccOffset+=s.start-r.start,s.new=!1,s=r,r=e[s.prevCC]}e.presentationOffset=i}(i,s,o)),o){if(!t)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=e.endTime-e.startTime,u=on(9e4*(e.startTime+a-g),9e4*r)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=Do(e.startTime,e.endTime,m)),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(d)},l.forEach(e=>{if(p){if(wo(e,"X-TIMESTAMP-MAP=")){p=!1,e.slice(16).split(",").forEach(e=>{wo(e,"LOCAL:")?u=e.slice(6):wo(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{g=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(m(t)&&m(i)&&m(s)&&m(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*s,t+=36e5*r,t}(u)/1e3}catch(e){c=e}return}""===e&&(p=!1)}o.parse(e+"\n")}),o.flush()}const Co="stpp.ttml.im1t",_o=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Mo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Oo={left:"start",center:"center",right:"end",start:"start",end:"end"};function Fo(e,t,i,s){const r=fe(new Uint8Array(e),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map(e=>H(e)),a=function(e,t,i=1,s=!1){return Jr(e,t,1/i,s)}(t.baseTime,1,t.timescale);try{n.forEach(e=>i(function(e,t){const i=(new DOMParser).parseFromString(e,"text/xml"),s=i.getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((e,t)=>(e[t]=s.getAttribute(`ttp:${t}`)||r[t],e),{}),a="preserve"!==s.getAttribute("xml:space"),o=No(Uo(s,"styling","style")),l=No(Uo(s,"layout","region")),d=Uo(s,"body","[begin]");return[].map.call(d,e=>{const i=Bo(e,a);if(!i||!e.hasAttribute("begin"))return null;const s=Go(e.getAttribute("begin"),n),r=Go(e.getAttribute("dur"),n);let d=Go(e.getAttribute("end"),n);if(null===s)throw Vo(e);if(null===d){if(null===r)throw Vo(e);d=s+r}const h=new vo(s-t,d-t,i);h.id=Do(h.startTime,h.endTime,h.text);const c=function(e,t,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce((i,n)=>{const a=$o(t,s,n)||$o(e,s,n)||$o(r,s,n);return a&&(i[n]=a),i},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:u}=c;if(u){const e=Oo[u];e&&(h.lineAlign=e),h.align=u}return x(h,c),h}).filter(e=>null!==e)}(e,a)))}catch(e){s(e)}}function Uo(e,t,i){const s=e.getElementsByTagName(t)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function No(e){return e.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Bo(e,t){return[].slice.call(e.childNodes).reduce((e,i,s)=>{var r;return"br"===i.nodeName&&s?e+"\n":null!=(r=i.childNodes)&&r.length?Bo(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function $o(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Vo(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Go(e,t){if(!e)return null;let i=Eo(e);return null===i&&(_o.test(e)?i=function(e,t){const i=_o.exec(e),s=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/t.frameRate}(e,t):Mo.test(e)&&(i=function(e,t){const i=Mo.exec(e),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return 1e3*s;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}(e,t))),i}class Ho{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(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function Ko(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function jo(e,t){return!!e&&e.kind===Ko(t)&&bn(t,e)}function Wo(e,t,i,s){return Math.min(t,s)-Math.max(e,i)}const qo=/\s/,Yo={newCue(e,t,i,s){const r=[];let n,a,o,l,d;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(n=s.rows[u],o=!0,l=0,d="",!n.isEmpty()){var c;for(let e=0;e<n.chars.length;e++)qo.test(n.chars[e].uchar)&&o?l++:(d+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;const s=Io(d.trim()),f=Do(t,i,s);null!=e&&null!=(c=e.cues)&&c.getCueById(f)||(a=new h(t,i,s),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return e&&r.length&&(r.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),r.forEach(t=>Ca(e,t))),r}};const zo=/(\d+)-(\d+)\/(\d+)/;class Xo{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Qo,this.controller=new self.AbortController,this.stats=new X}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}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();const r=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(x({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&m(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout);(mn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var r;this.response=this.loader=i;const a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(a-s.loading.start)),!i.ok){const{status:e,statusText:t}=i;throw new Jo(t||"fetch, bad network response",e,i)}s.loading.first=a,s.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=zo.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(m(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(i.headers)||s.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&m(t.highWaterMark)?this.loadProgressively(i,s,e,t.highWaterMark,o):n?i.arrayBuffer():"json"===e.responseType?i.json():i.text()}).then(i=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[a];l&&(s.loaded=s.total=l);const d={url:o.url,data:i,code:o.status},h=null==(r=this.callbacks)?void 0:r.onProgress;h&&!m(t.highWaterMark)&&h(s,e,i,o),null==(n=this.callbacks)||n.onSuccess(d,s,e,o)}).catch(t=>{var i;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=t&&t.code||0,n=t?t.message:null;null==(i=this.callbacks)||i.onError({code:r,text:n},e,t?t.details:null,s)})}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,r){const n=new Hs,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return t.loaded+=d,d<s||n.dataLength?(n.push(l),n.dataLength>=s&&r(t,i,n.flush().buffer,e)):r(t,i,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}}function Qo(e,t){return new self.Request(e.url,t)}class Jo extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Zo=/^age:\s*[\d.]+\s*$/im;class el{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new X,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const 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()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){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 r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return r(i,t.url)}).catch(e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(e=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:e.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:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(const t in s)e.setRequestHeader(t,s[t]);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=r&&m(r)?r:n,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,r=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const s=t.status,l="text"===t.responseType?t.responseText:null;if(s>=200&&s<300){const r=null!=l?l:t.response;if(null!=r){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,e,r,t);const d={url:t.responseURL,data:r,code:s};return void(null==(a=this.callbacks)||a.onSuccess(d,i,e,t))}}const d=r.loadPolicy.errorRetry;var o;if(Dt(d,i.retry,!1,{url:e.url,data:void 0,code:s}))this.retry(d);else $.error(`${s} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:s,text:t.statusText},e,t,i)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Dt(e,this.stats.retry,!0))this.retry(e);else{var t;$.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Pt(e,i.retry),i.retry++,$.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Zo.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 tl=_(_({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:el,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends M{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:i,partCurrent:s,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!i||!a)return;const o=performance.now(),l=s?s.stats:i.stats,d=s?s.duration:i.duration,h=o-l.loading.start,c=r.minAutoLevel,u=i.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,p=!!e||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const y=r.mainForwardBufferInfo;if(!p&&null===y)return;const v=this.bwEstimator.getEstimateTTFB(),T=Math.abs(a.playbackRate);if(h<=Math.max(v,d/(2*T)*1e3))return;const S=y?y.len/T:0,A=l.loading.first?l.loading.first-l.loading.start:-1,b=l.loaded&&A>-1,L=this.getBwEstimate(),R=r.levels,I=R[u],k=Math.max(l.loaded,Math.round(d*(i.bitrate||I.averageBitrate)/8));let P=b?h-A:h;P<1&&b&&(P=Math.min(h,8*l.loaded/L));const w=b?1e3*l.loaded/P:0,D=v/1e3,x=w?(k-l.loaded)/w:8*k/L+D;if(x<=S)return;const C=w?8*w:L,_=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),M=this.hls.config.abrBandWidthUpFactor;let O,F=Number.POSITIVE_INFINITY;for(O=u-1;O>c;O--){const e=R[O].maxBitrate,t=!R[O].details||_;if(F=this.getTimeToLoadFrag(D,C,d*e,t),F<Math.min(S,d+D))break}if(F>=x)return;if(F>10*d)return;b?this.bwEstimator.sample(h-Math.min(v,A),l.loaded):this.bwEstimator.sampleTTFB(h);const U=R[O].maxBitrate;this.getBwEstimate()*M>U&&this.resetEstimator(U);const N=this.findBestLevel(U,c,O,0,S,1,1);N>-1&&(O=N),this.warn(`Fragment ${i.sn}${s?" part "+s.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${i.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${x.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|A} ms\n Current BW estimate: ${m(L)?0|L:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|U} bps`),r.nextLoadLevel=r.nextAutoLevel=O,this.clearTimer();const B=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${i.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,O>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,O,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||x>2*F?B():this.timer=self.setInterval(B,1e3*F),r.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:s,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new w(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=t.part)?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 T.BUFFER_ADD_CODEC_ERROR:case T.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case T.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:i,partCurrent:s}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){const t=performance.now(),i=s?s.stats:e.stats,r=t-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,i,s){return e+i/t+(s?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,r=s.end-s.first;m(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===R&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=i?i.duration:t.duration,r=this.hls.levels[t.level],n=(r.loaded?r.loaded.bytes:0)+s.loaded,a=(r.loaded?r.loaded.duration:0)+e;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(E.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,r=null!=s&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==R||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const s=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,s)&&t[e].loadError<=t[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,s,l,0,d,h);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=h=1}}const u=this.findBestLevel(o,n,s,l,c,d,h);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,r,n,a){var o;const l=s+r,d=this.lastLoadedFragLevel,h=-1===d?this.hls.firstLevel:d,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:y}=this.hls;if(1===f.length)return 0;const v=f[h],T=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===p||-1===d;let S,A="SDR",b=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:R}=y,I=this.audioTracksByGroup||(this.audioTracksByGroup=ut(g));let k=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(e,t,i,s){return e.slice(i,s+1).reduce((e,i,s)=>{if(!i.codecSet)return e;const r=i.audioGroups;let n=e[i.codecSet];n||(e[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,s),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;const i=t.groups[e];i&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach(e=>{n.channels[e]=(n.channels[e]||0)+i.channels[e]}))}),e},{})}(f,I,t,i)),r=function(e,t,i,s,r){const n=Object.keys(e),a=null==s?void 0:s.channels,o=null==s?void 0:s.audioCodec,l=null==r?void 0:r.videoCodec,d=a&&2===parseInt(a);let h=!1,c=!1,u=1/0,f=1/0,g=1/0,p=1/0,y=0,v=[];const{preferHDR:T,allowedVideoRanges:E}=dt(t,r);for(let t=n.length;t--;){const i=e[n[t]];h||(h=i.channels[2]>0),u=Math.min(u,i.minHeight),f=Math.min(f,i.minFramerate),g=Math.min(g,i.minBitrate),E.filter(e=>i.videoRanges[e]>0).length>0&&(c=!0)}u=m(u)?u:0,f=m(f)?f:0;const S=Math.max(1080,u),A=Math.max(30,f);g=m(g)?g:i,i=Math.max(g,i),c||(t=void 0);const b=n.length>1;return{codecSet:n.reduce((t,s)=>{const r=e[s];if(s===t)return t;if(v=c?E.filter(e=>r.videoRanges[e]>0):[],b){if(r.minBitrate>i)return ct(s,`min bitrate of ${r.minBitrate} > current estimate of ${i}`),t;if(!r.hasDefaultAudio)return ct(s,"no renditions with default or auto-select sound found"),t;if(o&&s.indexOf(o.substring(0,4))%5!=0)return ct(s,`audio codec preference "${o}" not found`),t;if(a&&!d){if(!r.channels[a])return ct(s,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||d)&&h&&0===r.channels[2])return ct(s,"no renditions with stereo sound found"),t;if(r.minHeight>S)return ct(s,`min resolution of ${r.minHeight} > maximum of ${S}`),t;if(r.minFramerate>A)return ct(s,`min framerate of ${r.minFramerate} > maximum of ${A}`),t;if(!v.some(e=>r.videoRanges[e]>0))return ct(s,`no variants with VIDEO-RANGE of ${ht(v)} found`),t;if(l&&s.indexOf(l.substring(0,4))%5!=0)return ct(s,`video codec preference "${l}" not found`),t;if(r.maxScore<y)return ct(s,`max score of ${r.maxScore} < selected max of ${y}`),t}return t&&(Ne(s)>=Ne(t)||r.fragmentError>e[t].fragmentError)?t:(p=r.minIndex,y=r.maxScore,s)},void 0),videoRanges:v,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:p}}(s,A,e,L,R),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:d,preferHDR:h}=r;k=d,S=n,A=h?a[a.length-1]:a[0],b=o,e=Math.max(e,l),this.log(`picked start tier ${ht(r)}`)}else S=null==v?void 0:v.codecSet,A=null==v?void 0:v.videoRange;const P=u?u.duration:c?c.duration:0,w=this.bwEstimator.getEstimateTTFB()/1e3,D=[];for(let o=i;o>=t;o--){var x;const t=f[o],c=o>h;if(!t)continue;if(y.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&Xe(t,I,A,b,e,L)?(t.supportedPromise=Qe(t,I,i,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;const i=this.hls.levels,s=i.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${s} ${ht(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${s} not smooth or powerEfficient: ${ht(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${ht(e)}`),s>-1&&i.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=Ye}if((S&&t.codecSet!==S||A&&t.videoRange!==A||c&&b>t.frameRate||!c&&b>0&&b<t.frameRate||null!=(x=t.supportedResult)&&null!=(x=x.decodingInfoResults)&&x.some(e=>!1===e.smooth))&&(!E||o!==k)){D.push(o);continue}const g=t.details,v=(u?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||P;let R;R=c?a*e:n*e;const C=P&&s>=2*P&&0===r?t.averageBitrate:t.maxBitrate,_=this.getTimeToLoadFrag(w,R,C*v,void 0===g);if(R>=C&&(o===d||0===t.loadError&&0===t.fragmentError)&&(_<=w||!m(_)||T&&!this.bitrateTestDelay||_<l)){const e=this.forcedAutoLevel;return o===p||-1!==e&&e===p||(D.length&&this.trace(`Skipped level(s) ${D.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[D[0]].codecs}" ${f[D[0]].videoRange}; not compatible with "${S}" ${A}`),this.info(`switch candidate:${h}->${o} adjustedbw(${Math.round(R)})-bitrate=${Math.round(R-C)} ttfb:${w.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${_.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${p}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},bufferController:class extends M{constructor(e,t){var i;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:t,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(i=V(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this),e.off(E.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?x(i,s.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(i[t]=x({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(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.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const s=V(this.appendSource);if(s){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const r=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(r),e)this._objectUrl=i.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const t=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||t&&r instanceof t,Pn(i),function(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(i=e.constructor)?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,s=t.tracks,r=s?Object.keys(s):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${ht(i,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${ht(s,(e,t)=>"initSegment"===e?void 0:t)}}`),!G(s,i)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach(e=>{const t=e,i=s[t];if(i){const e=i.buffer;if(e){const s=this.fragmentTracker,r=i.id;if(s.hasFragments(r)||s.hasParts(r)){const i=di.getBuffered(e);s.detectEvictedFragments(t,i,r,null,!0)}const n=wn(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,i)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),r.removeSourceBuffer(t[i]);e&&r.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(s.removeAttribute("src"),this.appendSource&&Pn(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(E.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[wn(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Ln(this.tracks)}onBufferCodecs(e,t){var i;const s=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(e=>!s[e]);n||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(e=>{var i,r;const n=t[e],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:c}=n;let u=s[e];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[e],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;u||(u=s[e]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:d,levelCodec:l,metadata:h,id:a});const y=Ge(m,p),v=null==y?void 0:y.replace(Rn,"$1");let T=Ge(o,l);const E=null==(r=T)?void 0:r.replace(Rn,"$1");T&&y&&v!==E&&("audio"===e.slice(0,5)&&(T=Ve(T,this.appendSource)),this.log(`switching codec ${m} to ${T}`),T!==(u.pendingCodec||u.codec)&&(u.pendingCodec=T),u.container=d,this.appendChangeType(e,d,T))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(i=t.audio)?void 0:i.id)&&(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}`,r={label:`change-type=${s}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),n.changeType(s),r.codec=i,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,R))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>s||null!=t&&t.buffer&&di.isBuffered(t.buffer,s)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,R))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=t,h=l.buffering[r],{sn:c,cc:u}=a,f=self.performance.now();h.start=f;const g=a.stats.buffering,p=o?o.stats.buffering:null;0===g.start&&(g.start=f),p&&0===p.start&&(p.start=f);const y=i.audio;let S=!1;"audio"===r&&"audio/mpeg"===(null==y?void 0:y.container)&&(S=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const A=i.video,b=null==A?void 0:A.buffer;if(b&&"initSegment"!==c){const e=o||a,t=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||A.ending||A.ended){if("video"===r){const i=e.end;if(t){const e=t.frag.start;(i>e||i<this.lastVideoAppendEnd||di.isBuffered(b,e))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const t=e.start+.05*e.duration,i=b.buffered,s=this.currentOp("video");i.length||s?!s&&!di.isBuffered(b,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const L=(o||a).start,I={label:`append-${r}`,execute:()=>{var e;h.executeStart=self.performance.now();const t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(S?this.updateTimestampOffset(t,L,.1,r,c,u):void 0!==d&&m(d)&&this.updateTimestampOffset(t,d,1e-6,r,c,u)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();h.executeEnd=h.end=e,0===g.first&&(g.first=e),p&&0===p.first&&(p.first=e);const t={};this.sourceBuffers.forEach(([e,i])=>{e&&(t[e]=di.getBuffered(i))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const i={type:v.MEDIA_ERROR,parent:a.type,details:T.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},s=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)i.details=T.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!s)i.errorAction=$t(!0);else if(e.name===In&&0===this.sourceBufferCount)i.errorAction=$t(!0);else{const e=++this.appendErrors[r];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${s||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}this.hls.trigger(E.ERROR,i)}};this.log(`queuing "${r}" append sn: ${c}${o?" p: "+o.index:""} of ${a.type===R?"level":"track"} ${a.level} cc: ${u}`),this.append(I,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:r}=t;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,s,r),e)})}onFragParsed(e,t){const{frag:i,part:s}=t,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[Z]?r.push("audiovideo"):(n[Q]&&r.push("audio"),n[J]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(()=>{const e=self.performance.now();i.stats.buffering.end=e,s&&(s.stats.buffering.end=e);const t=s?s.stats:i.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:i,part:s,stats:t,id:i.type})},r).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}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(([e])=>{if(e){const i=this.tracks[e];t.type&&t.type!==e||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}});const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){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===T.BUFFER_APPEND_ERROR&&t.frag){var i;const e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;m(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||null===t)return;if(!this.sourceBufferCount)return;const s=e.config,r=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(m(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(r/n)*n-e;this.flushBackBuffer(r,n,t)}const o=s.frontBufferFlushThreshold;if(m(o)&&o>0){const e=Math.max(s.maxBufferLength,o),t=Math.max(e,n),i=Math.floor(r/n)*n+t;this.flushFrontBuffer(r,n,i)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([e,t])=>{if(t){const r=di.getBuffered(t);if(r.length>0&&i>r.start(0)){var s;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:i});const t=this.tracks[e];if(null!=(s=this.details)&&s.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([t,s])=>{if(s){const r=di.getBuffered(s),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(i>a||e>=a&&e<=o)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,s)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return m(r)?{duration:r}:null;const n=this.media.duration;return s>(m(i.duration)?i.duration:0)&&s>n||!m(n)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==e&&(m(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),void 0!==t&&void 0!==i&&(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}) ${ht(i)}`),this.tracksReady){var s;const e=null==(s=this.transferData)?void 0:s.tracks;e&&Object.keys(e).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(E.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.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 r in e){const n=r,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),r=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${ht(a)}`);try{const e=i.addSourceBuffer(r),s=wn(n),o=[n,e];t[s]=o,a.buffer=e}catch(e){var s;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[n],void this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&("video"===t||"audiovideo"===t)&&Me(i,"video")&&(s=function(e,t){const i=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)_e(t[e],"video")||i.push(t[e])}return t&&i.push(t),i.join(",")}(s,i));const r=Ge(s,e.levelCodec);return r?"audio"===t.slice(0,5)?Ve(r,this.appendSource):r:""}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",(e,t)=>{const i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;const i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const r=this.currentOp(e);r&&r.onError(s)}updateTimestampOffset(e,t,i,s,r,n){const a=t-e.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:s,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!s||!r||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=m(s.duration)?s.duration:1/0,l=m(r.duration)?r.duration:1/0,d=Math.max(0,t),h=Math.min(i,o,l);h>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`),a.remove(d,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],s=null==i?void 0:i.buffer;if(!s)throw new kn(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,s=t.map(e=>this.appendBlocker(e));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;i&&!i.updating&&this.shiftAndExecuteNext(e)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,e);s.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(e=>{i.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}},capLevelController:Dn,errorController:class extends M{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(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===R?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;const s=e.audioGroups;if(s){return this.hls.allAudioTracks.filter(e=>s.indexOf(e.groupId)>=0).some(e=>{var i;return null==(i=e.details)?void 0:i.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,r=t.context;switch(t.details){case T.FRAG_LOAD_ERROR:case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_ERROR:case T.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case T.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=$t());case T.FRAG_GAP:case T.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=_t);case T.LEVEL_EMPTY_ERROR:case T.LEVEL_PARSING_ERROR:{var n;const e=t.parent===R?t.level:s.loadLevel;t.details===T.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case T.LEVEL_LOAD_ERROR:case T.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case T.AUDIO_TRACK_LOAD_ERROR:case T.AUDIO_TRACK_LOAD_TIMEOUT:case T.SUBTITLE_LOAD_ERROR:case T.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=s.loadLevelObj;if(e&&(r.type===b&&e.hasAudioGroup(r.groupId)||r.type===L&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=_t,void(t.errorAction.flags=Ut)}return;case T.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:_t,flags:Nt});case T.KEY_SYSTEM_SESSION_UPDATE_FAILED:case T.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case T.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:_t,flags:Bt});case T.BUFFER_ADD_CODEC_ERROR:case T.REMUX_ALLOC_ERROR:case T.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:s.loadLevel);return;case T.INTERNAL_EXCEPTION:case T.BUFFER_APPENDING_ERROR:case T.BUFFER_FULL_ERROR:case T.LEVEL_SWITCH_ERROR:case T.BUFFER_STALLED_ERROR:case T.BUFFER_SEEK_OVER_HOLE:case T.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=$t())}t.type===v.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=$t())}getPlaylistRetryOrSwitchAction(e,t){const i=kt(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++;if(Dt(i,s,Lt(e),e.response))return{action:Ot,flags:Ft,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(e,t);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=kt(Rt(e)?n:r,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(s&&(e.details!==T.FRAG_GAP&&s.fragmentError++,!It(e))){if(Dt(a,o,Lt(e),e.response))return{action:Ot,flags:Ft,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;null==t&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var r,n;const t=e.details;s.loadError++,t===T.BUFFER_APPEND_ERROR&&s.fragmentError++;let l=-1;const{levels:d,loadLevel:h,minAutoLevel:c,maxAutoLevel:u}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===I&&t===T.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===T.BUFFER_ADD_CODEC_ERROR||t===T.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:e})=>s.audioCodec!==e),m="video"===e.sourceBufferName&&(t===T.BUFFER_ADD_CODEC_ERROR||t===T.BUFFER_APPEND_ERROR)&&d.some(({codecSet:e,audioCodec:t})=>s.codecSet!==e&&s.audioCodec===t),{type:p,groupId:y}=null!=(n=e.context)?n:{};for(let i=d.length;i--;){const r=(i+h)%d.length;if(r!==h&&r>=c&&r<=u&&0===d[r].loadError){var a,o;const i=d[r];if(t===T.FRAG_GAP&&f===R&&e.frag){const t=d[r].details;if(t){const i=Et(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(p===b&&i.hasAudioGroup(y)||p===L&&i.hasSubtitleGroup(y))continue;if(f===I&&null!=(a=s.audioGroups)&&a.some(e=>i.hasAudioGroup(e))||f===k&&null!=(o=s.subtitleGroups)&&o.some(e=>i.hasSubtitleGroup(e))||g&&s.audioCodec===i.audioCodec||m&&s.codecSet===i.codecSet||!g&&s.codecSet!==i.codecSet)continue}l=r;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:_t,flags:Ft,nextAutoLevel:l}}return{action:_t,flags:Ut}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case Ct:break;case _t:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===T.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s}=i,r=i.nextAutoLevel;switch(s){case Ft:this.switchLevel(e,r);break;case Nt:{const s=this.getVariantLevelIndex(e.frag),r=t.levels[s],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(i.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){t.maxHdcpLevel=et[et.indexOf(n)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Bt:{const t=e.decryptdata;if(t){const s=this.hls.levels,r=s.length;for(let i=r;i--;){var n,a;if(this.variantHasKey(s[i],t))this.log(`Banned key found in level ${i} (${s[i].bitrate}bps) or audio group "${null==(n=s[i].audioGroups)?void 0:n.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${K(t.keyId||[])}`),s[i].fragmentError++,s[i].loadError++,this.log(`Removing level ${i} with key error (${e.error})`),this.hls.removeLevel(i)}const o=e.frag;if(this.hls.levels.length<r)i.resolved=!0;else if(o&&o.type!==R){const e=o.decryptdata;e&&!t.matches(e)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&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===T.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=We(e.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${s} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(s))}}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.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 e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(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 e=s-this.lastTime,r=i-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger(E.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,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)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Bi,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Yo,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends Vs{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",k),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(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Ds,this.setInterval(500),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,success:s}=t;if(this.fragContextChanged(i)||(te(i)&&(this.fragPrevious=i),this.state=Ds),!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let e=0;e<r.length;e++)if(a>=r[e].start&&a<=r[e].end){n=r[e];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(0===i&&s!==Number.POSITIVE_INFINITY){const e=s-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let i=0;i<t.length;)if(t[i].end<=e)t.shift();else{if(!(t[i].start<e))break;t[i].start=e,i++}}),this.fragmentTracker.removeFragmentsInRange(i,e,k)}}onError(e,t){const i=t.frag;(null==i?void 0:i.type)===k&&(t.details===T.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ws&&(this.state=Ds))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&Sn(this.levels,t)?this.levels=t.map(e=>new ot(e)):(this.tracksBuffered=[],this.levels=t.map(e=>{const t=new ot(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,k),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==ws&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:a}=t;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;const e=this.mainDetails;if(!e)return void(this.startFragRequested=!1);const t=e.fragments[0];var d;if(o.details)l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&t&&(l=t.start,fs(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(Rs(n,e),l=n.fragmentStart):t&&(l=t.start,fs(n,l));e&&!this.startFragRequested&&this.setStartPosition(e,l)}if(o.details=n,this.levelLastLoaded=o,a===s&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Ds)){Et(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&Li(s.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Ri(s.method)).catch(e=>{throw r.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(i=>{const s=performance.now();r.trigger(E.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:s}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=Ds})}}doTick(){if(this.media){if(this.state===Ds){const{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;const{config:s}=this,r=this.getLoadPosition(),n=di.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),{end:a,len:o}=n,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const d=l.fragments,h=d.length,c=l.edge;let u=null;const f=this.fragPrevious;if(a<c){const e=s.maxFragLookUpTolerance,t=a>c-e?0:e;u=Et(f,d,Math.max(d[0].start,a),t),!u&&f&&f.start<d[0].start&&(u=d[0])}else u=d[h-1];if(u=this.filterReplacedPrimary(u,i.details),!u)return;const g=d[u.sn-l.startSN-1];if(g&&g.cc===u.cc&&this.fragmentTracker.getState(g)===Vt&&(u=g),this.fragmentTracker.getState(u)===Vt){const e=this.mapToInitFragWhenRequired(u);e&&this.loadFragment(e,i,a)}}}else this.state=Ds}loadFragment(e,t,i){te(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Qa(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends En{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 e=null;const t=Oa(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}const i=this.findTrackForTextTrack(e);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,s)return;Oa(i.textTracks).forEach(e=>{_a(e)})}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:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}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 r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>-1===(null==s?void 0:s.indexOf(e)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!r&&t){this.selectDefaultTrack=!1;const i=gt(t,e);if(i>-1)r=e[i];else{const e=gt(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,n),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const r=t[s];if((!i||r.default)&&(i||e)&&(!e||mt(r,e)))return s}if(e){for(let i=0;i<t.length;i++){const s=t[i];if(An(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const s=t[i];if(An(e.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){if(bn(t[i],e))return i}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==L||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&mt(e,i))return i;const s=gt(e,this.tracksInGroup);if(s>-1){const e=this.tracksInGroup[s];return this.setSubtitleTrack(s),e}if(i)return null;{const i=gt(e,t);if(i>-1)return t[i]}}}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,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Oa(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter(e=>bn(i,e))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(e=>{"disabled"!==e.mode&&e!==s&&(e.mode="disabled")}),s){const e=this.subtitleDisplay?"showing":"hidden";s.mode!==e&&(s.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!m(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});const r=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=s;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const h=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(h)}},timelineController:class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Ho(this,"textTrack1"),t=new Ho(this,"textTrack2"),i=new Ho(this,"textTrack3"),s=new Ho(this,"textTrack4");this.cea608Parser1=new mo(1,e,t),this.cea608Parser2=new mo(3,i,s)}addCues(e,t,i,s,r){let n=!1;for(let e=r.length;e--;){const s=r[e],a=Wo(s[0],s[1],t,i);if(a>=0&&(s[0]=Math.min(s[0],t),s[1]=Math.max(s[1],i),n=!0,a/(i-t)>.5))return}if(n||r.push([t,i]),this.config.renderTextTracksNatively){const r=this.captionsTracks[e];this.Cues.newCue(r,t,i,s)}else{const r=this.Cues.newCue(null,t,i,s);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:r,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;i===R&&(this.initPTS[t.cc]={baseTime:s,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,e):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(jo(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:r,languageCode:n}=t[e],a=this.getExistingTrack(r,n);if(a)i[e]=a,_a(i[e]),xa(i[e],s);else{const t=this.createTextTrack("captions",r,n);t&&(t[e]=!0,i[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(e=>{_a(s[e]),delete s[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)_a(t[e])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(e=>e.textCodec===Co);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Sn(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const e=this.media,t=e?Oa(e.textTracks):null;if(this.tracks.forEach((e,i)=>{let s;if(t){let i=null;for(let s=0;s<t.length;s++)if(t[s]&&jo(t[s],e)){i=t[s],t[s]=null;break}i&&(s=i)}if(s)_a(s);else{const t=Ko(e);s=this.createTextTrack(t,e.name,e.lang),s&&(s.mode="disabled")}s&&this.textTracks.push(s)}),null!=t&&t.length){const e=t.filter(e=>null!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const i=`textTrack${t[1]}`,s=this.captionsProperties[i];s&&(s.label=e.name,e.lang&&(s.languageCode=e.lang),s.media=e)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===R){var i,s;const{cea608Parser1:e,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(i=null==(s=t.part)?void 0:s.index)?i:-1;e&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===k)if(s.byteLength){const e=i.decryptdata,r="stats"in t;if(null==e||!e.encrypted||r){const e=this.tracks[i.level],r=this.vttCCs;r[i.cc]||(r[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===Co?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Fo(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),i.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{i.logger.log(`Failed to parse IMSC1: ${t}`),i.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[i.cc]&&-1===a)return void n.push(e);const o=this.hls;xo(null!=(t=i.initSegment)&&t.data?be(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,e=>{this._appendCues(e,i.level),o.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},t=>{const r="Missing initPTS for VTT MPEGTS"===t.message;r?n.push(e):this._fallbackToIMSC1(i,s),o.logger.log(`Failed to parse VTT cue: ${t}`),r&&a>i.cc||o.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Fo(t,this.initPTS[e.cc],()=>{i.textCodec=Co,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach(e=>Ca(i,e))}else{const s=this.tracks[t];if(!s)return;const r=s.default?"default":"subtitles"+t;i.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===k&&this.onFragLoaded(E.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!==R||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;e<s.length;e++){const t=s[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(t);this.cea608Parser1.addData(s[e].pts,i[0]),this.cea608Parser2.addData(s[e].pts,i[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!r||"video"===r){const{captionsTracks:e}=this;Object.keys(e).forEach(s=>Ma(e[s],t,i))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==s){const{textTracks:e}=this;Object.keys(e).forEach(i=>Ma(e[i],t,s))}}}extractCea608Data(e){const t=[[],[]],i=31&e[0];let s=2;for(let r=0;r<i;r++){const i=e[s++],r=127&e[s++],n=127&e[s++];if(0===r&&0===n)continue;if(!!(4&i)){const e=3&i;0!==e&&1!==e||(t[e].push(r),t[e].push(n))}}return t}},audioStreamController:class extends Vs{constructor(e,t,i){super(e,t,i,"audio-stream-controller",I),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){if(i===R){const e=t.cc,i=this.fragCurrent;if(this.initPTS[e]={baseTime:s,timescale:r,trackId:n},this.log(`InitPTS for cc: ${e} found from main: ${s/r} (${s}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===Bs){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==e)&&this.syncWithAnchor(t,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==e?(i.abortRequests(),this.syncWithAnchor(t,i)):this.state===Ds&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const s=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(t&&(null==s?void 0:s.cc)===t.cc)return;const r=(s||e).cc,n=bt(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===Ds&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=ws);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Ds):this.state=Ms,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Ds:this.doTickIdle();break;case Ms:{const{levels:e,trackId:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=Bs}break}case _s:this.checkRetryDate();break;case Bs:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:r}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=Cs;const e={frag:t,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),r&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=Ds}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:r}=this,n=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[r])return;const a=i[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Ms,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Q,I));const d=this.getFwdBufferInfo(l,I);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return t.trigger(E.BUFFER_EOS,{type:"audio"}),void(this.state=Us);const h=d.len,c=t.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing?g:d.end;if(this.switchingTrack&&s){const e=g;o.PTSKnown&&e<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(h>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,d,R,c)),!p)return void(this.bufferFlushed=!0);let y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&te(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Kt&&(this.mainFragLoading=y=null),y&&te(y))){if(p.start>y.end){const e=this.fragmentTracker.getFragAtPos(m,R);e&&e.end>y.end&&(y=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(p.start>y.end)return}this.loadFragment(p,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new ot(e))}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,this.flushAudioIfNeeded(t),this.state!==ws&&(this.setInterval(100),this.state=Ds,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(E.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:r,id:n,groupId:a,track:o}=t;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==ws&&(this.state=Ms));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=s[n];let h=0;if(r.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;if(d.details)h=this.alignPlaylists(r,d.details,null==(c=this.levelLastLoaded)?void 0:c.details);r.alignedSliding||(Ls(r,l),r.alignedSliding||Rs(r,l),h=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state!==Ms||this.waitForCdnTuneIn(r)||(this.state=Ds),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const h=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Tn(this.hls,I,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=s?s.index:-1,n=-1!==t,a=new oi(i.level,i.sn,i.stats.chunkCount,r.byteLength,t,n);c.push(r,f,h,"",i,s,d.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Hs,complete:!1};e.push(new Uint8Array(r)),this.state!==ws&&(this.state=Bs)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0: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===R&&te(t.frag)&&(this.mainFragLoading=t,this.state===Ds&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type===I)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"}`);else{if(te(i)){this.fragPrevious=i;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,_({},e)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==R||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var i;if(t.fatal)this.state=Ns;else switch(t.details){case T.FRAG_GAP:case T.FRAG_PARSING_ERROR:case T.FRAG_DECRYPT_ERROR:case T.FRAG_LOAD_ERROR:case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_ERROR:case T.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(I,t);break;case T.AUDIO_TRACK_LOAD_ERROR:case T.AUDIO_TRACK_LOAD_TIMEOUT:case T.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Ms||(null==(i=t.context)?void 0:i.type)!==b||(this.state=Ds);break;case T.BUFFER_ADD_CODEC_ERROR:case T.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case T.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case T.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==J&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==J){this.flushing=!1,this.bufferFlushed=!0,this.state===Us&&(this.state=Ds);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,I),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{details:h}=d,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&h){if(this.state=Os,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,g.tracks,e,n),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(c){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=c;l&&(l.elementaryStreams[Q]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),o.setElementaryStreamInfo(Q,e,t,i,s),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=x({id:i,frag:o,details:h},f);s.trigger(E.FRAG_PARSING_METADATA,e)}if(u){const e=x({id:i,frag:o,details:h},u);s.trigger(E.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,i,s){if(this.state!==Os)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const r=t.audio;r.id=I;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(E.BUFFER_CODECS,t);const a=r.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:a};this.hls.trigger(E.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);var r;if(this.switchingTrack||s===Vt||s===Ht)if(te(e))if(null!=(r=t.details)&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Bs;const i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&Rs(t.details,i)}else super.loadFragment(e,t,i);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;mt({name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},e,pt)||(vt(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.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,_({},e))}},audioTrackController:class extends En{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.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:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}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 r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>-1===(null==s?void 0:s.indexOf(e)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!r&&t){const i=gt(t,e,pt);if(i>-1)r=e[i];else{const e=gt(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==s&&-1===o)this.setAudioTrack(s);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==b||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){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&&mt(e,s,pt))return s;const r=gt(e,this.tracksInGroup,pt);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r),e}if(s){let s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);const r=function(e,t,i,s,r){const n=t[s],a=t.reduce((e,t,i)=>{const s=t.uri;return(e[s]||(e[s]=[])).push(i),e},{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),h=yt(t,s,t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==d)return!1;const s=t.audioGroups,n=i.filter(e=>!s||-1!==s.indexOf(e.groupId));return gt(e,n,r)>-1});return h>-1?h:yt(t,s,t=>{const s=t.audioGroups,n=i.filter(e=>!s||-1!==s.indexOf(e.groupId));return gt(e,n,r)>-1})}(e,t.levels,i,s,pt);if(-1===r)return null;t.nextLoadLevel=r}if(e.channels||e.audioCodec){const t=gt(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],r=s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;if(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,_({},s)),r)return;const n=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if((!this.selectDefaultTrack||s.default)&&(!e||mt(e,s,pt)))return i}if(e){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(mt({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},t[e],pt))return e}for(let i=0;i<t.length;i++){const s=t[i];if(An(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const s=t[i];if(An(e.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&vt(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},emeController:Ia,cmcdController:class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:xn.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:i}=e,s=this.hls.levels[t.level],r=this.getObjectType(t),n={d:1e3*(i||t).duration,ot:r};r!==xn.VIDEO&&r!==xn.AUDIO&&r!=xn.MUXED||(n.br=s.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=i?this.getNextPart(i):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(n.nor=a.url),this.apply(e,n)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,s;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=t.tracks.video)?void 0:s.buffer}createData(){var e;return{v:1,sf:Cn.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){x(t,this.createData());const i=t.ot===xn.INIT||t.ot===xn.VIDEO||t.ot===xn.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((e,i)=>(s.includes(i)&&(e[i]=t[i]),e),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Ea(e.headers,t,r)):e.url=ba(e.url,t,r)}getNextFrag(e){var t;const i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){const t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t;const{index:i,fragment:s}=e,r=null==(t=this.hls.levels[s.level])||null==(t=t.details)?void 0:t.partList;if(r){const{sn:e}=s;for(let t=r.length-1;t>=0;t--){const s=r[t];if(s.index===i&&s.fragment.sn===e)return r[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?xn.TIMED_TEXT:"initSegment"===e.sn?xn.INIT:"audio"===t?xn.AUDIO:"main"===t?this.hls.audioTracks.length?xn.VIDEO:xn.MUXED:void 0}getTopBandwidth(e){let t,i=0;const s=this.hls;if(e===xn.AUDIO)t=s.audioTracks;else{const e=s.maxAutoLevel,i=e>-1?e+1:s.levels.length;t=s.levels.slice(0,i)}return t.forEach(e=>{e.bitrate>i&&(i=e.bitrate)}),i>0?i:NaN}getBufferLength(e){const t=this.media,i=e===xn.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!t)return NaN;return 1e3*di.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}},contentSteeringController:class extends M{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&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=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(t=>t!==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;null!==i&&(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((null==i?void 0:i.action)===_t&&i.flags===Ut){const e=this.levels;let s=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:i,pathwayId:s,type:n}=t.context;i&&e?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&e&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r),t.details!==T.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${ht(s)} penalized: ${ht(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){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 null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(e=>{s-i[e]>3e5&&delete i[e]});for(let s=0;s<e.length;s++){const r=e[s];if(r in i)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,vs(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(t===b&&s[i].hasAudioGroup(e)||t===L&&s[i].hasSubtitleGroup(e))return s[i].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(e=>{const t=new yi(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(i[t.AUDIO]=n,t.AUDIO=n),o&&(s[t.SUBTITLES]=o,t.SUBTITLES=o);const l=Ra(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new ot({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(let t=1;t<e.audioGroups.length;t++)d.addGroupId("audio",`${e.audioGroups[t]}_clone_${r}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)d.addGroupId("text",`${e.subtitleGroups[t]}_clone_${r}`);return d});t.push(...o),La(this.audioTracks,i,a,r),La(this.subtitleTracks,s,a,r)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;let s;this.loader&&this.loader.destroy(),this.loader=new i(t);try{s=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==s.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+e)}const r={responseType:"json",url:s.href},n=t.steeringManifestLoadPolicy.default,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:(e,t,i,r)=>{this.log(`Loaded steering manifest: "${s}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,s).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:s.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(e,t,i,s)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,r)},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}},interstitialsController:class extends M{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const i=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&e<s.start||e>=s.end){var r;const t=this.findItemIndex(s);let n=this.schedule.findItemIndexAtTime(e);if(-1===n&&(n=t+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${n})`)),!this.isInterstitial(s)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&n>t){const e=this.schedule.findJumpRestrictedIndex(t+1,n);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(s)){const t=s.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;var l;(i&&e<a||e>=a+o)&&(null!=(l=s.event)&&l.appendInPlace&&(this.clearInterstitial(s.event,s),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,n))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const i=this.playingAsset;if(!i)return;e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{const i=this.schedule;if(!i)return;const s=this.playingItem,r=i.events||[],n=i.items||[],a=i.durations,o=e.map(e=>e.identifier),l=!(!r.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(e=>qa(e))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let d=null,h=null;s&&(d=this.updateItem(s,this.timelinePos),this.itemsMatch(s,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const c=this.bufferingItem;if(c&&(h=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,h)?this.bufferingItem=h:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(s){Math.abs(i)>Ua&&this.warn(`${s} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),l||t){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(s)&&o.includes(s.event.identifier))return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);s&&this.trimInPlace(d,s),c&&h!==d&&this.trimInPlace(h,c),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Ya(e),this.schedule=new Wa(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){ks(e,"play",this.onPlay),ks(e,"pause",this.onPause),ks(e,"seeking",this.onSeeking),ks(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Is(i,"seeking",this.onSeeking),Is(i,"timeupdate",this.onTimeupdate),Is(i,"play",this.onPlay),Is(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const e=this.findItemIndex(i);this.setSchedulePosition(e)}}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 e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.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=t=>t?e.getAssetPlayer(t.identifier):t,s=(t,s,n,a,o)=>{if(t){let l=t[s].start;const d=t.event;if(d){if("playout"===s||d.timelineOccupancy!==Na.Point){const e=i(n);(null==e?void 0:e.interstitial)===d&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?r():e[a])-t.start}return l}return 0},r=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=t=>{var i,s;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(s=e.schedule)?void 0:s.durations[t])||0},a=(t,r)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${r}"`);const l=e.effectivePlayingItem,d=e.schedule.findItemIndexAtTime(t,r),h=null==(a=e.schedule.items)?void 0:a[d],c=e.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&e.itemsMatch(l,h);if(l&&(f||g)){const n=i(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const i="primary"===r?a.currentTime:s(l,r,e.playingAsset,"timelinePos","currentTime"),o=t-i,d=(f?i:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(h){let i=t;if("primary"!==r){const e=t-h[r].start;i=h.start+e}const s=!e.isInterstitial(h);if(e.isInterstitial(l)&&!l.event.appendInPlace||!s&&!h.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(d>n){const t=e.schedule.findJumpRestrictedIndex(n+1,d);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(s)e.timelinePos=i,e.checkBuffer();else{const e=h.event.assetList,i=t-(h[r]||h).start;for(let t=e.length;t--;){const s=e[t];if(s.duration&&i>=s.startOffset&&i<s.startOffset+s.duration){a=t;break}}}e.setSchedulePosition(d,a)}}else{const t=e.media||(f?null==c?void 0:c.media:null);t&&(t.currentTime=i)}}},o=()=>{const i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;const s=t();return e.isInterstitial(s)?s:null},l={get bufferedEnd(){const i=t(),r=e.bufferingItem;var n;return r&&r===i&&(s(r,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=e.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const t=o(),i=e.effectivePlayingItem;return i&&i===t?s(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){const i=o(),s=e.effectivePlayingItem;s&&s===i&&a(t+s.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const i=null==(t=o())?void 0:t.event.assetList;return i?i.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var t;const i=null==(t=o())?void 0:t.event;return i&&e.effectivePlayingAsset?i.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(){const i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){var t;return((t,i)=>{var s;if(0!==t&&"primary"!==i&&null!=(s=e.schedule)&&s.length){var r;const s=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[s];if(n)return t+(n[i].start-n.start)}return t})((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){const s=e.findItemIndex(t);if(i.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(i,s,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=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(s=this.primaryMedia);const r=null==(t=s)?void 0:t.currentTime;return void 0!==r&&m(r)?r:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!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)return void(this.detachedData={media:s});const i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ht(i)}`),this.detachedData=i}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else if(l){const e=this.getBufferingPlayer();e?(r=e.transferMedia(),d=`${e}`):d="detached MediaSource"}else d="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ht(r)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach(e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}const h=r&&"mediaSource"in r&&"closed"!==(null==(s=r.mediaSource)?void 0:s.readyState),c=h&&r?r:t;this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`);const u=this.schedule;if(c===r&&u){const t=a&&e.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||t,cueRemoval:!a}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.log(Xa("checkStart",i)),this.timelinePos=i,t.length&&t[0].cue.pre){const i=e.findEventIndex(t[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){const t=this.timelinePos=i>0?i:0,s=e.findItemIndexAtTime(t);this.setSchedulePosition(s)}}else if(s&&!this.playingItem){const t=e.findItemIndex(s);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const i=e.event,s=i.findAssetIndex(t),r=Ha(i,s);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const t=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,r)}advanceAfterAssetEnded(e,t,i){const s=Ha(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=t+1;if(s>=i.length)return void this.setSchedulePosition(-1);const r=e.resumeTime;this.timelinePos<r&&(this.log(Xa("advanceAfterAssetEnded",r)),this.timelinePos=r,e.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){const t=e.assetList[s];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const s=t.parentIdentifier,r=i.getEvent(s);if(r){const t=i.findEventIndex(s),n=i.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,t,n-1)}}setSchedulePosition(e,t){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const r=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r?qa(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,d=this.playingAsset,h=null==d?void 0:d.identifier,c=h?this.getAssetPlayer(h):null;if(c&&h&&(!this.eventItemsMatch(n,r)||void 0!==t&&h!==i.assetList[t].identifier)){var o;const t=i.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${i.assetList.length} ${Ka(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:i,schedule:s.slice(0),scheduleIndex:e,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(h,r),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${qa(n)}`),i.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:e}),i.cue.once)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(r&&e){const i=this.findItemIndex(r);this.advanceSchedule(i,e,t,n,a)}return}}this.advanceSchedule(e,s,t,n,a)}advanceSchedule(e,t,i,s,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(t=>{const i=t.interstitial,s=n.findEventIndex(i.identifier);(s<e||s>e+1)&&this.clearInterstitial(i,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===i){const t=Ha(r,(i=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(t)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,e,i);i=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let d=this.preloadAssets(r,i);if(this.eventItemsMatch(a,l||s)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${qa(a)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(E.INTERSTITIAL_STARTED,{event:r,schedule:t.slice(0),scheduleIndex:e})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const h=r.assetList[i];if(!h)return void this.advanceAfterAssetEnded(r,e,i||0);if(d||(d=this.getAssetPlayer(h.identifier)),null===d||d.destroyed){const e=r.assetList.length;this.warn(`asset ${i+1}/${e} player destroyed ${r}`),d=this.createAssetPlayer(r,h,i),d.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(d,i,t,e,o),this.shouldPlay&&za(d.media)}else a?(this.resumePrimary(a,e,s),this.shouldPlay&&za(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,i){var s,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${qa(e)}`),null==(s=this.detachedData)||!s.mediaSource){let i=this.timelinePos;(i<e.start||i>=e.end)&&(i=this.getPrimaryResumption(e,t),this.log(Xa("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,e)}if(!i)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${qa(e)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(i<e.fragmentStart||i>e.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return di.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 r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Xa("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs(((null==(i=s.mainForwardBufferInfo)?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){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(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const s=_(_({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=_(_({},this.altSelection),{},{audio:i}));const r=_(_({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=_(_({},this.altSelection),{},{subtitles:i}));const r=_(_({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=ft(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=ft(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.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 e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const s=t[e];if(s.cue.post){var i;const e=this.schedule.findEventIndex(s.identifier),t=null==(i=this.schedule.items)?void 0:i[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const s=null==(i=this.schedule)?void 0:i.items;if(e&&s){return s[this.findItemIndex(e,t)]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,i)=>{e.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(t.identifier,null)});const i=e.end+.25,s=di.bufferInfo(this.primaryMedia,i,0);if(s.end>i||(s.nextStart||0)>i){this.log(`trim buffered interstitial ${qa(e)} (was ${qa(t)})`);const s=!0;this.attachPrimary(i,null,s),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===(null==(i=t.event)?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&(null==(t=this.schedule)||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=null==(t=this.schedule)?void 0:t.items;if(!i)return;const s=di.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,r=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(1===t.length&&this.itemsMatch(t[0],r))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const i=this.findItemIndex(r),s=Math.min(i+1,t.length-1),n=t[s];if((-1===o&&r&&e>=r.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=s),this.isInterstitial(r)){const e=r.event;if(s-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>i&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else i&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{const i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:s,events:r}=i;if(!s||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${qa(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const t=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,i)=>{const s=this.getAssetPlayer(e.identifier);s&&(i===t&&s.loadSource(),s.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.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(null!==i){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){const e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,r=0===s&&!e.assetListLoader,n=e.cue.once;if(r){const r=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-r;e>0&&(n=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(e,0,0,r,e.duration,i);const l=this.assetListLoader.loadAssetList(e,n);l&&(e.assetListLoader=l)}else if(!n&&s){for(let i=t;i<s;i++){const t=e.assetList[i],s=this.getAssetPlayerQueueIndex(t.identifier);-1!==s&&!this.playerQueue[s].destroyed||t.error||this.createAssetPlayer(e,t,i)}const i=e.assetList[t];if(i){const e=this.getAssetPlayer(i.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach(t=>{this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})})}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,r,n){const a={parentIdentifier:e.identifier,identifier:Ba(e,n,t),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){const s=this.hls,r=s.userConfig;let n=r.videoPreference;const a=s.loadLevelObj||s.levels[s.currentLevel];(n||a)&&(n=x({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let d=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const i=t.duration;i&&e<i&&(d=e)}}const h=t.identifier,c=_(_({},r),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(c.timelineOffset=t.timelineStart));const u=c.cmcd;null!=u&&u.sessionId&&u.contentId&&(c.cmcd=x({},u,{contentId:Fa(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const f=new ja(this.HlsPlayerClass,c,e,t);this.playerQueue.push(f),e.assetList[i]=t;let g=!0;const m=s=>{if(s.live){var r;const t=new Error(`Interstitials MUST be VOD assets ${e}`),s={fatal:!0,type:v.OTHER_ERROR,details:T.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=(null==(r=this.schedule)?void 0:r.findEventIndex(e.identifier))||-1;return void this.handleAssetItemError(s,e,n,i,t.message)}const n=s.edge-s.fragmentStart,a=t.duration;(g||null===a||n>a)&&(g=!1,this.log(`Interstitial asset "${h}" duration change ${a} > ${n}`),t.duration=n,this.updateSchedule())};f.on(E.LEVEL_UPDATED,(e,{details:t})=>m(t)),f.on(E.LEVEL_PTS_UPDATED,(e,{details:t})=>m(t)),f.on(E.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(e,t)=>{const i=this.getAssetPlayer(h);if(i&&t.tracks){i.off(E.BUFFER_CODECS,p),i.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};f.on(E.BUFFER_CODECS,p);f.on(E.BUFFERED_TO_END,()=>{var i;const s=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${s}`),!s||!this.schedule)return;const r=this.schedule.findEventIndex(e.identifier),n=null==(i=this.schedule.items)?void 0:i[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,t)});const y=t=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return f.once(E.MEDIA_ENDED,y(i)),f.once(E.PLAYOUT_LIMIT_REACHED,y(1/0)),f.on(E.ERROR,(t,s)=>{if(!this.schedule)return;const r=this.getAssetPlayer(h);if(s.details===T.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${s.error} ${e}`)}),f.on(E.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${h}`),s={fatal:!0,type:v.OTHER_ERROR,details:T.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ka(t)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)}),e.reset()}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){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(-1!==i){const e=this.playerQueue[i];this.log(`clear ${e} toSegment: ${t?qa(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(i,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,d&&d.identifier===o||(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Ka(a)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,s;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,a=this.schedule.findEventIndex(r.identifier),o=null==(i=this.schedule.items)?void 0:i[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const d=r.appendInPlace;if(d&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const h=(null==l?void 0:l.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(h&&!G(h,e.tracks)){const t=new Error(`Asset ${Ka(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),i={fatal:!0,type:v.OTHER_ERROR,details:T.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},s=r.findAssetIndex(n);return void this.handleAssetItemError(i,r,a,s,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const s=i.currentTime,r=t.findAssetIndex(e,s),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||s-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const i=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,s,r){if(e.details===T.BUFFER_STALLED_ERROR)return;const n=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?Ka(n):n} ${e.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,h=x({},e,{fatal:!1,errorAction:$t(!0),asset:n,assetListIndex:s,event:t,schedule:d,scheduleIndex:i,player:l});if(this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;const c=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),t.assetList.some(e=>!e.error))for(let e=s;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):c&&c.identifier===a?this.advanceAfterAssetEnded(t,i,s):u&&u.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${qa(i)} error: ${e.error}`);let s=this.timelinePos;-1===s&&(s=this.hls.startPosition);const r=this.updateItem(i,s);if(this.itemsMatch(i,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const n=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(n)}else this.checkStart()}onAssetListLoaded(e,t){var i,s;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((e,t)=>{const i=parseFloat(e.DURATION);this.createAsset(r,t,d,o+d,i,e.URI),d+=i}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const h=this.waitingItem,c=(null==h?void 0:h.event.identifier)===n;this.updateSchedule();const u=null==(s=this.bufferingItem)?void 0:s.event;if(c){var f;const e=this.schedule.findEventIndex(n),t=null==(f=this.schedule.items)?void 0:f[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return r.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${r}`),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==u?void 0:u.identifier)===n){const e=r.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case T.ASSET_LIST_PARSING_ERROR:case T.ASSET_LIST_LOAD_ERROR:case T.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case T.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function il(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(il):Object.keys(e).reduce((t,i)=>(t[i]=il(e[i]),t),{}):e}function sl(e,t){const i=e.loader;if(i!==Xo&&i!==el)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=Xo,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class rl extends ai{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.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(100),this.mediaSource=t.mediaSource;const i=this.media=t.media;Is(i,"playing",this.onMediaPlaying),Is(i,"waiting",this.onMediaWaiting),Is(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(ks(i,"playing",this.onMediaPlaying),ks(i,"waiting",this.onMediaWaiting),ks(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(d)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})));if(!di.getBuffered(n).length)return void(this.nudgeRetry=0);const h=di.bufferInfo(n,e,0),c=h.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const t=nl(this.hls.inFlightFragments,e),i=h.len>2,s=!c||t||c-e>2&&!u.getPartialFragment(e);if(i||s)return;this.moved=!1}const f=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(h.len>0)&&!c)return;const t=Math.max(c,h.start||0)-e,i=!(null==f||!f.live)?2*f.targetduration:2,s=ol(e,u);if(t>0&&(t<=i||s))return void(n.paused||this._trySkipBufferHole(s))}const g=r.detectStallWithCurrentTimeMs,m=self.performance.now(),p=this.waiting;let y=this.stalled;if(null===y){if(!(p>0&&m-p<g))return void(this.stalled=m);y=this.stalled=p}const v=m-y;if(!a&&(v>=g||p)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(E.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(h),!this.media||!this.hls)return}const S=di.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(S,v,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(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&s&&s.length>1&&e>s.end(0)){const i=di.bufferedInfo(di.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){const i=di.timeRangesToArray(s),r=di.bufferedInfo(i,t,0).bufferedIndex;if(r>-1&&r<i.length-1){const t=di.bufferedInfo(i,e,0).bufferedIndex,s=i[r].end,n=i[r+1].start;if((-1===t||t>r)&&n-s<1&&e-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${s} -> ${n} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;let r=ol(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=di.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,i){var s,r;const{fragmentTracker:n,media:a}=this,o=null==(s=this.hls)?void 0:s.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,d=ol(i,n);if(d||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=e.buffered,c=this.adjacentTraversal(e,i);(h&&h.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-i<o.maxBufferHole||c))&&(t>1e3*o.highBufferWatchdogPeriod||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 e=i.getFragAtPos(t,R),r=i.getFragAtPos(s,R);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:r}=this;if(!s&&null!==r&&i&&t){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ht(e)})`);this.warn(s.message),t.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,r=null==(t=this.hls)?void 0:t.config;if(!s||!i||!r)return 0;const n=s.currentTime,a=di.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=r.maxBufferHole,d=a.len>0&&a.len<1&&s.readyState<3,h=o-n;if(h>0&&(t||d)){if(h>r.maxBufferHole){let t=!1;if(0===n){const e=i.getAppendedFrag(0,R);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(nl(this.hls.inFlightFragments,o))return 0;let t=!1,s=e.end;for(;s<o;){const e=ol(s,i);if(!e){t=!0;break}s+=e.duration}if(t)return 0}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,s.currentTime=t,null==e||!e.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),s={type:v.MEDIA_ERROR,details:T.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?s.part=e:s.frag=e),this.hls.trigger(E.ERROR,s)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,r=null==t?void 0:t.config;if(!i||!r)return 0;const n=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){const a=n+(s+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),i.currentTime=a,t.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const i=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(i.message),t.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:e.len,bufferInfo:e})}}}function nl(e,t){const i=al(e.main);if(i&&i.start<=t)return i;const s=al(e.audio);return s&&s.start<=t?s:null}function al(e){if(!e)return null;switch(e.state){case Ds:case ws:case Us:case Ns:return null}return e.frag}function ol(e,t){return t.getAppendedFrag(e,R)||t.getPartialFragment(e)}function ll(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function dl(e,t,i,s,r){let n=new e(t,i,"");try{n.value=s,r&&(n.type=r)}catch(a){n=new e(t,i,ht(r?_({type:r},s):s))}return n}const hl=(()=>{const e=ll();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class cl{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(E.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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&_a(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if("metadata"===i.kind&&"id3"===i.label)return xa(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=ll();if(n)for(let e=0;e<r.length;e++){const t=r[e].type;if(t===yr.emsg&&!i||!s)continue;const a=fr(r[e].data),o=r[e].pts;let l=o+r[e].duration;l>hl&&(l=hl);l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const i=a[e];if(!gr(i)){this.updateId3CueEnds(o,t);const e=dl(n,o,l,i,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){var i;const s=null==(i=this.id3Track)?void 0:i.cues;if(s)for(let i=s.length;i--;){const r=s[i];r.type===t&&r.startTime<e&&r.endTime===hl&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===s?e=>e.type===yr.audioId3&&o:"video"===s?e=>e.type===yr.emsg&&a:e=>e.type===yr.audioId3&&o||e.type===yr.emsg&&a,Ma(r,t,i,e)}}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:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=ll();if(i&&s&&!n){const{fragmentStart:t,fragmentEnd:s}=e;let r=this.assetCue;r?(r.startTime=t,r.endTime=s):a&&(r=this.assetCue=dl(a,t,s,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,d=Object.keys(l);let h=this.dateRangeCuesAppended;var c;if(o&&t)if(null!=(c=o.cues)&&c.length){const e=Object.keys(h).filter(e=>!d.includes(e));for(let t=e.length;t--;){var u;const i=e[t],s=null==(u=h[i])?void 0:u.cues;delete h[i],s&&Object.keys(s).forEach(e=>{const t=s[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(e){}}})}}else h=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==d.length&&m(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<d.length;e++){const t=d[e],i=l[t],s=i.startTime,r=h[t],o=(null==r?void 0:r.cues)||{};let c=(null==r?void 0:r.durationKnown)||!1,u=hl;const{duration:f,endDate:g}=i;if(g&&null!==f)u=s+f,c=!0;else if(i.endOnNext&&!c){const e=d.reduce((e,t)=>{if(t!==i.id){const s=l[t];if(s.class===i.class&&s.startDate>i.startDate&&(!e||i.startDate<e.startDate))return s}return e},null);e&&(u=e.startTime,c=!0)}const m=Object.keys(i.attr);for(let e=0;e<m.length;e++){const l=m[e];if(!vi(l))continue;const d=o[l];if(d)!c||null!=r&&r.durationKnown?Math.abs(d.startTime-s)>.01&&(d.startTime=s,d.endTime=u):d.endTime=u;else if(a){let e=i.attr[l];Ti(l)&&(e=j(e));const r=dl(a,s,u,{key:l,data:e},yr.dateRange);r&&(r.id=t,this.id3Track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}h[t]={cues:o,dateRange:i,durationKnown:c}}}}}class ul{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,s=Math.min(t,Math.max(1,i));this.changeMediaPlaybackRate(e,s)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*s);const d=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,r=e-t-this.edgeStalled,n=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);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(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===T.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(s=this.targetLatency)?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 null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class fl extends En{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach(e=>{const t=e.attrs;let{audioCodec:d,videoCodec:h}=e;d&&(e.audioCodec=d=Ve(d,i)||void 0),h&&(h=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const i=t[e].split(".");i.length>2&&"avc1"===i[0]&&(t[e]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}(h));const{width:c,height:u,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(a||(a=!(!c||!u)),o||(o=!!h),l||(l=!!d),g||d&&!this.isAudioSupported(d)||h&&!this.isVideoSupported(h))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":y,"PATHWAY-ID":v,RESOLUTION:T,"VIDEO-RANGE":E}=t,S=`${`${v||"."}-`}${e.bitrate}-${T}-${p}-${m}-${E}-${y}`;if(r[S])if(r[S].uri===e.url||e.attrs["PATHWAY-ID"])r[S].addGroupId("audio",t.AUDIO),r[S].addGroupId("text",t.SUBTITLES);else{const t=n[S]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const i=this.createLevel(e);r[S]=i,s.push(i)}else{const t=this.createLevel(e);r[S]=t,n[S]=1,s.push(t)}}),this.filterAndSortMediaOptions(s,t,a,o,l)}createLevel(e){const t=new ot(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=ze(e,[])}return t}isAudioSupported(e){return Me(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Me(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,r){var n;let a=[],o=[],l=e;const d=(null==(n=t.stats)?void 0:n.parsing)||{};if((i||s)&&r&&(l=l.filter(({videoCodec:e,videoRange:t,width:i,height:s})=>{return(!!e||!(!i||!s))&&(!!(r=t)&&tt.indexOf(r)>-1);var r})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${ht(t.levels.map(e=>e.attrs.CODECS).filter((e,t,i)=>i.indexOf(e)===t))}`,this.warn(i),e+=` (${i})`);const s=new Error(e);this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:T.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:s,reason:i})}}),void(d.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),gl(a)),t.subtitles&&(o=t.subtitles,gl(o));const h=l.slice(0);l.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return tt.indexOf(e.videoRange)-tt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const i=Ue(e.videoCodec),s=Ue(t.videoCodec);if(i!==s)return s-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const i=Ne(e.codecSet),s=Ne(t.codecSet);if(i!==s)return s-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let c=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length))for(let e=0;e<h.length;e++)if(h[e].pathwayId===l[0].pathwayId){c=h[e];break}this._levels=l;for(let e=0;e<l.length;e++)if(l[e]===c){var u;this._firstLevel=e;const t=c.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const f=r&&!s,g=this.hls.config,m=!(!g.audioStreamController||!g.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:m&&!f&&a.some(e=>!!e.url)};d.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,p)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const i=new Error("invalid level idx"),s=e<0;if(this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.LEVEL_SWITCH_ERROR,level:e,fatal:s,error:i,reason:i.message}),s)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&s&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==s?void 0:s.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?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(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=i}}onError(e,t){!t.fatal&&t.context&&t.context.type===A&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===R){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(s,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(r.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,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(E.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const i=this._levels.filter((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));vs(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&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(E.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(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function gl(e){const t={};e.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function ml(){return self.SourceBuffer||self.WebKitSourceBuffer}function pl(){if(!V())return!1;const e=ml();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class yl extends Vs{constructor(e,t,i){super(e,t,i,"stream-controller",R),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!m(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const i=this.getFwdBufferInfoAtPos(e,t,R,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.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(100),this.level=-1,!this.startFragRequested){let e=s.startLevel;-1===e&&(s.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=s.firstAutoLevel),s.nextLoadLevel=e,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=Ds,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=ws}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case $s:{const{levels:e,level:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=Ds;break}if(this.hls.nextLoadLevel!==this.level){this.state=Ds;break}break}case _s:this.checkRetryDate()}this.state===Ds&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(null===t||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==i||!i[r])return;const n=i[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(E.BUFFER_EOS,e),void(this.state=Us)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===$s||this.waitForLive(n))return this.level=r,this.state=$s,void(this.startFragRequested=!1);const d=a.len,h=this.getMaxBufferLength(n.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&te(u)&&this.fragmentTracker.getState(u)!==Kt){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?Q:J,t=(e===J?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,R)}u=this.getNextFragmentLoopLoading(u,l,a,R,h)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===Vt||s===Ht?te(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,R)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*r.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*s)+1:0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,s=Math.max(n.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case xs:case Cs:case _s:case Os:case Fs:this.state=Ds}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;Is(i,"playing",this.onMediaPlaying),Is(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(ks(i,"playing",this.onMediaPlaying),ks(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let e=0;e<t.levels.length;e++){const r=t.levels[e].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),s=s||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&s&&!function(){var e;const t=ml();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.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}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==Ds)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=$s)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,d=this.fragCurrent;!d||this.state!==Cs&&this.state!==_s||d.level!==t.level&&d.loader&&this.abortCurrentFrag();let h=0;if(a.live||null!=(i=l.details)&&i.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,h),this.hls.trigger(E.LEVEL_UPDATED,{details:a,level:n}),this.state===$s){if(this.waitForCdnTuneIn(a))return;this.state=Ds}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r<s||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&i.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=di.bufferInfo(i,s,0);if(null==(l=e.buffered)||!l.length)return void(i.currentTime=s);if(e.start<=r)return void(i.currentTime=s);const{nextStart:t}=di.bufferedInfo(e.buffered,r,0);t&&(i.currentTime=t)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(t=i.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Tn(this.hls,R,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=-1!==f,m=new oi(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[i.cc];u.push(r,h,c,l,i,s,o.totalduration,d,m,p)}onAudioTrackSwitching(e,t){const i=this.hls,s=2===this.altAudio;if(vt(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.fragmentTracker.removeAllFragments(),i.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),void i.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=vt(t.url,this.hls);if(i){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,r,n=!1;for(const e in i){const t=i[e];if("main"===t.id){if(r=e,s=t,"video"===e){const t=i[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,r=i.type===R;if(r){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Fs&&(this.state=Ds));const e=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),te(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const n=this.media;n&&(!this._hasEnoughToStart&&di.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal)this.state=Ns;else switch(t.details){case T.FRAG_GAP:case T.FRAG_PARSING_ERROR:case T.FRAG_DECRYPT_ERROR:case T.FRAG_LOAD_ERROR:case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_ERROR:case T.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(R,t);break;case T.LEVEL_LOAD_ERROR:case T.LEVEL_LOAD_TIMEOUT:case T.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==$s||(null==(i=t.context)?void 0:i.type)!==A||(this.state=Ds);break;case T.BUFFER_ADD_CODEC_ERROR:case T.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case T.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 T.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Ds,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Q||!this.altAudio){const e=(t===J?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,R),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&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)return void this.log(`could not seek to ${i}, already seeking at ${t}`);const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=di.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${a}`),e.currentTime=i)}}_getAudioCodec(e){let 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}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:i}=this,s=null==e?void 0:e.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=Ds,this.startFragRequested=!1,this.bitrateTest=!1;const r=s.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(E.FRAG_LOADED,e),s.bitrateTest=!1}).catch(t=>{this.state!==ws&&this.state!==Ns&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:d,text:h,id3:c,initSegment:u}=s,{details:f}=l,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Os,u){const e=u.tracks;if(e){const s=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,e,s,r),i.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:s,id:t,tracks:e})}const s=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(m(s)&&(!o||o.baseTime!==s||o.timescale!==n)){const e=u.trackId;this.initPTS[a.cc]={baseTime:s,timescale:n,trackId:e},i.trigger(E.INIT_PTS_FOUND,{frag:a,id:t,initPTS:s,timescale:n,trackId:e})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,i=!e||a.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:s,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:e,endPTS:s,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!i)return void this.backtrack(a);i&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,s,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,e,s,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,t||i)}else{if(!t&&!i)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=g;o&&(o.elementaryStreams[Q]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),a.setElementaryStreamInfo(Q,e,t,i,s),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const e={id:t,frag:a,details:f,samples:c.samples};i.trigger(E.FRAG_PARSING_METADATA,e)}if(f&&h){const e={id:t,frag:a,details:f,samples:h.samples};i.trigger(E.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${te(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==Os)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:a}=t;if(r){const i=e.audioCodec;let s=Ge(r.codec,i);"mp4a"===s&&(s="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){s&&(s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===n.indexOf("firefox")&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),i&&i!==s&&this.log(`Swapping manifest audio codec "${i}" for "${s}"`),r.levelCodec=s,r.id=R,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=R;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:e,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,R)}get maxBufferLength(){const{levels:e,level:t}=this,i=null==e?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=Ds}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const i=e.currentTime;if(di.isBuffered(e,i)?t=this.getAppendedFrag(i):di.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,i=t.level;e&&t.sn===e.sn&&e.level===i||(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(E.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return m(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(m(t)){const e=this.getLevelDetails(),i=this.currentFrag||(e?Et(null,e.fragments,t):null);if(i){const e=i.programDateTime;if(null!==e){const s=e+1e3*(t-i.start);return new Date(s)}}}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 vl extends M{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var t;if(e&&e!==(null==(t=s.context)?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=T.KEY_LOAD_ERROR,i,s,r){return new ni({type:v.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,r=t.length;s<r;s++){const n=t[s];if(e.cc<=n.cc&&(!te(e)||!te(n)||e.sn<n.sn)||!i&&s==r-1)return this.emeController.selectKeySystemFormat(n).then(e=>{if(!this.emeController)return;n.setKeyFormat(e);const t=Fi(e);return t?this.emeController.getKeySystemAccess([t]):void 0})}if(this.config.requireKeySystemAccessOnStart){const e=Ni(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const i=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,T.KEY_LOAD_ERROR,i))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,T.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=Tl(r);let o=this.keyIdToKeyInfo[a];if(null!=(i=o)&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(s=o)&&s.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(t=>{const{keyInfo:i}=t;return r.key=i.decryptdata.key,{frag:e,keyInfo:i}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+K(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,T.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&null!=(s=t.initSegment)&&s.data){const i=function(e){const t=[];return Se(e,e=>t.push(e.subarray(8,24))),t}(t.initSegment.data);if(i.length){const t=i[0];t.some(e=>0!==e)&&(this.log(`Using keyId found in init segment ${K(t)}`),e.decryptdata.keyId=t,Hi.setKeyIdForUri(e.decryptdata.uri,t))}}const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(t=>(e.mediaKeySessionContext=t,i))).catch(i=>{throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=new(0,i.loader)(i);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((r,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,i,s)=>{const{frag:a,keyInfo:o}=i,l=Tl(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,T.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(e,i,s,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,T.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),s,_({url:a.url,data:void 0},e)))},onTimeout:(e,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,T.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(e,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,T.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(a,l,d)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const n=Tl(i.decryptdata)||s;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function Tl(e){if(e.keyFormat!==_i){const t=e.keyId;if(t)return K(t)}return e.uri}function El(e){const{type:t}=e;switch(t){case b:return I;case L:return k;default:return R}}function Sl(e,t){let i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}class Al{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,r=new(i||s)(t);return this.loaders[e.type]=r,r}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:S,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:A,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:b,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:L,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const i=this.loaders[A];if(i){const e=i.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(i.abort(),delete this.loaders[A])}}load(e){var t;const i=this.hls.config;let s,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,i=r.context;if(i&&i.levelOrTrack===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives))return void(i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(s=e.type===S?i.manifestLoadPolicy.default:x({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),m(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===A&&null!==e.level?t=this.hls.levels[e.level].details:e.type===b&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===L&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,i=t.targetduration;if(e&&i){const t=1e3*Math.max(3*e,.8*i);s=x({},s,{maxTimeToFirstByteMs:Math.min(t,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,s.maxTimeToFirstByteMs)})}}}const n=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=e.data;t.parsing.start=performance.now(),Xi.isMediaPlaylist(n)||i.type!==S?this.handleTrackOrLevelPlaylist(e,t,i,s||null,r):this.handleMasterPlaylist(e,t,i,s)},onError:(e,t,i,s)=>{this.handleNetworkError(t,i,!1,e,s)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};r.load(e,a,o)}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 r=this.hls,n=e.data,a=Sl(e,i),o=Xi.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,i,o.playlistParsingError,s,t);const{contentSteering:l,levels:d,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f,d.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:r}=e;for(let n=t.length;n--;){const a=t[n];Me(a,"audio",i)?(e.audioCodec=s=s?`${s},${a}`:a,Ce.audio[s.substring(0,4)]=2,t.splice(n,1)):Me(a,"video",i)&&(e.videoCodec=r=r?`${r},${a}`:a,Ce.video[r.substring(0,4)]=2,t.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Xi.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some(e=>!e.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new yi({}),bitrate:0,url:""}))}r.trigger(E.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:s,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,s,r){const n=this.hls,{id:a,level:o,type:l}=i,d=Sl(e,i),h=m(o)?o:m(a)?a:0,c=El(i),u=Xi.parseLevelPlaylist(e.data,d,h,c,0,this.variableList);if(l===S){const e={attrs:new yi({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=t.loading.start+gs(u,0),n.trigger(E.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=u,this.handlePlaylistLoaded(u,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:T.MANIFEST_PARSING_ERROR,fatal:t.type===S,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===A?n+=`: ${e.level} id: ${e.id}`:e.type!==b&&e.type!==L||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=T.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case S:o=i?T.MANIFEST_LOAD_TIMEOUT:T.MANIFEST_LOAD_ERROR,l=!0;break;case A:o=i?T.LEVEL_LOAD_TIMEOUT:T.LEVEL_LOAD_ERROR,l=!1;break;case b:o=i?T.AUDIO_TRACK_LOAD_TIMEOUT:T.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case L:o=i?T.SUBTITLE_TRACK_LOAD_TIMEOUT:T.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);const h={type:v.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:r};if(s){const i=(null==t?void 0:t.url)||e.url;h.response=_({url:i,data:void 0},s)}this.hls.trigger(E.ERROR,h)}handlePlaylistLoaded(e,t,i,s,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:h,groupId:c,deliveryDirectives:u}=s,f=Sl(t,s),g=El(s);let m="number"==typeof s.level&&g===R?l:void 0;const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:T.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:s,level:m,parent:g,networkDetails:r,stats:i});e.playlistParsingError=null}if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:T.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:s,level:m,parent:g,networkDetails:r,stats:i})}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case S:case A:if(m)if(d){if(d!==a.levels[m]){const e=a.levels.indexOf(d);e>-1&&(m=e)}}else m=0;a.trigger(E.LEVEL_LOADED,{details:e,levelInfo:d||a.levels[0],level:m||0,id:h||0,stats:i,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===S});break;case b:a.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:u});break;case L:a.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:u})}}}class bl{static get version(){return Ys}static isMSESupported(){return pl()}static isSupported(){return function(){if(!pl())return!1;const e=V();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(Fe(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(Fe(t,"audio"))))}()}static getMediaSource(){return V()}static get Events(){return E}static get MetadataSchema(){return yr}static get ErrorTypes(){return v}static get ErrorDetails(){return T}static get DefaultConfig(){return bl.defaultConfig?bl.defaultConfig:tl}static set DefaultConfig(e){bl.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new qs,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,i){const s=U();if("object"==typeof console&&!0===e||"object"==typeof e){const r=["debug","log","info","warn","error"];r.forEach(t=>{s[t]=N(t,e,i)});try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.6.14`)}catch(e){return U()}r.forEach(t=>{B[t]=N(t,e)})}else x(B,s);return s}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(e,t,i){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"');const s=il(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach(i=>{const r=`${e}Loading${i}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=s[n].default;switch(t[n]={default:e},i){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${ht(t[n])}`)}),_(_({},s),t)}(bl.DefaultConfig,e,t);this.userConfig=e,i.progressive&&sl(i,t);const{abrController:s,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=i,l=new a(this),d=this.abrController=new s(this),h=new jt(this),c=i.interstitialsController,u=c?this.interstitialsController=new c(this,bl):null,f=this.bufferController=new r(this,h),g=this.capLevelController=new n(this),m=new o(this),p=new Al(this),y=i.contentSteeringController,v=y?new y(this):null,T=this.levelController=new fl(this,v),S=new cl(this),A=new vl(this.config,this.logger),b=this.streamController=new yl(this,h,A),L=this.gapController=new rl(this,h);g.setStreamController(b),m.setStreamController(b);const R=[p,T,b];u&&R.splice(1,0,u),v&&R.splice(1,0,v),this.networkControllers=R;const I=[d,f,L,g,m,S,h];this.audioTrackController=this.createController(i.audioTrackController,R);const k=i.audioStreamController;k&&R.push(this.audioStreamController=new k(this,h,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,R);const P=i.subtitleStreamController;P&&R.push(this.subtititleStreamController=new P(this,h,A)),this.createController(i.timelineController,I),A.emeController=this.emeController=this.createController(i.emeController,I),this.cmcdController=this.createController(i.cmcdController,I),this.latencyController=this.createController(ul,I),this.coreComponents=I,R.push(l);const w=l.onErrorOut;"function"==typeof w&&this.on(E.ERROR,w,l),this.on(E.MANIFEST_LOADED,p.onManifestLoaded,p)}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(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const i=e===E.ERROR;this.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(E.ERROR,{type:v.OTHER_ERROR,details:T.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}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(E.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,s=this._url=z.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[R]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[I]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[k]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)})}}}()),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-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){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){(function(e){return et.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}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(s=-1===t&&null!=e&&e.length?e.length-1:t,i)for(let t=s;t--;){const s=e[t].attrs["HDCP-LEVEL"];if(s&&s<=i)return t}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?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 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}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(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Qe(e,ut(t),navigator.mediaCapabilities)}}function Ll(){const e=navigator.userAgent,t=function(){var e;if("userAgentData"in navigator&&(null===(e=navigator.userAgentData)||void 0===e?void 0:e.platform))return navigator.userAgentData.platform;const t=navigator.userAgent;return/Mac|iPhone|iPad|iPod/i.test(t)?/iPhone|iPad|iPod/i.test(t)?"iPhone":"MacIntel":/Win/i.test(t)?"Win32":/Linux/i.test(t)?/Android/i.test(t)?"Linux armv8l":"Linux x86_64":/CrOS/i.test(t)?"CrOS":navigator.platform||"Unknown"}();let i="Unknown",s="0",r=0,n=!1,a=!1,o=!0,l=!0,d="ima";if(/Web0S|webOS/i.test(e)){i="LG WebOS",n=!0;const t=e.match(/Web0S[/\s]*([\d.]+)/i);if(s=t&&t[1]?t[1]:"Unknown","Unknown"!==s){const e=s.split(".");r=e[0]?parseInt(e[0],10):0}}else if(/Tizen/i.test(e)){i="Samsung Tizen",n=!0;const t=e.match(/Tizen[/\s]*([\d.]+)/i);if(s=t&&t[1]?t[1]:"Unknown","Unknown"!==s){const e=s.split(".");r=e[0]?parseInt(e[0],10):0}}else/SMART-TV|SmartTV/i.test(e)?(i="Smart TV",n=!0):/NetCast/i.test(e)?(i="LG NetCast",n=!0,a=!0):/BRAVIA/i.test(e)&&(i="Sony BRAVIA",n=!0);const h=function(e){const t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e),c=function(e){const t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e);return h>0&&(n||(i="Chrome",s=h.toString(),r=h),h<50&&(o=!1,l=!1,a=!0,d="hls")),c>0&&c<600&&(l=!1,n&&(a=!0,o=!1,d="hls")),"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(l=!1,o=!1,d="hls"),"undefined"==typeof URLSearchParams&&(l=!1),{name:i,version:s,majorVersion:r,isSmartTV:n,isLegacyTV:a,platform:t,supportsIMA:o,supportsModernJS:l,recommendedAdPlayer:d}}function Rl(){const e=Ll();if(e.isLegacyTV)return!1;if("undefined"==typeof document||"function"!=typeof document.createElement)return!1;try{if(!document.createElement("video"))return!1}catch(e){return!1}return"undefined"!=typeof Promise&&e.supportsIMA}function Il(e=!1){if(!e)return;const t=Ll(),i=Rl();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",{browser:`${t.name} ${t.version}`,platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsIMA:i,supportsModernJS:t.supportsModernJS,recommendedAdPlayer:t.recommendedAdPlayer,userAgent:navigator.userAgent})}function kl(){const e=Ll(),t={};return!e.isLegacyTV&&e.supportsIMA||(t.adPlayerType="hls"),e.isSmartTV&&(t.allowNativeHls=!0),t}function Pl(e,t){let i=!1,s=!1,r=!1,n="number"!=typeof e.volume||Number.isNaN(e.volume)?1:Math.max(0,Math.min(1,e.volume));const a=new Map,o=new Map,l=new Map;let d,h,c,u,f,g;function m(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function p(){s&&(e.style.visibility="visible",e.style.transition="opacity 0.3s ease-in-out",e.offsetHeight,e.style.opacity="1",e.muted=r,e.volume=n,s=!1)}function y(){const e=document.createElement("video");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="contain",e.style.backgroundColor="transparent",e.style.zIndex="15",e.playsInline=!0,e.muted=!1,e.volume=r?0:n,e.style.opacity="0",e.addEventListener("canplay",()=>{e.style.opacity="1"},{once:!0}),e}function v(e,t){const i=a.get(e);if(i)for(const e of Array.from(i))try{e(t)}catch{}}function T(){var e,t,i;if(!Rl())return console.warn("[IMA] Google IMA SDK is not supported on this browser. Please use HLS ad player instead."),Promise.reject(new Error("Google IMA SDK not supported on this browser"));try{const t=window.frameElement,i=(null===(e=null==t?void 0:t.getAttribute)||void 0===e?void 0:e.call(t,"sandbox"))||"";if(i){const e=new Set(i.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0));e.has("allow-scripts")||console.error("StormcloudVideoPlayer: The host page is inside a sandboxed iframe without 'allow-scripts'. Google IMA cannot run ads within sandboxed frames. Remove the sandbox attribute or include 'allow-scripts allow-same-origin'.")}}catch{}if("undefined"!=typeof window&&(null===(t=window.google)||void 0===t?void 0:t.ima))return Promise.resolve();const s=document.querySelector('script[data-ima="true"]');return s?(null===(i=window.google)||void 0===i?void 0:i.ima)?Promise.resolve():new Promise((e,t)=>{const i=setTimeout(()=>{t(new Error("IMA SDK load timeout"))},1e4);s.addEventListener("load",()=>{clearTimeout(i),e()}),s.addEventListener("error",()=>{clearTimeout(i),t(new Error("IMA SDK load failed"))})}):new Promise((e,t)=>{const i=document.createElement("script");i.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",i.async=!0,i.defer=!0,i.setAttribute("data-ima","true"),i.onload=()=>e(),i.onerror=()=>t(new Error("IMA SDK load failed")),document.head.appendChild(i)})}let E=0;let S,A,b;function L(t,i){const s=new t.ima.AdsRequest;console.log("[IMA] 📡 Requesting VAST from URL (letting IMA fetch fresh)"),s.adTagUrl=i;const r=e.offsetWidth||e.clientWidth||640,n=e.offsetHeight||e.clientHeight||360;if(s.linearAdSlotWidth=r,s.linearAdSlotHeight=n,s.nonLinearAdSlotWidth=r,s.nonLinearAdSlotHeight=n,"function"==typeof s.setAdWillAutoPlay)try{const t=!e.paused||e.autoplay;s.setAdWillAutoPlay(t)}catch(e){console.warn("[IMA] Failed to call setAdWillAutoPlay:",e)}if("function"==typeof s.setAdWillPlayMuted)try{const t=e.muted||0===e.volume;s.setAdWillPlayMuted(t)}catch(e){console.warn("[IMA] Failed to call setAdWillPlayMuted:",e)}s.vastLoadTimeout=1e4,c.requestAds(s)}function R(){var t;if(f)return;const i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="transparent",i.style.transition="opacity 0.3s ease-in-out, background-color 0.3s ease-in-out",i.style.opacity="0",null===(t=e.parentElement)||void 0===t||t.appendChild(i),f=i}function I(){if(h){try{h.destroy()}catch{}h=void 0}d&&(d.style.opacity="0")}return{initialize(){T().then(()=>{var e;const t=window.google;if(R(),!u&&f){d||(d=y(),f.appendChild(d)),u=new t.ima.AdDisplayContainer(f,d);try{null===(e=u.initialize)||void 0===e||e.call(u)}catch{}}}).catch(()=>{})},async requestAds(a){if(!a||""===a.trim()){const e=new Error("VAST tag URL is empty or undefined");return console.warn("[IMA] ❌",e.message),Promise.reject(e)}try{new URL(a)}catch(e){const t=new Error(`Invalid VAST tag URL format: ${a}`);return console.warn("[IMA] ❌",t.message),Promise.reject(t)}if(i)return console.warn("[IMA] ⚠️ Cannot request new ads while an ad is playing. Call stop() first."),Promise.reject(new Error("Ad already playing - cannot request new ads"));let o;I(),b=void 0,A=void 0,S=new Promise((e,t)=>{A=e,b=t,o=t,setTimeout(()=>{b&&(b(new Error("Ad request timeout")),b=void 0,A=void 0)},1e4)});try{await T();const l=window.google;if(g=a,E=0,!u){const t=document.createElement("div");if(t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.right="0",t.style.bottom="0",t.style.display="none",t.style.alignItems="center",t.style.justifyContent="center",t.style.pointerEvents="none",t.style.zIndex="10",t.style.backgroundColor="transparent",t.style.transition="opacity 0.3s ease-in-out, background-color 0.3s ease-in-out",t.style.opacity="0",!e.parentElement)throw new Error("Video element has no parent for ad container");e.parentElement.appendChild(t),f=t,d||(d=y(),f.appendChild(d)),u=new l.ima.AdDisplayContainer(t,d)}const R=e.offsetWidth||e.clientWidth,k=e.offsetHeight||e.clientHeight;if(!R||!k||0===R||0===k){const e=new Error(`Invalid video dimensions: ${R}x${k}. Cannot initialize ads.`);return console.warn("[IMA]",e.message),null==o||o(e),b=void 0,A=void 0,Promise.reject(e)}if(!c){const a=new l.ima.AdsLoader(u);c=a,c.addEventListener(l.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,a=>{try{const o=new l.ima.AdsRenderingSettings;o.enablePreloading=!0,h=a.getAdsManager(e,o);const c=l.ima.AdEvent.Type,u=l.ima.AdErrorEvent.Type;h.addEventListener(u.AD_ERROR,s=>{var r,n;const a=s.getError();if(console.error("[DEBUG-ERROR] ❌ AD_ERROR:",null===(r=a.getMessage)||void 0===r?void 0:r.call(a)),I(),i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p(),b&&(b(new Error("Ad playback error")),b=void 0,A=void 0),g&&E<2){const e=500*Math.pow(2,E++);window.setTimeout(()=>{try{L(l,g)}catch{}},e)}else v("ad_error"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&(null===(n=e.play())||void 0===n||n.catch(()=>{}))}),h.addEventListener(c.CONTENT_PAUSE_REQUESTED,()=>{(null==t?void 0:t.continueLiveStreamDuringAds)||e.pause(),i=!0,m(!0),v("content_pause")}),h.addEventListener(c.STARTED,()=>{m(!0),s||(e.style.transition="opacity 0.3s ease-in-out",e.style.opacity="0",setTimeout(()=>{e.style.visibility="hidden"},300),e.muted=!0,e.volume=0,s=!0),d&&(d.volume=r?0:n,d.muted=r),f&&(f.style.pointerEvents="auto",f.style.display="flex",f.style.backgroundColor="#000",f.offsetHeight,f.style.opacity="1")}),h.addEventListener(c.CONTENT_RESUME_REQUESTED,()=>{i=!1,m(!1),v("content_resume")}),h.addEventListener(c.ALL_ADS_COMPLETED,()=>{i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p(),!(null==t?void 0:t.continueLiveStreamDuringAds)&&e.paused&&e.play().catch(()=>{}),v("all_ads_completed")}),A&&(A(),A=void 0,b=void 0)}catch(s){console.error("[IMA] Error setting up ads manager:",s),i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p(),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(()=>{}),b&&(b(new Error("Failed to setup ads manager")),b=void 0,A=void 0),v("ad_error")}},!1),c.addEventListener(l.ima.AdErrorEvent.Type.AD_ERROR,s=>{var r;const n=s.getError();console.error("[DEBUG-ERROR] ❌ ADS_LOADER ERROR:",null===(r=n.getMessage)||void 0===r?void 0:r.call(n)),i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p(),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(()=>{}),b&&(b(new Error("Ads loader error")),b=void 0,A=void 0),v("ad_error")},!1)}return L(l,a),S}catch(e){return console.error("[IMA] Failed to request ads:",e),null==o||o(e),b=void 0,A=void 0,Promise.reject(e)}},async preloadAds(e){if(!e||""===e.trim())return Promise.resolve();if(o.has(e))return Promise.resolve();const t=l.get(e);if(t)return t;const i=async function(e){const t=await fetch(e,{mode:"cors"});if(!t.ok)throw new Error(`Failed to preload VAST: ${t.status}`);return t.text()}(e).then(t=>{o.set(e,t)}).catch(()=>{o.delete(e)}).finally(()=>{l.delete(e)});return l.set(e,i),i},hasPreloadedAd:e=>o.has(e),async play(){var s,a;if(!(null===(s=window.google)||void 0===s?void 0:s.ima)||!u)return Promise.reject(new Error("IMA SDK not available"));if(!h)return Promise.reject(new Error("No ads manager"));try{const t=e.clientWidth||640,s=e.clientHeight||360;h.init(t,s,window.google.ima.ViewMode.NORMAL),i=!0;const a=r?0:n;d&&(d.volume=a,d.muted=r);try{h.setVolume(a)}catch{}return h.start(),Promise.resolve()}catch(s){return console.error("[IMA] ❌ Error starting ad:",s),i=!1,m(!1),(null==t?void 0:t.continueLiveStreamDuringAds)||null===(a=e.play())||void 0===a||a.catch(()=>{}),Promise.reject(s)}},async stop(){var e;i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none")},300)),p();try{null===(e=null==h?void 0:h.stop)||void 0===e||e.call(h)}catch{}I()},destroy(){var e;I(),i=!1,m(!1),f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.pointerEvents="none",f.style.display="none",f.parentElement&&f.parentElement.removeChild(f),f=void 0,d=void 0)},300)),p();try{null===(e=null==c?void 0:c.destroy)||void 0===e||e.call(c)}catch{}u=void 0,c=void 0,s=!1,o.clear(),l.clear()},isAdPlaying:()=>i,resize(e,t){var i;if(h&&(null===(i=window.google)||void 0===i?void 0:i.ima))try{console.log(`[IMA] Resizing ads manager to ${e}x${t}`),h.resize(e,t,window.google.ima.ViewMode.NORMAL)}catch(e){console.warn("[IMA] Error resizing ads manager:",e)}else console.warn("[IMA] Cannot resize: No ads manager or IMA SDK available")},on(e,t){a.has(e)||a.set(e,new Set),a.get(e).add(t)},off(e,t){var i;null===(i=a.get(e))||void 0===i||i.delete(t)},updateOriginalMutedState(e,t){const i="number"!=typeof t||Number.isNaN(t)?n:Math.max(0,Math.min(1,t));r=e,n=i},getOriginalMutedState:()=>r,getOriginalVolume:()=>n,setAdVolume(e){const t=Math.max(0,Math.min(1,e));if(d&&i&&(d.volume=t,d.muted=0===t),h&&i)try{h.setVolume(t)}catch{}},getAdVolume(){if(d&&i)return d.volume;if(h&&i)try{return h.getVolume()}catch(e){return console.warn("[IMA] Failed to get ad volume:",e),1}return 1},showPlaceholder(){R(),f&&(f.style.display="flex",f.style.backgroundColor="#000",f.offsetHeight,f.style.opacity="1",f.style.pointerEvents="auto")},hidePlaceholder(){f&&(f.style.opacity="0",f.style.backgroundColor="transparent",setTimeout(()=>{f&&(f.style.display="none",f.style.pointerEvents="none")},300))}}}function wl(e,t){let i=!1,s=!1,r=Math.max(0,Math.min(1,e.volume||1));const n=new Map,a=null==t?void 0:t.licenseKey,o=null==t?void 0:t.mainHlsInstance;let l,d,h,c,u;const f=new Map,g=new Map;let m=!1,p=[],y={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function v(e,t){const i=n.get(e);if(i)for(const s of Array.from(i))try{s(t)}catch(t){console.warn(`[HlsAdPlayer] Error in event listener for ${e}:`,t)}}function T(e){e&&0!==e.length&&e.forEach(e=>{try{let t=e;u&&(t=`${t}${t.includes("?")?"&":"?"}session_id=${u}`),a&&(t=`${t}${t.includes("?")?"&":"?"}license_key=${a}`);new Image(1,1).src=t,console.log(`[HlsAdPlayer] Fired tracking pixel: ${t}`)}catch(e){console.warn("[HlsAdPlayer] Error firing tracking pixel:",e)}})}function E(e){if(0===e.length)throw new Error("No media files available");const t=e[0];if(!t)throw new Error("No media files available");if(1===e.length)return t;const i=function(){if(!o||!o.levels)return null;const e=o.currentLevel;if(-1===e||!o.levels[e]){const e=o.loadLevel;if(-1!==e&&o.levels[e]){const t=o.levels[e];return{width:t.width||1920,height:t.height||1080,bitrate:t.bitrate||5e6}}return null}const t=o.levels[e];return{width:t.width||1920,height:t.height||1080,bitrate:t.bitrate||5e6}}();if(!i)return console.log("[HlsAdPlayer] No main stream quality info, using first media file"),t;console.log("[HlsAdPlayer] Main stream quality:",i);const s=e.map(e=>{const t=Math.abs(e.width-i.width)+Math.abs(e.height-i.height),s=1e3*(e.bitrate||5e3),r=Math.abs(s-i.bitrate);return{file:e,score:2*t+r/1e3,resolutionDiff:t,bitrateDiff:r}});s.sort((e,t)=>e.score-t.score);const r=s[0];return r?(console.log("[HlsAdPlayer] Selected media file:",{url:r.file.url,resolution:`${r.file.width}x${r.file.height}`,bitrate:r.file.bitrate,score:r.score,resolutionDiff:r.resolutionDiff,bitrateDiff:r.bitrateDiff}),r.file):(console.log("[HlsAdPlayer] No best match found, using first media file"),t)}async function S(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch VAST: ${t.statusText}`);const i=await t.text();return console.log("[HlsAdPlayer] VAST XML received"),console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):",i.substring(0,2e3)),function(e){var t,i,s,r;try{const n=(new DOMParser).parseFromString(e,"text/xml"),a=n.querySelector("parsererror");if(a)return console.error("[HlsAdPlayer] XML parsing error (malformed VAST XML):",a.textContent),null;const o=n.querySelector("Ad");if(!o)return console.warn("[HlsAdPlayer] No Ad element found in VAST XML"),null;const l=o.getAttribute("id")||"unknown",d=(null===(t=n.querySelector("AdTitle"))||void 0===t?void 0:t.textContent)||"Ad",h="empty"===l||d.toLowerCase().includes("no ad available")||"no ad available"===d.toLowerCase(),c=((null===(i=n.querySelector("Duration"))||void 0===i?void 0:i.textContent)||"00:00:30").split(":"),u=3600*parseInt(c[0]||"0",10)+60*parseInt(c[1]||"0",10)+parseInt(c[2]||"0",10),f=n.querySelectorAll("MediaFile"),g=[];if(console.log(`[HlsAdPlayer] Found ${f.length} MediaFile element(s) in VAST XML`),f.forEach((e,t)=>{var i;const s=e.getAttribute("type")||"",r=(null===(i=e.textContent)||void 0===i?void 0:i.trim())||"",n=e.getAttribute("width")||"",a=e.getAttribute("height")||"";if(console.log(`[HlsAdPlayer] MediaFile ${t}: type="${s}", url="${r}", width="${n}", height="${a}"`),"application/x-mpegURL"===s||s.includes("m3u8")){if(!r)return void console.warn(`[HlsAdPlayer] MediaFile ${t} has HLS type but empty URL`);const i=e.getAttribute("bitrate"),o=i?parseInt(i,10):void 0;g.push({url:r,type:s,width:parseInt(n||"1920",10),height:parseInt(a||"1080",10),bitrate:o&&o>0?o:void 0}),console.log(`[HlsAdPlayer] Added HLS MediaFile: ${r}`)}else console.log(`[HlsAdPlayer] MediaFile ${t} ignored (type="${s}" is not HLS)`)}),0===g.length)return h?console.warn("[HlsAdPlayer] No ads available (VAST response indicates no ads)"):console.warn("[HlsAdPlayer] No HLS media files found in VAST XML"),null;const m={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],mute:[],unmute:[],pause:[],resume:[],fullscreen:[],exitFullscreen:[],skip:[],error:[]};n.querySelectorAll("Impression").forEach(e=>{var t;const i=null===(t=e.textContent)||void 0===t?void 0:t.trim();i&&m.impression.push(i)}),n.querySelectorAll("Tracking").forEach(e=>{var t;const i=e.getAttribute("event"),s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(i&&s){const e=i;m[e]&&m[e].push(s)}});const p=null===(r=null===(s=n.querySelector("ClickThrough"))||void 0===s?void 0:s.textContent)||void 0===r?void 0:r.trim();return{id:l,title:d,duration:u,mediaFiles:g,trackingUrls:m,clickThrough:p}}catch(e){return console.error("[HlsAdPlayer] Error parsing VAST XML:",e),null}}(i)}function A(){l&&c&&(l.addEventListener("timeupdate",()=>{if(!c||!l)return;const e=l.currentTime/c.duration;e>=.25&&!y.firstQuartile&&(y.firstQuartile=!0,T(c.trackingUrls.firstQuartile)),e>=.5&&!y.midpoint&&(y.midpoint=!0,T(c.trackingUrls.midpoint)),e>=.75&&!y.thirdQuartile&&(y.thirdQuartile=!0,T(c.trackingUrls.thirdQuartile))}),l.addEventListener("playing",()=>{c&&!y.start&&(y.start=!0,T(c.trackingUrls.start),console.log("[HlsAdPlayer] Ad started playing"))}),l.addEventListener("ended",()=>{c&&!y.complete&&(y.complete=!0,T(c.trackingUrls.complete),console.log("[HlsAdPlayer] Ad completed"),function(){console.log("[HlsAdPlayer] Handling ad completion"),i=!1,b(!1),v("content_resume");const t=window.setTimeout(()=>{if(m)return void console.log("[HlsAdPlayer] Player destroyed, skipping post-completion check");"true"===e.dataset.stormcloudAdPlaying&&(console.log("[HlsAdPlayer] Still in ad pod - keeping ad container visible (black screen)"),h&&(h.style.display="flex",h.style.pointerEvents="auto"));const i=p.indexOf(t);-1!==i&&p.splice(i,1)},50);p.push(t)}())}),l.addEventListener("error",e=>{console.error("[HlsAdPlayer] Ad video error:",e),c&&T(c.trackingUrls.error),L()}),l.addEventListener("volumechange",()=>{c&&(l.muted?T(c.trackingUrls.mute):T(c.trackingUrls.unmute))}),l.addEventListener("pause",()=>{c&&!l.ended&&T(c.trackingUrls.pause)}),l.addEventListener("play",()=>{c&&l.currentTime>0&&T(c.trackingUrls.resume)}))}function b(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function L(){console.log("[HlsAdPlayer] Handling ad error"),i=!1,b(!1);const n=e.muted;e.muted=s,e.volume=s?0:r,console.log(`[HlsAdPlayer] Restored mute state: ${n} -> ${s}`),h&&(h.style.display="none",h.style.pointerEvents="none"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(()=>{}),v("ad_error")}return{initialize(){var t;if(console.log("[HlsAdPlayer] Initializing"),!h){const i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(i),h=i}},async requestAds(e){if(console.log("[HlsAdPlayer] Requesting ads:",e),i)return console.warn("[HlsAdPlayer] Cannot request new ads while an ad is playing"),Promise.reject(new Error("Ad already playing"));try{let t;return u=`session-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,f.has(e)?(t=f.get(e),f.delete(e),console.log("[HlsAdPlayer] Using preloaded VAST response:",e)):t=await S(e),t?(c=t,console.log(`[HlsAdPlayer] Ad parsed: ${t.title}, duration: ${t.duration}s`),T(t.trackingUrls.impression),y.impression=!0,Promise.resolve()):(console.warn("[HlsAdPlayer] No ads available from VAST response"),v("ad_error"),Promise.resolve())}catch(e){return console.error("[HlsAdPlayer] Error requesting ads:",e),v("ad_error"),Promise.reject(e)}},async preloadAds(e){if(!e||""===e.trim())return Promise.resolve();if(f.has(e))return Promise.resolve();const t=g.get(e);if(t)return t;const i=S(e).then(t=>{t&&(f.set(e,t),console.log("[HlsAdPlayer] Cached VAST response for preloading:",e))}).catch(t=>{console.warn("[HlsAdPlayer] Failed to preload VAST response:",t),f.delete(e)}).finally(()=>{g.delete(e)});return g.set(e,i),i},hasPreloadedAd:e=>f.has(e),async play(){if(!c)return console.warn("[HlsAdPlayer] Cannot play: No ad loaded (no ads available)"),Promise.reject(new Error("No ad loaded"));console.log("[HlsAdPlayer] Starting ad playback");try{l||(l=function(){const e=document.createElement("video");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="contain",e.style.backgroundColor="#000",e.playsInline=!0,e.muted=!1,e.volume=1,console.log(`[HlsAdPlayer] Created ad video element with volume ${e.volume}`),e}(),null==h||h.appendChild(l),A()),y={impression:y.impression,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};const n=e.volume;if(r=Math.max(0,Math.min(1,n||r)),(null==t?void 0:t.continueLiveStreamDuringAds)?console.log("[HlsAdPlayer] Content continues (Live mode)"):(e.pause(),console.log("[HlsAdPlayer] Content paused (VOD mode)")),console.log("[HlsAdPlayer] FORCE MUTING main video"),e.muted=!0,e.volume=0,i=!0,b(!0),l){const e=s?0:r;l.volume=Math.max(0,Math.min(1,e)),l.muted=!1,console.log(`[HlsAdPlayer] Set ad video volume to ${l.volume}, muted: ${l.muted}, originalMutedState: ${s}, contentVolume: ${n}`)}h&&(h.style.display="flex",h.style.pointerEvents="auto"),v("content_pause");const a=E(c.mediaFiles);if(!a)throw new Error("No media file available for ad");if(console.log(`[HlsAdPlayer] Loading ad from: ${a.url}`),bl.isSupported())d&&d.destroy(),d=new bl({enableWorker:!0,lowLatencyMode:!1}),d.loadSource(a.url),d.attachMedia(l),d.on(bl.Events.MANIFEST_PARSED,()=>{console.log("[HlsAdPlayer] HLS manifest parsed, starting playback"),l.play().catch(e=>{console.error("[HlsAdPlayer] Error starting ad playback:",e),L()})}),d.on(bl.Events.ERROR,(e,t)=>{console.error("[HlsAdPlayer] HLS error:",t),t.fatal&&L()});else{if(!l.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS not supported");l.src=a.url,l.play().catch(e=>{console.error("[HlsAdPlayer] Error starting ad playback:",e),L()})}return Promise.resolve()}catch(e){return console.error("[HlsAdPlayer] Error playing ad:",e),L(),Promise.reject(e)}},async stop(){console.log("[HlsAdPlayer] Stopping ad"),i=!1,b(!1),h&&(h.style.display="none",h.style.pointerEvents="none"),d&&(d.destroy(),d=void 0),l&&(l.pause(),l.src=""),c=void 0},destroy(){console.log("[HlsAdPlayer] Destroying"),m=!0;for(const e of p)clearTimeout(e);p=[],i=!1,b(!1),e.muted=s,e.volume=s?0:r,d&&(d.destroy(),d=void 0),l&&(l.pause(),l.src="",l.remove(),l=void 0),(null==h?void 0:h.parentElement)&&h.parentElement.removeChild(h),h=void 0,c=void 0,n.clear(),f.clear(),g.clear()},isAdPlaying:()=>i,resize(e,t){console.log(`[HlsAdPlayer] Resizing to ${e}x${t}`),h&&(h.style.width=`${e}px`,h.style.height=`${t}px`),l&&(l.style.width=`${e}px`,l.style.height=`${t}px`)},on(e,t){n.has(e)||n.set(e,new Set),n.get(e).add(t)},off(e,t){var i;null===(i=n.get(e))||void 0===i||i.delete(t)},updateOriginalMutedState(e,t){const i="number"!=typeof t||Number.isNaN(t)?r:Math.max(0,Math.min(1,t));console.log(`[HlsAdPlayer] updateOriginalMutedState called: { muted: ${s} -> ${e}, volume: ${r} -> ${i} }`),s=e,r=i},getOriginalMutedState:()=>s,getOriginalVolume:()=>r,setAdVolume(e){l&&i&&(l.volume=Math.max(0,Math.min(1,e)))},getAdVolume:()=>l&&i?l.volume:1,showPlaceholder(){var t;if(!h){const i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(i),h=i}h&&(h.style.display="flex",h.style.pointerEvents="auto")},hidePlaceholder(){h&&(h.style.display="none",h.style.pointerEvents="none")}}}bl.defaultConfig=void 0;let Dl=null;function xl(){var e,t,i,s;const r=navigator.userAgent,n=navigator.platform,a=navigator.vendor||"",o=navigator.maxTouchPoints||0,l=navigator.deviceMemory||null,d=navigator.hardwareConcurrency||1,h={width:null===screen||void 0===screen?void 0:screen.width,height:null===screen||void 0===screen?void 0:screen.height,availWidth:null===screen||void 0===screen?void 0:screen.availWidth,availHeight:null===screen||void 0===screen?void 0:screen.availHeight,orientation:(null===(e=null===screen||void 0===screen?void 0:screen.orientation)||void 0===e?void 0:e.type)||"",pixelDepth:null===screen||void 0===screen?void 0:screen.pixelDepth};let c="desktop",u="Unknown",f="Unknown",g="",m=!1,p=!1,y=!1,v=!1;if(r.includes("Web0S")){u="LG",f="webOS",m=!0,c="tv";const e=r.match(/Web0S\/([^\s]+)/);g=e?`webOS ${e[1]}`:"webOS TV"}else if(r.includes("Tizen")){u="Samsung",f="Tizen",m=!0,c="tv";const e=r.match(/Tizen\/([^\s]+)/),t=r.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";g=e?`Tizen ${e[1]} ${t}`.trim():"Tizen TV"}else r.includes("Philips")?(u="Philips",f="Saphi",m=!0,c="tv"):r.includes("Sharp")||r.includes("AQUOS")?(u="Sharp",f="Android TV",m=!0,c="tv"):r.includes("Android")&&(r.includes("Sony")||a.includes("Sony"))?(u="Sony",f="Android TV",m=!0,c="tv"):r.includes("Android")&&(r.includes("NetCast")||r.includes("LG"))?(u="LG",f="Android TV",m=!0,c="tv"):r.includes(" Roku")||r.includes("Roku/")?(u="Roku",f="Roku OS",m=!0,c="tv"):r.includes("AppleTV")&&(u="Apple",f="tvOS",m=!0,c="tv");if(r.includes("Android")){p=!0,f="Android",c=/Mobile/.test(r)?"mobile":"tablet",r.includes("Android")&&(0===o||r.includes("Google TV")||r.includes("XiaoMi"))&&(c="tv",m=!0,u="Unknown"===u?"Android TV":u);const e=r.match(/\(([^)]*Android[^)]*)\)/);e&&e[1]&&(g=e[1])}return/iPad|iPhone|iPod/.test(r)&&(f="iOS",c="mobile",u="Apple",navigator.maxTouchPoints>1&&/iPad/.test(r)&&(c="tablet")),p||m||/Mobile/.test(r)||(r.includes("Windows")?(f="Windows",c="desktop"):r.includes("Mac")&&!/iPhone/.test(r)?(f="macOS",c="desktop",o>1&&(c="tablet")):r.includes("Linux")&&(f="Linux",c="desktop")),"Unknown"===u&&((a.includes("Google")||r.includes("Chrome"))&&(u="Google"),a.includes("Apple")&&(u="Apple"),(a.includes("Samsung")||r.includes("SM-"))&&(u="Samsung")),y=/wv|WebView|Linux; U;/.test(r),0===(null===window||void 0===window?void 0:window.outerHeight)&&0===(null===window||void 0===window?void 0:window.outerWidth)&&(y=!0),v=window.matchMedia("(display-mode: standalone)").matches||!0===window.navigator.standalone||void 0!==(null===(i=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===i?void 0:i.angle),{brand:u,os:f,model:g||r.substring(0,50)+"...",deviceType:c,isSmartTV:m,isAndroid:p,isWebView:y,isWebApp:v,domain:window.location.hostname,origin:window.location.origin,path:window.location.pathname,userAgent:r,vendor:a,platform:n,screen:h,hardwareConcurrency:d,deviceMemory:l,maxTouchPoints:o,language:navigator.language,languages:(null===(s=navigator.languages)||void 0===s?void 0:s.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}async function Cl(e){if(Dl)return Dl;const t=JSON.stringify(e);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)try{let e;if(await crypto.subtle.digest("SHA-256",new Uint8Array([1,2,3])),"undefined"!=typeof TextEncoder)e=(new TextEncoder).encode(t);else{const i=unescape(encodeURIComponent(t)),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);e=s}const i=await crypto.subtle.digest("SHA-256",e),s=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("");return Dl=s,s}catch(e){console.warn("[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash")}let i=0;for(let e=0;e<t.length;e++){i=(i<<5)-i+t.charCodeAt(e),i&=i}const s=Math.abs(i).toString(16).padStart(8,"0"),r=Date.now().toString(16).padStart(12,"0"),n=Math.random().toString(16).substring(2,14).padStart(12,"0");return Dl=(s+r+n).padEnd(64,"0"),Dl}async function _l(e){try{const t=xl(),i={browserId:await Cl(t),...t},s={"Content-Type":"application/json"};e&&(s.Authorization=`Bearer ${e}`);const r=await fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track",{method:"POST",headers:s,body:JSON.stringify(i)});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);await r.json()}catch(e){console.error("[StormcloudVideoPlayer] Error sending initial tracking data:",e)}}async function Ml(e){try{const t=xl(),i={browserId:await Cl(t),timestamp:(new Date).toISOString()},s={"Content-Type":"application/json"};e&&(s.Authorization=`Bearer ${e}`);const r=await fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat",{method:"POST",headers:s,body:JSON.stringify(i)});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);await r.json()}catch(e){console.error("[StormcloudVideoPlayer] Error sending heartbeat:",e)}}function Ol(){"function"!=typeof Object.assign&&(Object.assign=function(e,...t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");const i=Object(e);for(let e=0;e<t.length;e++){const s=t[e];if(null!=s)for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(i[e]=s[e])}return i}),Array.from||(Array.from=function(e,t,i){const s=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");const r=s.length>>>0,n=new Array(r);for(let e=0;e<r;e++)n[e]=t?t.call(i,s[e],e):s[e];return n}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=!t||t<0?0:+t,this.substring(t,t+e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e}),String.prototype.includes||(String.prototype.includes=function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),function(){if("undefined"==typeof URLSearchParams){class e{constructor(t){this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach((e,t)=>{this.append(t,e)})}parseQueryString(e){const t=e.startsWith("?")?e.slice(1):e;t&&t.split("&").forEach(e=>{const[t,i]=e.split("=");if(t){const e=this.safeDecodeURIComponent(t),s=i?this.safeDecodeURIComponent(i):"";this.append(e,s)}})}safeDecodeURIComponent(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}}append(e,t){const i=this.params.get(e)||[];i.push(String(t)),this.params.set(e,i)}delete(e){this.params.delete(e)}get(e){const t=this.params.get(e);return t&&t.length>0&&void 0!==t[0]?t[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,t){this.params.set(e,[String(t)])}forEach(e){this.params.forEach((t,i)=>{t.forEach(t=>{e(t,i,this)})})}toString(){const e=[];return this.params.forEach((t,i)=>{t.forEach(t=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(t)}`)})}),e.join("&")}}window.URLSearchParams=e}}(),"undefined"==typeof TextEncoder&&(window.TextEncoder=class{constructor(){this.encoding="utf-8"}encode(e){const t=[];for(let i=0;i<e.length;i++){let s=e.charCodeAt(i);s<128?t.push(s):s<2048?t.push(192|s>>6,128|63&s):s<55296||s>=57344?t.push(224|s>>12,128|s>>6&63,128|63&s):(i++,s=65536+((1023&s)<<10|1023&e.charCodeAt(i)),t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s))}return new Uint8Array(t)}}),"undefined"==typeof Promise||Promise.prototype.finally||(Promise.prototype.finally=function(e){const t=this.constructor;return this.then(i=>t.resolve(e()).then(()=>i),i=>t.resolve(e()).then(()=>{throw i}))})}class Fl{constructor(e){this.attached=!1,this.inAdBreak=!1,this.ptsDriftEmaMs=0,this.adPodQueue=[],this.lastHeartbeatTime=0,this.currentAdIndex=0,this.totalAdsInBreak=0,this.showAds=!1,this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,this.adPodAllUrls=[],this.preloadingAdUrls=new Set,this.vastToMediaUrlMap=new Map,this.preloadedMediaUrls=new Set,this.preloadingMediaUrls=new Set,this.adRequestTokenCounter=0,this.activeAdRequestToken=null,this.adRequestWatchdogToken=null,this.adFailsafeToken=null,this.fetchedAdDurations=new Map,this.targetAdBreakDurationMs=null,this.isAdaptiveMode=!1,this.failedVastUrls=new Set,this.continuousFetchingActive=!1,this.adRequestQueue=[],this.successfulAdRequests=[],this.maxPlaceholderDurationMs=5e3,this.placeholderStartTimeMs=null,this.isShowingPlaceholder=!1,Ol();const t=kl();this.config={...e,...t},this.video=e.videoElement,Il(e.debugAdTiming),this.ima=this.createAdPlayer(!1)}createAdPlayer(e){const t=this.config.vastMode||"default";let i=this.config.adPlayerType||("adstorm"===t?"hls":"ima");return"ima"!==i||Rl()||(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Google IMA SDK not supported on this browser, falling back to HLS ad player"),i="hls"),"hls"===i?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Creating HLS ad player (AdStorm mode)"),wl(this.video,{continueLiveStreamDuringAds:e,...this.config.licenseKey?{licenseKey:this.config.licenseKey}:{},...this.hls?{mainHlsInstance:this.hls}:{}})):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Creating Google IMA ad player (Default mode)"),Pl(this.video,{continueLiveStreamDuringAds:e}))}async load(){var e,t;this.attached||this.attach();try{await this.fetchAdConfiguration()}catch(e){this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration:",e)}if(this.initializeTracking(),this.shouldUseNativeHls())return this.nativeHlsMode=!0,this.videoSrcProtection=this.config.src,this.video.src=this.config.src,this.isLiveStream=null!==(e=this.config.lowLatencyMode)&&void 0!==e&&e,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using native HLS playback - VOD mode:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:"vod (main video pauses during ads)"}),this.ima.destroy(),this.ima=this.createAdPlayer(!1),this.ima.initialize(),void(this.config.autoplay&&await(null===(t=this.video.play())||void 0===t?void 0:t.catch(()=>{})));this.hls=new bl({enableWorker:!0,backBufferLength:30,liveDurationInfinity:!0,lowLatencyMode:!!this.config.lowLatencyMode,maxLiveSyncPlaybackRate:this.config.lowLatencyMode?1.5:1,...this.config.lowLatencyMode?{liveSyncDuration:2}:{},maxBufferLength:30,maxMaxBufferLength:600,maxBufferSize:6e7,maxBufferHole:.5,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,startPosition:-1}),this.hls.on(bl.Events.MEDIA_ATTACHED,()=>{var e;null===(e=this.hls)||void 0===e||e.loadSource(this.config.src)}),this.hls.on(bl.Events.MANIFEST_PARSED,async(e,t)=>{var i,s,r,n,a;if(this.isLiveStream=null!==(r=null===(s=null===(i=this.hls)||void 0===i?void 0:i.levels)||void 0===s?void 0:s.some(e=>{var t,i;return!0===(null===(t=null==e?void 0:e.details)||void 0===t?void 0:t.live)||"LIVE"===(null===(i=null==e?void 0:e.details)||void 0===i?void 0:i.type)}))&&void 0!==r&&r,this.config.debugAdTiming){const e=this.shouldContinueLiveStreamDuringAds()?"live (main video continues muted during ads)":"vod (main video pauses during ads)";console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:e})}this.ima.destroy(),this.ima=this.createAdPlayer(this.shouldContinueLiveStreamDuringAds()),this.ima.initialize(),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay;const o=null!==(n=this.config.minSegmentsBeforePlay)&&void 0!==n?n:2;this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Waiting for",o,"segments to buffer before playback"),0!==o&&this.config.autoplay||(this.hasInitialBufferCompleted=!0,this.config.autoplay&&await(null===(a=this.video.play())||void 0===a?void 0:a.catch(()=>{})))}),this.hls.on(bl.Events.FRAG_BUFFERED,async(e,t)=>{var i,s;if(this.hasInitialBufferCompleted)return;this.bufferedSegmentsCount++;const r=null!==(i=this.config.minSegmentsBeforePlay)&&void 0!==i?i:2;this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Buffered segment ${this.bufferedSegmentsCount}/${r}`),this.bufferedSegmentsCount>=r&&(this.hasInitialBufferCompleted=!0,this.shouldAutoplayAfterBuffering&&(this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Initial buffer complete (${this.bufferedSegmentsCount} segments). Starting playback.`),await(null===(s=this.video.play())||void 0===s?void 0:s.catch(e=>{this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)}))))}),this.hls.on(bl.Events.FRAG_PARSING_METADATA,(e,t)=>{((null==t?void 0:t.samples)||[]).map(e=>({key:"ID3",value:null==e?void 0:e.data,ptsSeconds:null==e?void 0:e.pts})).forEach(e=>this.onId3Tag(e))}),this.hls.on(bl.Events.FRAG_CHANGED,(e,t)=>{var i,s,r;const n=null==t?void 0:t.frag,a=null==n?void 0:n.tagList;if(Array.isArray(a))for(const e of a){let t="",n="";if(Array.isArray(e))t=String(null!==(i=e[0])&&void 0!==i?i:""),n=String(null!==(s=e[1])&&void 0!==s?s:"");else if("string"==typeof e){const i=e.indexOf(":");i>=0?(t=e.substring(0,i),n=e.substring(i+1)):(t=e,n="")}if(t)if(t.includes("EXT-X-CUE-OUT")){const e=this.parseCueOutDuration(n),i={type:"start",...void 0!==e?{durationSeconds:e}:{},raw:{tag:t,value:n}};this.onScte35Marker(i)}else if(t.includes("EXT-X-CUE-OUT-CONT")){const e=this.parseCueOutCont(n),i={type:"progress",...void 0!==(null==e?void 0:e.duration)?{durationSeconds:e.duration}:{},...void 0!==(null==e?void 0:e.elapsed)?{ptsSeconds:e.elapsed}:{},raw:{tag:t,value:n}};this.onScte35Marker(i)}else if(t.includes("EXT-X-CUE-IN"))this.onScte35Marker({type:"end",raw:{tag:t,value:n}});else if(t.includes("EXT-X-DATERANGE")){const e=this.parseAttributeList(n),i="SCTE35-OUT"in e||void 0!==e["SCTE35-OUT"],s="SCTE35-IN"in e||void 0!==e["SCTE35-IN"],a=String(null!==(r=e.CLASS)&&void 0!==r?r:""),o=this.toNumber(e.DURATION);if(i||/com\.apple\.hls\.cue/i.test(a)){const i={type:"start",...void 0!==o?{durationSeconds:o}:{},raw:{tag:t,value:n,attrs:e}};this.onScte35Marker(i)}s&&this.onScte35Marker({type:"end",raw:{tag:t,value:n,attrs:e}})}}}),this.hls.on(bl.Events.ERROR,(e,t)=>{var i,s;if(null==t?void 0:t.fatal)switch(t.type){case bl.ErrorTypes.NETWORK_ERROR:null===(i=this.hls)||void 0===i||i.startLoad();break;case bl.ErrorTypes.MEDIA_ERROR:null===(s=this.hls)||void 0===s||s.recoverMediaError();break;default:this.destroy()}}),this.hls.attachMedia(this.video)}attach(){this.attached||(this.attached=!0,this.video.autoplay=!!this.config.autoplay,this.video.muted=!!this.config.muted,this.ima.initialize(),this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),this.ima.on("all_ads_completed",()=>{this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] IMA all_ads_completed event received - ending ad break"),this.inAdBreak&&this.handleAdPodComplete()}),this.ima.on("ad_error",e=>{const t=this.getRemainingAdMs();if(console.error("[AD-ERROR] Ad playback failed",e||""),this.inAdBreak)if(t>500&&this.adPodQueue.length>0){const e=this.findNextPreloadedAd();e?(this.currentAdIndex++,this.playSingleAd(e).catch(()=>{this.handleAdFailure()})):this.handleAdFailure()}else this.handleAdFailure();else this.handleAdFailure()}),this.ima.on("content_pause",()=>{this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog(),this.activeAdRequestToken=null,this.showAds=!0}),this.ima.on("content_resume",()=>{if(this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog(),this.activeAdRequestToken=null,this.showAds=!1,!this.inAdBreak)return;const e=this.getRemainingAdMs();this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] content_resume event: remaining=${e}ms, queued ads=${this.adRequestQueue.length}`),e>500?this.tryNextAvailableAd():this.handleAdPodComplete()}),this.timeUpdateHandler=()=>{this.onTimeUpdate(this.video.currentTime)},this.video.addEventListener("timeupdate",this.timeUpdateHandler),this.emptiedHandler=()=>{if(this.nativeHlsMode&&this.videoSrcProtection&&!this.ima.isAdPlaying()){this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring:",this.videoSrcProtection);const e=this.video.currentTime,t=this.video.paused;this.video.src=this.videoSrcProtection,this.video.currentTime=e,t||this.video.play().catch(()=>{})}},this.video.addEventListener("emptied",this.emptiedHandler))}shouldUseNativeHls(){if("other"===this.getStreamType())return!0;const e=this.video.canPlayType("application/vnd.apple.mpegurl");return!(!this.config.allowNativeHls||!e)}onId3Tag(e){"number"==typeof e.ptsSeconds&&this.updatePtsDrift(e.ptsSeconds);const t=this.parseScte35FromId3(e);t&&this.onScte35Marker(t)}parseScte35FromId3(e){var t,i,s,r;const n=this.decodeId3ValueToText(e.value);if(!n)return;const a=n.match(/EXT-X-CUE-OUT(?::([^\r\n]*))?/i)||n.match(/CUE-OUT(?::([^\r\n]*))?/i);if(a){const i=(null!==(t=a[1])&&void 0!==t?t:"").trim(),s=this.parseCueOutDuration(i);return{type:"start",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},...void 0!==s?{durationSeconds:s}:{},raw:{id3:n}}}const o=n.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(o){const t=(null!==(i=o[1])&&void 0!==i?i:"").trim(),s=this.parseCueOutCont(t);return{type:"progress",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},...void 0!==(null==s?void 0:s.duration)?{durationSeconds:s.duration}:{},raw:{id3:n}}}if(n.match(/EXT-X-CUE-IN\b/i)||n.match(/CUE-IN\b/i)){return{type:"end",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},raw:{id3:n}}}const l=n.match(/EXT-X-DATERANGE:([^\r\n]*)/i);if(l){const t=this.parseAttributeList(null!==(s=l[1])&&void 0!==s?s:""),i="SCTE35-OUT"in t||void 0!==t["SCTE35-OUT"],a="SCTE35-IN"in t||void 0!==t["SCTE35-IN"],o=String(null!==(r=t.CLASS)&&void 0!==r?r:""),d=this.toNumber(t.DURATION);if(i||/com\.apple\.hls\.cue/i.test(o)){return{type:"start",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},...void 0!==d?{durationSeconds:d}:{},raw:{id3:n,attrs:t}}}if(a){return{type:"end",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},raw:{id3:n,attrs:t}}}}if(/SCTE35-OUT/i.test(n)){return{type:"start",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},raw:{id3:n}}}if(/SCTE35-IN/i.test(n)){return{type:"end",...void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{},raw:{id3:n}}}if(e.value instanceof Uint8Array){const t=this.parseScte35Binary(e.value);if(t)return t}}decodeId3ValueToText(e){try{if("string"==typeof e)return e;const t=new TextDecoder("utf-8",{fatal:!1}).decode(e);if(t&&/[\x20-\x7E]/.test(t))return t;let i="";for(let t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return i}catch{return}}onScte35Marker(e){var t,i;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 marker detected:",{type:e.type,ptsSeconds:e.ptsSeconds,durationSeconds:e.durationSeconds,currentTime:this.video.currentTime,raw:e.raw}),"start"===e.type){if(this.inAdBreak)return;this.inAdBreak=!0;const s=null!=e.durationSeconds?1e3*e.durationSeconds:void 0;this.expectedAdBreakDurationMs=s,this.currentAdBreakStartWallClockMs=Date.now();const r=this.isManifestBasedMarker(e),n=null===(t=this.config.immediateManifestAds)||void 0===t||t;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad start decision:",{isManifestMarker:r,forceImmediate:n,hasPts:"number"==typeof e.ptsSeconds}),r&&n)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (manifest-based)"),this.clearAdStartTimer(),this.handleAdStart(e);else if("number"==typeof e.ptsSeconds){const t=null!==(i=this.config.driftToleranceMs)&&void 0!==i?i:1e3,s=1e3*this.video.currentTime,r=s-this.ptsDriftEmaMs,n=Math.floor(1e3*e.ptsSeconds-r);this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] PTS-based timing calculation:",{nowMs:s,estCurrentPtsMs:r,markerPtsMs:1e3*e.ptsSeconds,deltaMs:n,tolerance:t}),n>t?(this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Scheduling ad start in ${n}ms`),this.scheduleAdStartIn(n)):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (within tolerance)"),this.clearAdStartTimer(),this.handleAdStart(e))}else this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (fallback)"),this.clearAdStartTimer(),this.handleAdStart(e);return void(null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs))}if("progress"===e.type&&this.inAdBreak){if(null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds),null!=this.expectedAdBreakDurationMs&&null!=this.currentAdBreakStartWallClockMs){const e=Date.now()-this.currentAdBreakStartWallClockMs,t=Math.max(0,this.expectedAdBreakDurationMs-e);this.scheduleAdStopCountdown(t)}if(!this.ima.isAdPlaying()&&null===this.activeAdRequestToken){const e=this.findCurrentOrNextBreak(1e3*this.video.currentTime),t=this.selectVastTagsForBreak(e)||(this.apiVastTagUrl?[this.apiVastTagUrl]:void 0);if(t&&t.length>0){const e=t[0],i=t.slice(1);this.adPodQueue=i,this.playSingleAd(e).catch(()=>{})}}}else if("end"===e.type)return this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.ima.isAdPlaying()&&this.ima.stop().catch(()=>{}),void this.handleAdPodComplete()}parseCueOutDuration(e){const t=parseFloat(e.trim());if(!Number.isNaN(t))return t;const i=e.match(/(?:^|[,\s])DURATION\s*=\s*([0-9.]+)/i)||e.match(/Duration\s*=\s*([0-9.]+)/i);if(i&&null!=i[1]){const e=i[1],t=parseFloat(e);return Number.isNaN(t)?void 0:t}}parseCueOutCont(e){const t=e.match(/Elapsed\s*=\s*([0-9.]+)/i),i=e.match(/Duration\s*=\s*([0-9.]+)/i),s={};if(t&&null!=t[1]){const e=parseFloat(t[1]);Number.isNaN(e)||(s.elapsed=e)}if(i&&null!=i[1]){const e=parseFloat(i[1]);Number.isNaN(e)||(s.duration=e)}if("elapsed"in s||"duration"in s)return s}parseAttributeList(e){var t,i,s;const r={},n=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;let a;for(;null!==(a=n.exec(e));){const e=null!==(t=a[1])&&void 0!==t?t:"";let n=null!==(s=null!==(i=a[3])&&void 0!==i?i:a[4])&&void 0!==s?s:"";n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1)),e&&(r[e]=n)}return r}toNumber(e){if(null==e)return;const t="string"==typeof e?parseFloat(e):Number(e);return Number.isNaN(t)?void 0:t}isManifestBasedMarker(e){const t=e.raw;if(!t)return!1;if(t.tag){const e=String(t.tag);return e.includes("EXT-X-CUE-OUT")||e.includes("EXT-X-CUE-IN")||e.includes("EXT-X-DATERANGE")}return t.id3||t.splice_command_type,!1}parseScte35Binary(e){const t=new class{constructor(e){this.buf=e,this.bytePos=0,this.bitPos=0}readBits(e){let t=0;for(;e>0;){if(this.bytePos>=this.buf.length)return t;const i=8-this.bitPos,s=Math.min(e,i);t=t<<s|this.buf[this.bytePos]>>i-s&((1<<s)-1&255),this.bitPos+=s,this.bitPos>=8&&(this.bitPos=0,this.bytePos+=1),e-=s}return t>>>0}skipBits(e){this.readBits(e)}}(e);if(252!==t.readBits(8))return;t.readBits(1),t.readBits(1),t.readBits(2);t.readBits(12);t.readBits(8),t.readBits(1),t.readBits(6);t.readBits(1),t.readBits(32);t.readBits(8),t.readBits(12);t.readBits(12);if(5!==t.readBits(8))return;t.readBits(32);const i=1===t.readBits(1);if(t.readBits(7),i)return;const s=1===t.readBits(1),r=1===t.readBits(1),n=1===t.readBits(1),a=1===t.readBits(1);if(t.readBits(4),r&&!a){1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7)}else if(!r){const e=t.readBits(8);for(let i=0;i<e;i++)if(t.readBits(8),!a){1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7)}}let o;if(n){t.readBits(6),t.readBits(1);o=(4294967296*t.readBits(1)+t.readBits(32))/9e4}if(t.readBits(16),t.readBits(8),t.readBits(8),s){return{type:"start",...void 0!==o?{durationSeconds:o}:{},raw:{splice_command_type:5}}}}initializeTracking(){_l(this.config.licenseKey).then(()=>{this.heartbeatInterval=window.setInterval(()=>{this.sendHeartbeatIfNeeded()},5e3)}).catch(e=>{this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send initial tracking:",e),this.heartbeatInterval=window.setInterval(()=>{this.sendHeartbeatIfNeeded()},5e3)})}sendHeartbeatIfNeeded(){const e=Date.now();(!this.lastHeartbeatTime||e-this.lastHeartbeatTime>3e4)&&(this.lastHeartbeatTime=e,Ml(this.config.licenseKey).catch(e=>{this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send heartbeat:",e)}))}async fetchAdConfiguration(){var e,t,i,s,r,n,a;const o=this.config.vastMode||"default";if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] VAST mode:",o),"adstorm"===o){if(!this.config.licenseKey)return void(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] AdStorm mode requires a license key"));const e=`https://adstorm.co/api-adstorm-dev/adstorm/vast/${this.config.licenseKey}`;return this.apiVastTagUrl=e,void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using AdStorm VAST endpoint (adstorm mode):",e))}if(this.config.vastTagUrl)return this.apiVastTagUrl=this.config.vastTagUrl,void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using custom VAST tag URL:",this.apiVastTagUrl));const l="https://adstorm.co/api-adstorm-dev/adstorm/ads/web";this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Fetching ad configuration from:",l);const d={};this.config.licenseKey&&(d.Authorization=`Bearer ${this.config.licenseKey}`);const h=await fetch(l,{headers:d});if(!h.ok)return void(this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Failed to fetch ad configuration: ${h.status}`));const c=await h.json(),u=null===(i=null===(t=null===(e=c.response)||void 0===e?void 0:e.ima)||void 0===t?void 0:t["publisherdesk.ima"])||void 0===i?void 0:i.payload;u?(this.apiVastTagUrl=decodeURIComponent(u),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Extracted VAST tag URL from /ads/web:",this.apiVastTagUrl)):this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] No VAST tag URL found in /ads/web response");const f=null===(a=null===(n=null===(r=null===(s=c.response)||void 0===s?void 0:s.options)||void 0===r?void 0:r.vast)||void 0===n?void 0:n.cue_tones)||void 0===a?void 0:a.number_ads;null!=f&&f>0&&(this.apiNumberAds=f,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Number of ads per break from API:",this.apiNumberAds))}getCurrentAdIndex(){return this.currentAdIndex}getTotalAdsInBreak(){return this.totalAdsInBreak}generateVastUrlsWithCorrelators(e,t){const i=[];for(let s=0;s<t;s++)try{const t=new URL(e),r=Date.now(),n=`${r}${Math.floor(1e6*Math.random())}${s}`;t.searchParams.set("correlator",n),i.push(t.toString())}catch(t){console.warn("[StormcloudVideoPlayer] Failed to parse VAST URL:",e,t),i.push(`${e}${e.includes("?")?"&":"?"}correlator=${Date.now()}${s}`)}return i}isAdPlaying(){return this.inAdBreak&&this.ima.isAdPlaying()}isShowingAds(){return this.showAds}getStreamType(){const e=this.config.src.toLowerCase();return e.includes(".m3u8")||e.includes("/hls/")||e.includes("application/vnd.apple.mpegurl")?"hls":"other"}shouldShowNativeControls(){var e,t;return"other"===this.getStreamType()?!(null!==(e=this.config.showCustomControls)&&void 0!==e&&e):!(!this.config.allowNativeHls||null!==(t=this.config.showCustomControls)&&void 0!==t&&t)}shouldContinueLiveStreamDuringAds(){return!this.config.allowNativeHls&&!!this.isLiveStream}async handleAdStart(e){const t=this.findCurrentOrNextBreak(1e3*this.video.currentTime),i=this.selectVastTagsForBreak(t);let s;if(this.apiVastTagUrl)s=this.apiVastTagUrl;else{if(!(i&&i.length>0&&i[0]))return;s=i[0]}const r=null!=e.durationSeconds?1e3*e.durationSeconds:null==t?void 0:t.durationMs;this.isLiveStream&&null!=r&&r>0?(this.isAdaptiveMode=!0,this.targetAdBreakDurationMs=r,this.fetchedAdDurations.clear(),this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] 📺 LIVE MODE: Target duration=${r}ms | Will continuously fetch ads during break`)):(this.isAdaptiveMode=!1,this.targetAdBreakDurationMs=null,this.fetchedAdDurations.clear(),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🎬 VOD MODE: Using fixed ad strategy")),this.adPodAllUrls=[],this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.failedVastUrls.clear(),this.adRequestQueue=[],this.successfulAdRequests=[],this.continuousFetchingActive=!0,this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null;const n=this.video.muted,a=this.video.volume;this.ima.updateOriginalMutedState(n,a),this.inAdBreak=!0,this.currentAdIndex=0,this.totalAdsInBreak=1,this.adPodQueue=[],null==this.expectedAdBreakDurationMs&&null!=r&&(this.expectedAdBreakDurationMs=r,this.currentAdBreakStartWallClockMs=Date.now(),this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🚀 Immediately requesting first ad...");const o=this.generateVastUrlsWithCorrelators(s,1)[0];if(!o)return this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ Failed to generate first ad URL"),void this.handleAdPodComplete();try{await this.ima.requestAds(o),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ First ad request successful, starting playback"),this.successfulAdRequests.push(o),this.currentAdIndex++,this.startContinuousFetching(s),await this.ima.play()}catch(e){this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ First ad request failed:",e),this.failedVastUrls.add(o),this.startContinuousFetching(s),this.tryNextAvailableAd()}}startContinuousFetching(e){this.continuousFetchingActive&&(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🔄 Starting continuous ad fetching loop"),this.continuousFetchLoop(e))}async continuousFetchLoop(e){for(;this.continuousFetchingActive&&this.inAdBreak;){if(this.getRemainingAdMs()<=0){this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ Ad break time expired, stopping fetch loop");break}const t=3;if(this.adRequestQueue.length>=t){this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] ⏸️ Queue full (${this.adRequestQueue.length}), pausing fetching...`),await new Promise(e=>setTimeout(e,2e3));continue}const i=this.generateVastUrlsWithCorrelators(e,1)[0];if(i&&!this.failedVastUrls.has(i)){this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] 📡 Attempting to fetch ad (${this.successfulAdRequests.length+this.adRequestQueue.length+1} total)...`);try{const e=await fetch(i,{mode:"cors"});if(!e.ok)throw new Error(`Failed to fetch VAST: ${e.status}`);const t=await e.text(),s=(new DOMParser).parseFromString(t,"text/xml");if(0===s.querySelectorAll("MediaFile").length){this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⚠️ VAST response has no media files, skipping"),this.failedVastUrls.add(i),await new Promise(e=>setTimeout(e,1e3));continue}this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] ✅ Successfully fetched ad, adding to queue (queue size: ${this.adRequestQueue.length+1})`),this.adRequestQueue.push(i),this.totalAdsInBreak++,await new Promise(e=>setTimeout(e,500))}catch(e){this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ❌ Ad fetch failed:",e.message),this.failedVastUrls.add(i),await new Promise(e=>setTimeout(e,2e3))}}else await new Promise(e=>setTimeout(e,1e3))}this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Continuous fetch loop ended")}stopContinuousFetching(){this.continuousFetchingActive=!1,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Stopping continuous ad fetching")}async tryNextAvailableAd(e=0){const t=this.getRemainingAdMs();if(t<=500)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No time remaining, ending ad break"),void this.handleAdPodComplete();if(this.adRequestQueue.length>0){const e=this.adRequestQueue.shift();if(e){this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] 🎬 Playing next queued ad (${this.currentAdIndex+1}/${this.totalAdsInBreak}, ${this.adRequestQueue.length} remaining in queue)`);const t=this.video.muted,i=this.video.volume;return this.ima.updateOriginalMutedState(t,i),this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] 🔊 Updated ad audio state: muted=${t}, volume=${i}`),this.currentAdIndex++,this.successfulAdRequests.push(e),void await this.playSingleAd(e).catch(()=>{this.tryNextAvailableAd(0)})}}if(this.continuousFetchingActive&&e<5&&t>2e3)return this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] ⏳ Queue empty but fetching active, waiting... (retry ${e+1}/5)`),await new Promise(e=>setTimeout(e,1e3)),void await this.tryNextAvailableAd(e+1);!this.isShowingPlaceholder&&t>1e3?this.showPlaceholderAndWaitForAds():(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No more ads available, ending ad break"),this.handleAdPodComplete())}async showPlaceholderAndWaitForAds(){const e=this.getRemainingAdMs(),t=Math.min(this.maxPlaceholderDurationMs,e);if(t<1e3)return void this.handleAdPodComplete();this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] ⬛ Showing black placeholder for ${t}ms while waiting for ads`),this.isShowingPlaceholder=!0,this.placeholderStartTimeMs=Date.now(),this.ima.showPlaceholder();const i=Math.floor(t/500);for(let e=0;e<i;e++){if(await new Promise(e=>setTimeout(e,500)),!this.inAdBreak)return;if(this.adRequestQueue.length>0){this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ New ad became available during placeholder"),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,this.ima.hidePlaceholder();const e=this.video.muted,t=this.video.volume;this.ima.updateOriginalMutedState(e,t);const i=this.adRequestQueue.shift();return void(i&&(this.currentAdIndex++,this.successfulAdRequests.push(i),await this.playSingleAd(i).catch(()=>{this.tryNextAvailableAd()})))}}this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏰ Placeholder timeout reached, no ads fetched"),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,this.ima.hidePlaceholder(),this.handleAdPodComplete()}findCurrentOrNextBreak(e){var t;const i=[];let s;for(const r of i){const i=null!==(t=this.config.driftToleranceMs)&&void 0!==t?t:1e3;r.startTimeMs<=e+i&&(null==s||r.startTimeMs>(s.startTimeMs||0))&&(s=r)}return s}onTimeUpdate(e){if(this.ima.isAdPlaying())return;const t=1e3*e,i=this.findBreakForTime(t);i&&this.handleMidAdJoin(i,t)}async handleMidAdJoin(e,t){var i;const s=null!==(i=e.durationMs)&&void 0!==i?i:0,r=e.startTimeMs+s;if(s>0&&t>e.startTimeMs&&t<r){const i=r-t,s=this.selectVastTagsForBreak(e)||(this.apiVastTagUrl?[this.apiVastTagUrl]:void 0);if(s&&s.length>0){const e=s[0],t=s.slice(1);this.adPodQueue=t,this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),await this.playSingleAd(e),this.inAdBreak=!0,this.expectedAdBreakDurationMs=i,this.currentAdBreakStartWallClockMs=Date.now(),this.scheduleAdStopCountdown(i)}}}scheduleAdStopCountdown(e){this.clearAdStopTimer();const t=Math.max(0,Math.floor(e));0!==t?this.adStopTimerId=window.setTimeout(()=>{this.ensureAdStoppedByTimer()},t):this.ensureAdStoppedByTimer()}clearAdStopTimer(){null!=this.adStopTimerId&&(clearTimeout(this.adStopTimerId),this.adStopTimerId=void 0)}ensureAdStoppedByTimer(){var e,t;if(!this.inAdBreak)return;this.adStopTimerId=void 0;const i=this.ima.isAdPlaying(),s=this.adPodQueue.length>0,r=Math.max(250,Math.floor(null!==(e=this.config.adBreakCheckIntervalMs)&&void 0!==e?e:1e3)),n=this.config.maxAdBreakExtensionMs,a="number"==typeof n&&n>0?n:6e4;let o=0;null!=this.currentAdBreakStartWallClockMs&&(o=Date.now()-this.currentAdBreakStartWallClockMs);const l=null!==(t=this.expectedAdBreakDurationMs)&&void 0!==t?t:0,d=Math.max(0,o-l);(i||s||this.showAds)&&d<a?this.scheduleAdStopCountdown(r):(i&&this.ima.stop().catch(()=>{}),this.handleAdPodComplete())}scheduleAdStartIn(e){this.clearAdStartTimer();const t=Math.max(0,Math.floor(e));0!==t?this.adStartTimerId=window.setTimeout(()=>{this.handleAdStart({type:"start"}).catch(()=>{})},t):this.handleAdStart({type:"start"}).catch(()=>{})}clearAdStartTimer(){null!=this.adStartTimerId&&(clearTimeout(this.adStartTimerId),this.adStartTimerId=void 0)}updatePtsDrift(e){const t=1e3*(this.video.currentTime-e);if(!Number.isFinite(t)||Math.abs(t)>6e4)return;this.ptsDriftEmaMs=.9*this.ptsDriftEmaMs+.1*t}async playSingleAd(e){if(this.ima.isAdPlaying())return;if(this.failedVastUrls.has(e))return console.warn("[AD-ERROR] Skipping already-failed VAST URL:",e.substring(0,60)),void this.handleAdFailure();const t=++this.adRequestTokenCounter;this.activeAdRequestToken=t,this.startAdRequestWatchdog(t);try{if(await this.ima.requestAds(e),this.clearAdRequestWatchdog(),this.activeAdRequestToken!==t)return;try{this.startAdFailsafeTimer(t),await this.ima.play()}catch(i){return console.error("[AD-ERROR] Failed to play ad:",i),this.failedVastUrls.add(e),this.clearAdFailsafeTimer(),this.activeAdRequestToken===t&&(this.activeAdRequestToken=null),void this.handleAdFailure()}}catch(i){console.error("[AD-ERROR] Ad request failed:",null==i?void 0:i.message),this.failedVastUrls.add(e),this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken===t&&(this.activeAdRequestToken=null),this.handleAdFailure()}}handleAdPodComplete(){var e;this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken=null,this.stopContinuousFetching(),this.isShowingPlaceholder&&(this.ima.hidePlaceholder(),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null),this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.adRequestQueue=[],this.successfulAdRequests=[],this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.adPodQueue=[],this.adPodAllUrls=[],this.showAds=!1,this.currentAdIndex=0,this.totalAdsInBreak=0,this.ima.stop().catch(()=>{});const t=this.ima.getOriginalMutedState(),i=this.ima.getOriginalVolume();this.video.muted!==t&&(this.video.muted=t),Math.abs(this.video.volume-i)>.01&&(this.video.volume=i),!this.shouldContinueLiveStreamDuringAds()&&this.video.paused&&(null===(e=this.video.play())||void 0===e||e.catch(()=>{}))}handleAdFailure(){const e=this.getRemainingAdMs();this.config.debugAdTiming&&console.log(`[CONTINUOUS-FETCH] Ad failure: remaining=${e}ms, queued ads=${this.adRequestQueue.length}`),e>500?this.tryNextAvailableAd():(console.error("[AD-ERROR] Ad failed and no time remaining. Failed URLs:",this.failedVastUrls.size),this.handleAdPodComplete())}startAdRequestWatchdog(e){var t;this.clearAdRequestWatchdog();const i=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adRequestWatchdogToken=e,this.adRequestWatchdogId=window.setTimeout(()=>{this.adRequestWatchdogToken===e&&(this.adRequestWatchdogId=void 0,this.adRequestWatchdogToken=null,this.activeAdRequestToken===e&&(this.activeAdRequestToken=null),this.logAdState("ad_request_timeout",{token:e,timeoutMs:i}),this.handleAdFailure())},i),this.logAdState("ad_request_watchdog_started",{token:e,timeoutMs:i})}clearAdRequestWatchdog(){null!=this.adRequestWatchdogId&&(clearTimeout(this.adRequestWatchdogId),this.adRequestWatchdogId=void 0),null!=this.adRequestWatchdogToken&&(this.logAdState("ad_request_watchdog_cleared",{token:this.adRequestWatchdogToken}),this.adRequestWatchdogToken=null)}startAdFailsafeTimer(e){var t;this.clearAdFailsafeTimer();const i=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adFailsafeToken=e,this.adFailsafeTimerId=window.setTimeout(()=>{this.adFailsafeToken===e&&(this.adFailsafeTimerId=void 0,this.adFailsafeToken=null,this.activeAdRequestToken===e&&(this.activeAdRequestToken=null),this.logAdState("ad_failsafe_triggered",{token:e,failsafeMs:i,videoPaused:this.video.paused,imaAdPlaying:this.ima.isAdPlaying()}),this.handleAdFailure())},i),this.logAdState("ad_failsafe_started",{token:e,failsafeMs:i})}clearAdFailsafeTimer(){null!=this.adFailsafeTimerId&&(clearTimeout(this.adFailsafeTimerId),this.logAdState("ad_failsafe_cleared",{token:this.adFailsafeToken}),this.adFailsafeTimerId=void 0),this.adFailsafeToken=null}selectVastTagsForBreak(e){if(e&&e.vastTagUrl)return e.vastTagUrl.includes(",")?e.vastTagUrl.split(",").map(e=>e.trim()).filter(e=>e.length>0):[e.vastTagUrl]}logAdState(e,t={}){this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer][AdState]",{event:e,timestamp:(new Date).toISOString(),showAds:this.showAds,adPlaying:this.ima.isAdPlaying(),inAdBreak:this.inAdBreak,activeAdRequestToken:this.activeAdRequestToken,...t})}async fetchAndParseVastXml(e){try{const t=await fetch(e,{mode:"cors"});if(!t.ok)throw new Error(`Failed to fetch VAST: ${t.status}`);const i=await t.text();return this.extractMediaUrlsFromVast(i)}catch(t){return this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Failed to fetch/parse VAST XML: ${e}`,t),[]}}extractMediaUrlsFromVast(e){var t;const i=[];try{const s=new DOMParser,r=s.parseFromString(e,"text/xml").querySelectorAll("MediaFile");for(const e of Array.from(r)){const s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(s){const e=s.toLowerCase();(e.endsWith(".mp4")||e.endsWith(".webm")||e.endsWith(".mov")||e.endsWith(".avi")||e.includes(".mp4?")||e.includes(".webm?")||e.includes("/mp4/")||e.includes("type=video"))&&i.push(s)}}this.config.debugAdTiming&&i.length>0&&console.log(`[StormcloudVideoPlayer] Extracted ${i.length} media URLs from VAST:`,i)}catch(e){this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to parse VAST XML:",e)}return i}async fetchVastDuration(e){var t;try{const i=await fetch(e,{mode:"cors"});if(!i.ok)return this.config.debugAdTiming&&console.warn(`[ADAPTIVE-POD] Failed to fetch VAST: ${i.status}`),null;const s=await i.text(),r=new DOMParser,n=null===(t=r.parseFromString(s,"text/xml").querySelector("Duration"))||void 0===t?void 0:t.textContent;if(!n)return this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] No Duration element found in VAST"),null;const a=n.split(":");return 3600*parseInt(a[0]||"0",10)+60*parseInt(a[1]||"0",10)+parseInt(a[2]||"0",10)}catch(t){return this.config.debugAdTiming&&console.warn(`[ADAPTIVE-POD] Error fetching VAST duration from ${e}:`,t),null}}calculateAdditionalAdsNeeded(){if(!this.isAdaptiveMode||null===this.targetAdBreakDurationMs)return 0;let e=0;for(const t of this.fetchedAdDurations.values())e+=1e3*t;const t=this.fetchedAdDurations.size,i=t>0?e/t:3e4,s=this.adPodAllUrls.length-t,r=s*i,n=e+r,a=this.targetAdBreakDurationMs-n;if(a<=0)return this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✅ Target duration met: Fetched=${e}ms + Queued(${s} ads)=${r}ms = ${n}ms / Target=${this.targetAdBreakDurationMs}ms`),0;const o=Math.ceil(a/i);return this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] 📊 Need ${o} more ads | Fetched: ${e}ms (${t} ads) | Queued: ${r}ms (${s} ads) | Target: ${this.targetAdBreakDurationMs}ms | Remaining: ${a}ms | Avg duration: ${i}ms`),o}async addAdaptiveAdsToQueue(){if(!this.isAdaptiveMode||!this.apiVastTagUrl)return;const e=this.calculateAdditionalAdsNeeded();if(e<=0)return;const t=this.generateVastUrlsWithCorrelators(this.apiVastTagUrl,e);this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] 🔄 Adding ${t.length} additional VAST URLs to queue (will be preloaded sequentially)`),this.adPodAllUrls.push(...t),this.adPodQueue.push(...t),this.totalAdsInBreak+=t.length}async preloadMediaFile(e){if(!this.preloadedMediaUrls.has(e)&&!this.preloadingMediaUrls.has(e)){this.preloadingMediaUrls.add(e);try{this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Preloading video file: ${e}`);const t=await fetch(e,{mode:"cors",method:"GET",headers:{Range:"bytes=0-1048576"}});(t.ok||206===t.status)&&(this.preloadedMediaUrls.add(e),this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Successfully preloaded video file: ${e}`))}catch(t){this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Failed to preload video file: ${e}`,t)}finally{this.preloadingMediaUrls.delete(e)}}}async preloadAllAdsInBackground(){var e,t;if(0!==this.adPodAllUrls.length)if(this.isAdaptiveMode){this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 🔄 Starting sequential preload of remaining ads");const i=new Set;for(const s of this.adPodAllUrls)((null===(t=(e=this.ima).hasPreloadedAd)||void 0===t?void 0:t.call(e,s))||this.fetchedAdDurations.has(s))&&i.add(s);for(this.config.debugAdTiming&&i.size>0&&console.log(`[ADAPTIVE-POD] 📦 Skipping ${i.size} already-preloaded ads`);;){const e=this.adPodAllUrls.find(e=>!i.has(e));if(!e){this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✅ All queued ads processed (${i.size} total)`);break}i.add(e),this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] 📥 Preloading ad ${i.size}/${this.adPodAllUrls.length}...`);try{await this.preloadSingleAd(e)}catch(e){this.config.debugAdTiming&&console.warn(`[ADAPTIVE-POD] ⚠️ Preload failed for ad ${i.size}:`,e)}if(0===this.calculateAdditionalAdsNeeded()){this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✅ Target duration reached (${i.size} ads preloaded), stopping`);break}}this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✅ Sequential preloading completed (${i.size} ads ready)`)}else{this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Starting parallel preload of ${this.adPodAllUrls.length} ads`);const e=this.adPodAllUrls.map(e=>this.preloadSingleAd(e).catch(t=>{this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Preload failed for ${e}:`,t)}));await Promise.all(e),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Background preloading completed for all ads")}}async preloadSingleAd(e){if(e)try{if(this.isAdaptiveMode&&!this.fetchedAdDurations.has(e)){const t=await this.fetchVastDuration(e);null!==t&&(this.fetchedAdDurations.set(e,t),this.config.debugAdTiming&&console.log(`[ADAPTIVE-POD] ✓ Fetched ad duration: ${t}s (${this.fetchedAdDurations.size} ads fetched so far)`),await this.addAdaptiveAdsToQueue())}this.ima.preloadAds&&!this.ima.hasPreloadedAd(e)&&(this.preloadingAdUrls.has(e)||(this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Preloading VAST: ${e}`),this.preloadingAdUrls.add(e),await this.ima.preloadAds(e).then(()=>{this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] IMA VAST preload complete: ${e}`)}).catch(t=>{this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] IMA VAST preload failed: ${e}`,t)}).finally(()=>{this.preloadingAdUrls.delete(e)})));let t=this.vastToMediaUrlMap.get(e);if(t||(this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Fetching and parsing VAST to extract media URLs: ${e}`),t=await this.fetchAndParseVastXml(e),this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Extracted ${t.length} media URLs:`,t),t.length>0&&this.vastToMediaUrlMap.set(e,t)),t&&t.length>0){const e=t[0];e&&!this.preloadedMediaUrls.has(e)&&await this.preloadMediaFile(e)}}catch(t){this.config.debugAdTiming&&console.warn(`[StormcloudVideoPlayer] Failed to preload ad: ${e}`,t)}}findNextPreloadedAd(){var e,t,i;for(let s=0;s<this.adPodQueue.length;s++){const r=this.adPodQueue[s];if(!r)continue;if(this.failedVastUrls.has(r)){console.warn("[AD-ERROR] Skipping failed URL in queue");continue}const n=null!==(i=null===(t=(e=this.ima).hasPreloadedAd)||void 0===t?void 0:t.call(e,r))&&void 0!==i&&i,a=this.vastToMediaUrlMap.get(r),o=!!(a&&a.length>0)&&this.preloadedMediaUrls.has(a[0]);if(n||o)return this.adPodQueue.splice(0,s+1),r}}getRemainingAdMs(){if(null==this.expectedAdBreakDurationMs||null==this.currentAdBreakStartWallClockMs)return 0;const e=Date.now()-this.currentAdBreakStartWallClockMs;return Math.max(0,this.expectedAdBreakDurationMs-e)}findBreakForTime(e){const t=[];for(const i of t){const t=(i.startTimeMs||0)+(i.durationMs||0);if(e>=(i.startTimeMs||0)&&(!i.durationMs||e<t))return i}}toggleMute(){if(this.ima.isAdPlaying()){const e=!this.isMuted();this.ima.updateOriginalMutedState(e,this.video.volume),this.ima.setAdVolume(e?0:1),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:",e)}else this.video.muted=!this.video.muted,this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted:",this.video.muted)}toggleFullscreen(){return new Promise((e,t)=>{if(document.fullscreenElement)document.exitFullscreen().then(()=>{this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Exited fullscreen"),e()}).catch(e=>{this.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Exit fullscreen error:",e),t(e)});else{const i=this.video.parentElement;if(!i)return void t(new Error("No parent container found for fullscreen"));i.requestFullscreen().then(()=>{this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Entered fullscreen"),e()}).catch(e=>{this.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Fullscreen error:",e),t(e)})}})}isMuted(){return this.ima.isAdPlaying()?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] isMuted() override during ad playback -> false"),!1):this.video.muted}setMuted(e){const t=this.ima.isAdPlaying();if(t&&e===this.video.muted)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted reflective update during ad ignored",{muted:e});else{if(this.video.muted=e,t)return this.ima.updateOriginalMutedState(e,this.video.volume),this.ima.setAdVolume(e?0:1),void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted applied during ad",{muted:e}));this.ima.updateOriginalMutedState(e,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted called:",e)}}setVolume(e){const t=Math.max(0,Math.min(1,e));this.ima.isAdPlaying()?(this.ima.setAdVolume(t),this.ima.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume applied during ad",{volume:t})):(this.video.volume=t,this.video.muted=0===t,this.ima.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume called:",t))}isFullscreen(){return!!document.fullscreenElement}isLive(){return this.isLiveStream}get videoElement(){return this.video}resize(){if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing player"),this.ima&&this.ima.isAdPlaying()){const e=this.video.clientWidth||640,t=this.video.clientHeight||360;this.config.debugAdTiming&&console.log(`[StormcloudVideoPlayer] Resizing ads manager to ${e}x${t}`),this.ima.resize(e,t)}}destroy(){var e,t;this.stopContinuousFetching(),this.clearAdStartTimer(),this.clearAdStopTimer(),this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog(),this.timeUpdateHandler&&(this.video.removeEventListener("timeupdate",this.timeUpdateHandler),delete this.timeUpdateHandler),this.emptiedHandler&&(this.video.removeEventListener("emptied",this.emptiedHandler),delete this.emptiedHandler),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),null===(e=this.hls)||void 0===e||e.destroy(),null===(t=this.ima)||void 0===t||t.destroy(),this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.adPodAllUrls=[],this.adRequestQueue=[],this.successfulAdRequests=[]}}var Ul={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Nl=g.createContext&&g.createContext(Ul),Bl=["attr","size","title"];function $l(e,t){if(null==e)return{};var i,s,r=function(e,t){if(null==e)return{};var i={};for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s)){if(t.indexOf(s)>=0)continue;i[s]=e[s]}return i}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(s=0;s<n.length;s++)i=n[s],t.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}function Vl(){return Vl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},Vl.apply(this,arguments)}function Gl(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function Hl(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Gl(Object(i),!0).forEach(function(t){Kl(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Gl(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function Kl(e,t,i){var s;return(t="symbol"==typeof(s=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t||"default");if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"))?s:s+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function jl(e){return e&&e.map((e,t)=>g.createElement(e.tag,Hl({key:t},e.attr),jl(e.child)))}function Wl(e){return t=>g.createElement(ql,Vl({attr:Hl({},e.attr)},t),jl(e.child))}function ql(e){var t=t=>{var i,{attr:s,size:r,title:n}=e,a=$l(e,Bl),o=r||t.size||"1em";return t.className&&(i=t.className),e.className&&(i=(i?i+" ":"")+e.className),g.createElement("svg",Vl({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,s,a,{className:i,style:Hl(Hl({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),n&&g.createElement("title",null,n),e.children)};return void 0!==Nl?g.createElement(Nl.Consumer,null,e=>t(e)):t(Ul)}function Yl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M436 192H312c-13.3 0-24-10.7-24-24V44c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v84h84c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm-276-24V44c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v84H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24zm0 300V344c0-13.3-10.7-24-24-24H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-84h84c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12H312c-13.3 0-24 10.7-24 24v124c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function zl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M0 180V56c0-13.3 10.7-24 24-24h124c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12H64v84c0 6.6-5.4 12-12 12H12c-6.6 0-12-5.4-12-12zM288 44v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12V56c0-13.3-10.7-24-24-24H300c-6.6 0-12 5.4-12 12zm148 276h-40c-6.6 0-12 5.4-12 12v84h-84c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24V332c0-6.6-5.4-12-12-12zM160 468v-40c0-6.6-5.4-12-12-12H64v-84c0-6.6-5.4-12-12-12H12c-6.6 0-12 5.4-12 12v124c0 13.3 10.7 24 24 24h124c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function Xl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z"},child:[]}]})(e)}function Ql(e){return Wl({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z"},child:[]}]})(e)}function Jl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z"},child:[]}]})(e)}function Zl(e){return Wl({tag:"svg",attr:{viewBox:"0 0 384 512"},child:[{tag:"path",attr:{d:"M215.03 72.04L126.06 161H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V89.02c0-21.47-25.96-31.98-40.97-16.98zm123.2 108.08c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 229.28 336 242.62 336 257c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.87z"},child:[]}]})(e)}function ed(e){return Wl({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zM461.64 256l45.64-45.64c6.3-6.3 6.3-16.52 0-22.82l-22.82-22.82c-6.3-6.3-16.52-6.3-22.82 0L416 210.36l-45.64-45.64c-6.3-6.3-16.52-6.3-22.82 0l-22.82 22.82c-6.3 6.3-6.3 16.52 0 22.82L370.36 256l-45.63 45.63c-6.3 6.3-6.3 16.52 0 22.82l22.82 22.82c6.3 6.3 16.52 6.3 22.82 0L416 301.64l45.64 45.64c6.3 6.3 16.52 6.3 22.82 0l22.82-22.82c6.3-6.3 6.3-16.52 0-22.82L461.64 256z"},child:[]}]})(e)}function td(e){return Wl({tag:"svg",attr:{viewBox:"0 0 576 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zm233.32-51.08c-11.17-7.33-26.18-4.24-33.51 6.95-7.34 11.17-4.22 26.18 6.95 33.51 66.27 43.49 105.82 116.6 105.82 195.58 0 78.98-39.55 152.09-105.82 195.58-11.17 7.32-14.29 22.34-6.95 33.5 7.04 10.71 21.93 14.56 33.51 6.95C528.27 439.58 576 351.33 576 256S528.27 72.43 448.35 19.97zM480 256c0-63.53-32.06-121.94-85.77-156.24-11.19-7.14-26.03-3.82-33.12 7.46s-3.78 26.21 7.41 33.36C408.27 165.97 432 209.11 432 256s-23.73 90.03-63.48 115.42c-11.19 7.14-14.5 22.07-7.41 33.36 6.51 10.36 21.12 15.14 33.12 7.46C447.94 377.94 480 319.54 480 256zm-141.77-76.87c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 228.28 336 241.63 336 256c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.86z"},child:[]}]})(e)}const id=["src","allowNativeHls","licenseKey","lowLatencyMode","driftToleranceMs","vastMode"],sd=g.memo(e=>{const{src:t,autoplay:i,muted:s,lowLatencyMode:r,allowNativeHls:n,driftToleranceMs:a,immediateManifestAds:o,debugAdTiming:l,showCustomControls:d,onVolumeToggle:h,onFullscreenToggle:c,onControlClick:m,onReady:p,wrapperClassName:y,wrapperStyle:v,className:T,style:E,controls:S,playsInline:A,preload:b,poster:L,children:R,licenseKey:I,vastMode:k,vastTagUrl:P,adPlayerType:w,minSegmentsBeforePlay:D,...x}=e,C=f.useRef(null),_=f.useRef(null),M=f.useRef(null),[O,F]=g.useState({showAds:!1,currentIndex:0,totalAds:0}),[U,N]=g.useState(!0),[B,$]=g.useState(!1),[V,G]=g.useState(!1),[H,K]=g.useState(!1),[j,W]=g.useState(0),[q,Y]=g.useState(0),[z,X]=g.useState(1),[Q,J]=g.useState(1),[Z,ee]=g.useState(!1),[te,ie]=g.useState(!1),[se,re]=g.useState(!0),[ne,ae]=g.useState(!1),[oe,le]=g.useState(!1),[de,he]=g.useState(!1),[ce,ue]=g.useState("undefined"!=typeof window?window.innerWidth:1920),[fe,ge]=g.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),me=ce<480?.7:ce<768?.8:ce<1024?.9:1,pe=e=>{if(!isFinite(e))return"0:00:00";const t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=Math.floor(e%60);return`${t}:${i.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`},ye=e=>{if(_.current&&isFinite(e)){const t=Math.max(0,Math.min(1,e));_.current.setVolume(t)}},ve=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),Te=d&&(!ve||n),Ee=f.useMemo(()=>id.map(t=>`${t}:${e[t]}`).join("|"),[t,n,I,r,a,k]);return f.useEffect(()=>{if("undefined"==typeof window)return;const e=C.current;if(!e||!t)return;if(!I)return he(!0),re(!1),void console.warn("StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.");if(he(!1),l&&console.log("[StormcloudUI] Initializing player, isLoading=true"),_.current){try{_.current.destroy()}catch{}_.current=null}const u={src:t,videoElement:e};void 0!==i&&(u.autoplay=i),void 0!==s&&(u.muted=s),void 0!==r&&(u.lowLatencyMode=r),void 0!==n&&(u.allowNativeHls=n),void 0!==a&&(u.driftToleranceMs=a),void 0!==o&&(u.immediateManifestAds=o),void 0!==l&&(u.debugAdTiming=l),void 0!==d&&(u.showCustomControls=d),void 0!==h&&(u.onVolumeToggle=h),void 0!==c&&(u.onFullscreenToggle=c),void 0!==m&&(u.onControlClick=m),void 0!==I&&(u.licenseKey=I),void 0!==k&&(u.vastMode=k),void 0!==P&&(u.vastTagUrl=P),void 0!==w&&(u.adPlayerType=w),void 0!==D&&(u.minSegmentsBeforePlay=D);const f=new Fl(u);return _.current=f,f.load().then(()=>{const e=f.shouldShowNativeControls();N(e),l&&console.log("[StormcloudUI] Player loaded successfully, waiting for video ready"),null==p||p(f)}).catch(e=>{console.error("StormcloudVideoPlayer: Failed to load player:",e),re(!1),null==p||p(f)}),()=>{try{f.destroy()}catch{}_.current=null}},[Ee]),f.useEffect(()=>{if(_.current)try{void 0!==i&&_.current.videoElement&&(_.current.videoElement.autoplay=i),void 0===s||_.current.isShowingAds()||_.current.setMuted(s)}catch(e){console.warn("Failed to update player properties:",e)}},[i,s]),f.useEffect(()=>{if(!_.current)return;const e=setInterval(()=>{if(_.current){const e=_.current.isShowingAds(),t=_.current.getCurrentAdIndex(),i=_.current.getTotalAdsInBreak();F(s=>s.showAds!==e||s.currentIndex!==t||s.totalAds!==i?{showAds:e,currentIndex:t,totalAds:i}:s)}},100);return()=>clearInterval(e)},[]),f.useEffect(()=>{if("undefined"==typeof window||!_.current)return;const e=()=>{_.current&&C.current&&"function"==typeof _.current.resize&&_.current.resize(),ue(window.innerWidth),ge(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),f.useEffect(()=>{if(!_.current||!C.current)return;const e=setInterval(()=>{var e;if(_.current&&C.current){$(_.current.isMuted()),K(!C.current.paused);const e=C.current.currentTime;W(isFinite(e)?e:0);const t=C.current.duration;Y(isFinite(t)?t:0);const i=C.current.volume;X(isFinite(i)?Math.max(0,Math.min(1,i)):1);const s=C.current.playbackRate;J(isFinite(s)&&s>0?s:1)}G(document.fullscreenElement===(null===(e=C.current)||void 0===e?void 0:e.parentElement))},200),t=()=>{var e;G(document.fullscreenElement===(null===(e=C.current)||void 0===e?void 0:e.parentElement))};return document.addEventListener("fullscreenchange",t),()=>{clearInterval(e),document.removeEventListener("fullscreenchange",t)}},[]),f.useEffect(()=>{if(!C.current)return;const e=()=>{var e;if(C.current){C.current.offsetHeight}l&&console.log("[StormcloudUI] Video event: loadedmetadata, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState)},t=()=>{var e;l&&console.log("[StormcloudUI] Video event: loadeddata, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState)},i=()=>{var e;l&&console.log("[StormcloudUI] Video event: loadstart, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState)},s=()=>{var e;re(!1),M.current&&(clearTimeout(M.current),M.current=null),ae(!1),l&&console.log("[StormcloudUI] Video event: canplay, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},r=()=>{var e;re(!1),M.current&&(clearTimeout(M.current),M.current=null),ae(!1),l&&console.log("[StormcloudUI] Video event: canplaythrough, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},n=()=>{var e;M.current&&clearTimeout(M.current),M.current=window.setTimeout(()=>{var e;ae(!0),l&&console.log("[StormcloudUI] Video buffering detected (after 300ms delay), readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- showing spinner, isBuffering=true")},300),l&&console.log("[StormcloudUI] Video event: waiting, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- buffering delay started (300ms)")},a=()=>{var e;re(!1),M.current&&(clearTimeout(M.current),M.current=null),ae(!1),le(!1),l&&console.log("[StormcloudUI] Video event: playing, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- playback started, isLoading=false, isBuffering=false")},o=()=>{_.current&&!_.current.isShowingAds()?le(!0):le(!1)},d=()=>{le(!0)},h=C.current;return h.addEventListener("loadstart",i),h.addEventListener("loadedmetadata",e),h.addEventListener("loadeddata",t),h.addEventListener("canplay",s),h.addEventListener("canplaythrough",r),h.addEventListener("waiting",n),h.addEventListener("playing",a),h.addEventListener("pause",o),h.addEventListener("ended",d),h.paused&&le(!0),()=>{M.current&&(clearTimeout(M.current),M.current=null),h.removeEventListener("loadstart",i),h.removeEventListener("loadedmetadata",e),h.removeEventListener("loadeddata",t),h.removeEventListener("canplay",s),h.removeEventListener("canplaythrough",r),h.removeEventListener("waiting",n),h.removeEventListener("playing",a),h.removeEventListener("pause",o),h.removeEventListener("ended",d)}},[l]),u.jsxs(u.Fragment,{children:[u.jsx("style",{children:"\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n \n .stormcloud-video-wrapper:fullscreen {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n .stormcloud-video-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n *:fullscreen {\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n }\n "}),u.jsxs("div",{className:`stormcloud-video-wrapper ${y||""}`,style:{display:"flex",alignItems:"center",justifyContent:"center",position:V?"fixed":"relative",top:V?0:void 0,left:V?0:void 0,overflow:"hidden",width:V?"100vw":"100%",height:V?"100vh":"auto",minHeight:V?"100vh":"auto",maxWidth:V?"100vw":"100%",maxHeight:V?"100vh":"none",zIndex:V?999999:void 0,backgroundColor:V?"#000":void 0,borderRadius:V?0:void 0,boxShadow:V?"none":void 0,...v},children:[u.jsx("video",{ref:C,className:T,style:{display:"block",width:"100%",height:V?"100%":"auto",maxWidth:"100%",maxHeight:V?"100%":"none",objectFit:V?"cover":"contain",backgroundColor:"#000",aspectRatio:V?"unset":void 0,...E},controls:U&&S&&!d,playsInline:A,preload:b,poster:L,...x,children:R}),(se||ne)&&u.jsx(Jl,{size:42,color:"white",style:{position:"absolute",top:"calc(50% - 21px)",left:"calc(50% - 21px)",zIndex:20,animation:"spin 1s linear infinite",filter:"drop-shadow(0 3px 6px rgba(0, 0, 0, 0.8))"}}),de&&u.jsxs("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:25,background:"linear-gradient(135deg, rgba(220, 38, 38, 0.95) 0%, rgba(185, 28, 28, 0.9) 100%)",color:"white",padding:"24px 32px",borderRadius:"16px",backdropFilter:"blur(20px)",border:"2px solid rgba(255, 255, 255, 0.2)",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.6), inset 0 2px 0 rgba(255, 255, 255, 0.2)",textAlign:"center",maxWidth:"400px",margin:"0 16px"},children:[u.jsx("div",{style:{fontSize:"20px",fontWeight:"bold",marginBottom:"12px",color:"#ffffff",textShadow:"0 2px 4px rgba(0, 0, 0, 0.5)"},children:"License Key Required"}),u.jsxs("div",{style:{fontSize:"14px",lineHeight:"1.5",color:"rgba(255, 255, 255, 0.9)",textShadow:"0 1px 2px rgba(0, 0, 0, 0.3)"},children:["Please provide a valid license key to use the Stormcloud Video Player.",u.jsx("br",{}),"Contact your administrator for licensing information."]})]}),oe&&!se&&!ne&&!de&&!O.showAds&&u.jsx("div",{onClick:()=>{var e;if(C.current&&C.current.paused){C.current.src||C.current.currentSrc&&""!==C.current.currentSrc||C.current.readyState>=1?(null===(e=C.current.play())||void 0===e||e.catch(e=>{console.error("[StormcloudVideoPlayer] Failed to play:",e)}),le(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source")}},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",borderRadius:"50%",width:"100px",height:"100px",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",border:"3px solid rgba(255, 255, 255, 0.8)",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"},onMouseEnter:e=>{const t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.95) 0%, rgba(40, 40, 40, 0.9) 100%)",t.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.borderColor="rgba(255, 255, 255, 0.9)"},onMouseLeave:e=>{const t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",t.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",t.style.borderColor="rgba(255, 255, 255, 0.8)"},title:"Play",children:u.jsx(Ql,{size:36,color:"white",style:{marginLeft:"6px",filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))"}})}),Te&&!de?u.jsx(u.Fragment,{children:u.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.8) 100%)",padding:"20px 16px 16px",zIndex:10},children:[u.jsxs("div",{style:{width:"100%",height:"8px",background:"linear-gradient(90deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%)",borderRadius:"8px",marginBottom:"16px",cursor:"pointer",position:"relative",backdropFilter:"blur(5px)",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"inset 0 2px 4px rgba(0, 0, 0, 0.2)"},onClick:e=>{if(C.current&&q>0&&isFinite(q)){const t=e.currentTarget.getBoundingClientRect(),i=e.clientX-t.left,s=Math.max(0,Math.min(1,i/t.width))*q;isFinite(s)&&s>=0&&s<=q&&(C.current.currentTime=s)}},children:[u.jsx("div",{style:{height:"100%",background:"linear-gradient(90deg, rgba(139, 92, 246, 0.9) 0%, rgba(59, 130, 246, 0.8) 50%, rgba(34, 197, 94, 0.9) 100%)",borderRadius:"8px",width:(q>0?j/q*100:0)+"%",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 2px 8px rgba(139, 92, 246, 0.4)"}}),u.jsx("div",{style:{position:"absolute",top:"-6px",right:(q>0?100-j/q*100:100)+"%",width:"20px",height:"20px",background:"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(240, 240, 240, 0.9) 100%)",borderRadius:"50%",border:"3px solid rgba(139, 92, 246, 0.8)",boxShadow:"0 4px 16px rgba(139, 92, 246, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.8)",transform:"translateX(50%)",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)"}})]}),u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",color:"white",flexWrap:ce<768?"wrap":"nowrap",gap:8*me+"px"},children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12*me+"px",flexWrap:ce<480?"wrap":"nowrap"},children:[u.jsx("button",{onClick:()=>{var e;if(C.current)if(C.current.paused){C.current.src||C.current.currentSrc&&""!==C.current.currentSrc||C.current.readyState>=1?(null===(e=C.current.play())||void 0===e||e.catch(e=>{console.error("[StormcloudVideoPlayer] Failed to play:",e)}),le(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source")}else C.current.pause(),le(!0)},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",backdropFilter:"blur(12px)",border:2*me+"px solid rgba(255, 255, 255, 0.3)",color:"#ffffff",cursor:"pointer",padding:10*me+"px",borderRadius:16*me+"px",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)",minWidth:48*me+"px",minHeight:48*me+"px"},onMouseEnter:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)",t.style.boxShadow="0 12px 48px rgba(0, 0, 0, 0.6), 0 6px 24px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.4)"},onMouseLeave:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",t.style.boxShadow="0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)"},title:H?"Pause":"Play",children:H?u.jsx(Xl,{size:Math.max(16,20*me),style:{filter:"drop-shadow(0 0 0 transparent)"}}):u.jsx(Ql,{size:Math.max(16,20*me),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),u.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1),children:[u.jsx("button",{onClick:()=>{_.current&&_.current.toggleMute(),h&&h()},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:2*me+"px solid rgba(255, 255, 255, 0.3)",color:"#ffffff",cursor:"pointer",padding:8*me+"px",borderRadius:16*me+"px",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:44*me+"px",minHeight:44*me+"px"},onMouseEnter:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:B?"Unmute":"Mute",children:B||0===z?u.jsx(ed,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}}):z<.5?u.jsx(Zl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}}):u.jsx(td,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),Z&&u.jsxs(u.Fragment,{children:[u.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1)}),u.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.88) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(15px)",padding:"10px 14px",borderRadius:"14px",border:"1px solid rgba(255, 255, 255, 0.15)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:e=>{ee(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.6), 0 6px 16px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 0 24px rgba(59, 130, 246, 0.3)",e.currentTarget.style.borderColor="rgba(59, 130, 246, 0.4)"},onMouseLeave:e=>{ee(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.15)"},children:u.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseEnter:e=>{},onMouseLeave:e=>{},onMouseDown:e=>{e.preventDefault();const t=e.currentTarget,i=e=>{if(!t)return;const i=t.getBoundingClientRect(),s=e.clientY-i.top,r=1-Math.max(0,Math.min(1,s/i.height));ye(r)},s=()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",s)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",s);const r=t.getBoundingClientRect(),n=e.clientY-r.top,a=1-Math.max(0,Math.min(1,n/r.height));ye(a)},onClick:e=>{e.stopPropagation();const t=e.currentTarget.getBoundingClientRect(),i=e.clientY-t.top,s=1-Math.max(0,Math.min(1,i/t.height));ye(s)},children:[u.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.15) 100%)",borderRadius:"4px",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.2)"}}),u.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:100*(B?0:z)+"%",background:"linear-gradient(180deg, rgba(96, 165, 250, 1) 0%, rgba(59, 130, 246, 0.95) 50%, rgba(37, 99, 235, 0.9) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 8px rgba(59, 130, 246, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.3)"}}),u.jsx("div",{style:{position:"absolute",bottom:`calc(${100*(B?0:z)}% - 7px)`,left:"50%",transform:"translateX(-50%)",width:"14px",height:"14px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:e=>{e.currentTarget.style.boxShadow="0 3px 10px rgba(0, 0, 0, 0.4), 0 0 0 3px rgba(59, 130, 246, 0.5), 0 0 20px rgba(59, 130, 246, 0.6)",e.currentTarget.style.cursor="grab"},onMouseLeave:e=>{e.currentTarget.style.boxShadow="0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)"},onMouseDown:e=>{e.currentTarget.style.cursor="grabbing"},onMouseUp:e=>{e.currentTarget.style.cursor="grab"}})]})})]})]}),u.jsxs("div",{style:{fontSize:14*me+"px",fontFamily:"monospace",color:"rgba(255, 255, 255, 0.9)",display:ce<480?"none":"block"},children:[pe(j)," / ",pe(q)]})]}),u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12*me+"px"},children:[u.jsxs("div",{style:{position:"relative",display:ce<600?"none":"block"},children:[u.jsxs("button",{onClick:()=>ie(!te),style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:2*me+"px solid rgba(255, 255, 255, 0.3)",color:"#ffffff",cursor:"pointer",padding:`${8*me}px ${14*me}px`,borderRadius:14*me+"px",fontSize:14*me+"px",fontFamily:"monospace",fontWeight:"700",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:56*me+"px",minHeight:40*me+"px"},onMouseEnter:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 32px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:"Playback Speed",children:[Q,"x"]}),te&&u.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,marginBottom:"12px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.95) 100%)",backdropFilter:"blur(20px)",borderRadius:"12px",border:"1px solid rgba(255, 255, 255, 0.1)",overflow:"hidden",minWidth:"90px",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.1)"},children:[.25,.5,.75,1,1.25,1.5,1.75,2].map(e=>u.jsxs("button",{onClick:()=>{return t=e,C.current&&isFinite(t)&&t>0&&(C.current.playbackRate=t),void ie(!1);var t},style:{display:"block",width:"100%",padding:"10px 16px",background:Q===e?"linear-gradient(135deg, rgba(99, 102, 241, 0.8) 0%, rgba(139, 92, 246, 0.6) 100%)":"transparent",border:"none",color:"white",cursor:"pointer",fontSize:"13px",fontFamily:"monospace",fontWeight:"600",textAlign:"center",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",borderBottom:2!==e?"1px solid rgba(255, 255, 255, 0.05)":"none"},onMouseEnter:t=>{Q!==e&&(t.target.style.background="linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%)")},onMouseLeave:t=>{Q!==e&&(t.target.style.background="transparent")},children:[e,"x"]},e))})]}),u.jsx("button",{onClick:()=>{c?c():_.current&&_.current.toggleFullscreen().catch(e=>{console.error("Fullscreen error:",e)})},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:2*me+"px solid rgba(255, 255, 255, 0.3)",color:"#ffffff",cursor:"pointer",padding:8*me+"px",borderRadius:16*me+"px",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:44*me+"px",minHeight:44*me+"px"},onMouseEnter:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:e=>{const t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:V?"Exit Fullscreen":"Enter Fullscreen",children:V?u.jsx(Yl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}}):u.jsx(zl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 0 0 transparent)"}})})]})]})]})}):d&&!de&&u.jsxs("div",{style:{position:"absolute",bottom:10*me+"px",right:10*me+"px",transform:"none",display:"flex",flexDirection:fe?"column":"row",gap:10*me+"px",zIndex:10},children:[u.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1),children:[u.jsx("button",{onClick:()=>{_.current&&_.current.toggleMute(),h&&h()},onMouseEnter:e=>{const t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:e=>{const t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:18*me+"px",padding:8*me+"px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:46*me+"px",minHeight:46*me+"px"},title:B?"Unmute":"Mute",children:B||0===z?u.jsx(ed,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):z<.5?u.jsx(Zl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):u.jsx(td,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})}),Z&&u.jsxs(u.Fragment,{children:[u.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1)}),u.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.96) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(20px)",padding:"10px 14px",borderRadius:"14px",border:"2px solid rgba(255, 255, 255, 0.7)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:e=>{ee(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), 0 6px 16px rgba(0, 0, 0, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 0 24px rgba(96, 165, 250, 0.4)",e.currentTarget.style.borderColor="rgba(96, 165, 250, 0.8)"},onMouseLeave:e=>{ee(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.7)"},children:u.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseDown:e=>{e.preventDefault();const t=e.currentTarget,i=e=>{if(!t)return;const i=t.getBoundingClientRect(),s=e.clientY-i.top,r=1-Math.max(0,Math.min(1,s/i.height));ye(r)},s=()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",s)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",s);const r=t.getBoundingClientRect(),n=e.clientY-r.top,a=1-Math.max(0,Math.min(1,n/r.height));ye(a)},onClick:e=>{e.stopPropagation();const t=e.currentTarget.getBoundingClientRect(),i=e.clientY-t.top,s=1-Math.max(0,Math.min(1,i/t.height));ye(s)},children:[u.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.85) 0%, rgba(255, 255, 255, 0.5) 100%)",borderRadius:"4px",border:"1px solid rgba(255, 255, 255, 0.4)",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.3)"}}),u.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:100*(B?0:z)+"%",background:"linear-gradient(180deg, rgba(125, 211, 252, 1) 0%, rgba(96, 165, 250, 0.98) 50%, rgba(59, 130, 246, 0.95) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 12px rgba(96, 165, 250, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.4)"}}),u.jsx("div",{style:{position:"absolute",bottom:`calc(${100*(B?0:z)}% - 8px)`,left:"50%",transform:"translateX(-50%)",width:"16px",height:"16px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",border:"2px solid rgba(96, 165, 250, 0.9)",boxShadow:"0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:e=>{e.currentTarget.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.6), 0 0 0 3px rgba(96, 165, 250, 0.6), 0 0 24px rgba(96, 165, 250, 0.7)",e.currentTarget.style.cursor="grab"},onMouseLeave:e=>{e.currentTarget.style.boxShadow="0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)"},onMouseDown:e=>{e.currentTarget.style.cursor="grabbing"},onMouseUp:e=>{e.currentTarget.style.cursor="grab"}})]})})]})]}),u.jsx("button",{onClick:()=>{c?c():_.current&&_.current.toggleFullscreen().catch(e=>{console.error("Fullscreen error:",e)})},onMouseEnter:e=>{const t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:e=>{const t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:18*me+"px",padding:8*me+"px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:46*me+"px",minHeight:46*me+"px"},title:V?"Exit Fullscreen":"Enter Fullscreen",children:V?u.jsx(Yl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):u.jsx(zl,{size:Math.max(14,16*me),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})})]}),m&&u.jsx("div",{onClick:m,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},(e,t)=>{for(const i of id)if(e[i]!==t[i])return!1;const i=["autoplay","muted","controls","showCustomControls","className","style","wrapperClassName","wrapperStyle","playsInline","preload","poster","children"];for(const s of i)if(e[s]!==t[s])return!1;const s=["onReady","onVolumeToggle","onFullscreenToggle","onControlClick"];for(const i of s)if(e[i]!==t[i])return!1;return!0}),rd=()=>{},nd={playing:!1,loop:!1,controls:!0,volume:1,muted:!1,playbackRate:1,width:"100%",height:"auto",style:{},progressInterval:1e3,playsInline:!1,autoplay:!1,preload:"metadata",poster:"",className:"",wrapperClassName:"",wrapperStyle:{},allowNativeHls:!1,lowLatencyMode:!1,driftToleranceMs:1e3,immediateManifestAds:!0,debugAdTiming:!1,showCustomControls:!1,licenseKey:"",adFailsafeTimeoutMs:1e4,minSegmentsBeforePlay:2,onStart:rd,onPlay:rd,onPause:rd,onBuffer:rd,onBufferEnd:rd,onEnded:rd,onError:rd,onDuration:rd,onSeek:rd,onProgress:rd,onVolumeToggle:rd,onFullscreenToggle:rd,onControlClick:rd},ad=f.lazy,od=(e,t)=>{const i={...e};return t.forEach(e=>{delete i[e]}),i},ld=e=>"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream,dd=(e,...t)=>{if(!t.length)return e;const i=t.shift();if(hd(e)&&hd(i))for(const t in i)hd(i[t])?(e[t]||Object.assign(e,{[t]:{}}),dd(e[t],i[t])):Object.assign(e,{[t]:i[t]});return dd(e,...t)},hd=e=>e&&"object"==typeof e&&!Array.isArray(e),cd="undefined"!=typeof window&&window.document,ud="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,fd=cd&&/iPad|iPhone|iPod/.test(navigator.userAgent),gd=cd&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),md=/\.(m3u8)($|\?)/i,pd=/\/hls\//i,yd=/\.(mpd)($|\?)/i,vd=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,Td=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,Ed={hls:e=>!(!e||"string"!=typeof e)&&(md.test(e)||pd.test(e)),dash:e=>!(!e||"string"!=typeof e)&&yd.test(e),video:e=>!(!e||"string"!=typeof e)&&vd.test(e),audio:e=>!(!e||"string"!=typeof e)&&Td.test(e),file:e=>!(!e||"string"!=typeof e)&&(vd.test(e)||Td.test(e))};class Sd extends f.Component{constructor(){super(...arguments),this.player=null,this.mounted=!1,this.load=async()=>{var e,t,i,s,r,n;if(this.props.videoElement&&this.props.src)try{this.player&&(this.player.destroy(),this.player=null);const r={src:this.props.src,videoElement:this.props.videoElement};void 0!==this.props.autoplay&&(r.autoplay=this.props.autoplay),void 0!==this.props.muted&&(r.muted=this.props.muted),void 0!==this.props.lowLatencyMode&&(r.lowLatencyMode=this.props.lowLatencyMode),void 0!==this.props.allowNativeHls&&(r.allowNativeHls=this.props.allowNativeHls),void 0!==this.props.driftToleranceMs&&(r.driftToleranceMs=this.props.driftToleranceMs),void 0!==this.props.immediateManifestAds&&(r.immediateManifestAds=this.props.immediateManifestAds),void 0!==this.props.debugAdTiming&&(r.debugAdTiming=this.props.debugAdTiming),void 0!==this.props.showCustomControls&&(r.showCustomControls=this.props.showCustomControls),void 0!==this.props.onVolumeToggle&&(r.onVolumeToggle=this.props.onVolumeToggle),void 0!==this.props.onFullscreenToggle&&(r.onFullscreenToggle=this.props.onFullscreenToggle),void 0!==this.props.onControlClick&&(r.onControlClick=this.props.onControlClick),void 0!==this.props.licenseKey&&(r.licenseKey=this.props.licenseKey),void 0!==this.props.adFailsafeTimeoutMs&&(r.adFailsafeTimeoutMs=this.props.adFailsafeTimeoutMs),void 0!==this.props.minSegmentsBeforePlay&&(r.minSegmentsBeforePlay=this.props.minSegmentsBeforePlay),this.player=new Fl(r),null===(t=(e=this.props).onMount)||void 0===t||t.call(e,this),await this.player.load(),this.mounted&&(null===(s=(i=this.props).onReady)||void 0===s||s.call(i))}catch(e){this.mounted&&(null===(n=(r=this.props).onError)||void 0===n||n.call(r,e))}},this.play=()=>{var e,t,i;if(this.props.videoElement){const s=this.props.videoElement;s.src||s.currentSrc&&""!==s.currentSrc||s.readyState>=1?(null===(e=s.play())||void 0===e||e.catch(e=>{var t,i;console.error("[HlsPlayer] Failed to play:",e),null===(i=(t=this.props).onError)||void 0===i||i.call(t,e)}),null===(i=(t=this.props).onPlay)||void 0===i||i.call(t)):console.warn("[HlsPlayer] Cannot play: video has no valid source")}},this.pause=()=>{var e,t;this.props.videoElement&&(this.props.videoElement.pause(),null===(t=(e=this.props).onPause)||void 0===t||t.call(e))},this.stop=()=>{this.pause(),this.props.videoElement&&(this.props.videoElement.currentTime=0)},this.seekTo=(e,t)=>{this.props.videoElement&&(this.props.videoElement.currentTime=e,t||this.pause())},this.setVolume=e=>{this.props.videoElement&&(this.props.videoElement.volume=Math.max(0,Math.min(1,e)))},this.mute=()=>{this.props.videoElement&&(this.props.videoElement.muted=!0)},this.unmute=()=>{this.props.videoElement&&(this.props.videoElement.muted=!1)},this.setPlaybackRate=e=>{this.props.videoElement&&e>0&&(this.props.videoElement.playbackRate=e)},this.getDuration=()=>this.props.videoElement&&isFinite(this.props.videoElement.duration)?this.props.videoElement.duration:null,this.getCurrentTime=()=>this.props.videoElement&&isFinite(this.props.videoElement.currentTime)?this.props.videoElement.currentTime:null,this.getSecondsLoaded=()=>this.props.videoElement&&this.props.videoElement.buffered.length>0?this.props.videoElement.buffered.end(this.props.videoElement.buffered.length-1):null,this.getInternalPlayer=(e="player")=>"player"===e?this.player:"video"===e?this.props.videoElement:"hls"===e&&this.player?this.player.hls:null}componentDidMount(){this.mounted=!0,this.load()}componentWillUnmount(){this.mounted=!1,this.player&&(this.player.destroy(),this.player=null)}componentDidUpdate(e){e.src!==this.props.src&&this.load()}render(){return null}}Sd.displayName="HlsPlayer",Sd.canPlay=Ed.hls;class Ad extends f.Component{constructor(){super(...arguments),this.mounted=!1,this.ready=!1,this.load=()=>{var e,t;if(!this.props.videoElement||!this.props.src)return;const i=this.props.videoElement,s=()=>{var e,t;this.mounted&&!this.ready&&(this.ready=!0,null===(t=(e=this.props).onReady)||void 0===t||t.call(e))},r=()=>{var e,t;this.mounted&&(null===(t=(e=this.props).onPlay)||void 0===t||t.call(e))},n=()=>{var e,t;this.mounted&&(null===(t=(e=this.props).onPause)||void 0===t||t.call(e))},a=()=>{var e,t;this.mounted&&(null===(t=(e=this.props).onEnded)||void 0===t||t.call(e))},o=e=>{var t,i;this.mounted&&(null===(i=(t=this.props).onError)||void 0===i||i.call(t,e))},l=()=>{var e,t;this.mounted&&(null===(t=(e=this.props).onLoaded)||void 0===t||t.call(e))};return i.addEventListener("loadedmetadata",s),i.addEventListener("play",r),i.addEventListener("pause",n),i.addEventListener("ended",a),i.addEventListener("error",o),i.addEventListener("loadeddata",l),i.src=this.props.src,void 0!==this.props.autoplay&&(i.autoplay=this.props.autoplay),void 0!==this.props.muted&&(i.muted=this.props.muted),void 0!==this.props.loop&&(i.loop=this.props.loop),void 0!==this.props.controls&&(i.controls=this.props.controls),void 0!==this.props.playsInline&&(i.playsInline=this.props.playsInline),void 0!==this.props.preload&&(i.preload=this.props.preload),void 0!==this.props.poster&&(i.poster=this.props.poster),null===(t=(e=this.props).onMount)||void 0===t||t.call(e,this),()=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("play",r),i.removeEventListener("pause",n),i.removeEventListener("ended",a),i.removeEventListener("error",o),i.removeEventListener("loadeddata",l)}},this.play=()=>{var e;if(this.props.videoElement){const t=this.props.videoElement;t.src||t.currentSrc&&""!==t.currentSrc||t.readyState>=1?null===(e=t.play())||void 0===e||e.catch(e=>{var t,i;console.error("[FilePlayer] Failed to play:",e),null===(i=(t=this.props).onError)||void 0===i||i.call(t,e)}):console.warn("[FilePlayer] Cannot play: video has no valid source")}},this.pause=()=>{this.props.videoElement&&this.props.videoElement.pause()},this.stop=()=>{this.pause(),this.props.videoElement&&(this.props.videoElement.currentTime=0)},this.seekTo=(e,t)=>{this.props.videoElement&&(this.props.videoElement.currentTime=e,t||this.pause())},this.setVolume=e=>{this.props.videoElement&&(this.props.videoElement.volume=Math.max(0,Math.min(1,e)))},this.mute=()=>{this.props.videoElement&&(this.props.videoElement.muted=!0)},this.unmute=()=>{this.props.videoElement&&(this.props.videoElement.muted=!1)},this.setPlaybackRate=e=>{this.props.videoElement&&e>0&&(this.props.videoElement.playbackRate=e)},this.setLoop=e=>{this.props.videoElement&&(this.props.videoElement.loop=e)},this.getDuration=()=>this.props.videoElement&&isFinite(this.props.videoElement.duration)?this.props.videoElement.duration:null,this.getCurrentTime=()=>this.props.videoElement&&isFinite(this.props.videoElement.currentTime)?this.props.videoElement.currentTime:null,this.getSecondsLoaded=()=>this.props.videoElement&&this.props.videoElement.buffered.length>0?this.props.videoElement.buffered.end(this.props.videoElement.buffered.length-1):null,this.getInternalPlayer=(e="player")=>"video"===e?this.props.videoElement:null,this.enablePIP=async()=>{if(this.props.videoElement&&"requestPictureInPicture"in this.props.videoElement)try{await this.props.videoElement.requestPictureInPicture()}catch(e){console.warn("Picture-in-Picture failed:",e)}},this.disablePIP=async()=>{if(document.pictureInPictureElement)try{await document.exitPictureInPicture()}catch(e){console.warn("Exit Picture-in-Picture failed:",e)}}}componentDidMount(){this.mounted=!0,this.load()}componentWillUnmount(){this.mounted=!1}componentDidUpdate(e){e.src!==this.props.src&&this.load()}render(){return null}}Ad.displayName="FilePlayer",Ad.canPlay=Ed.file;const bd=[{key:"hls",name:"HLS Player",canPlay:Ed.hls,lazyPlayer:ad(()=>Promise.resolve({default:Sd}))},{key:"file",name:"File Player",canPlay:Ed.file,canEnablePIP:e=>Ed.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode),lazyPlayer:ad(()=>Promise.resolve({default:Ad}))}];class Ld extends f.Component{constructor(){super(...arguments),this.mounted=!1,this.isReady=!1,this.isPlaying=!1,this.isLoading=!0,this.loadOnReady=null,this.startOnPlay=!0,this.seekOnPlay=null,this.onDurationCalled=!1,this.handlePlayerMount=e=>{this.player||(this.player=e,this.player.load(this.props.src)),this.progress()},this.getInternalPlayer=e=>this.player?this.player.getInternalPlayer(e):null,this.progress=()=>{var e,t;if(this.props.src&&this.player&&this.isReady){const i=this.getCurrentTime()||0,s=this.getSecondsLoaded(),r=this.getDuration();if(r){const n={playedSeconds:i,played:i/r,loaded:0,loadedSeconds:0};null!==s&&(n.loadedSeconds=s,n.loaded=s/r),n.playedSeconds===this.prevPlayed&&n.loadedSeconds===this.prevLoaded||null===(t=(e=this.props).onProgress)||void 0===t||t.call(e,n),this.prevPlayed=n.playedSeconds,this.prevLoaded=n.loadedSeconds}}this.progressTimeout=window.setTimeout(this.progress,this.props.progressInterval||1e3)},this.handleReady=()=>{if(!this.mounted)return;this.isReady=!0,this.isLoading=!1;const{onReady:e,playing:t,volume:i,muted:s}=this.props;e(),s||null===i||this.player.setVolume(i),this.loadOnReady?(this.player.load(this.loadOnReady,!0),this.loadOnReady=null):t&&this.player.play(),this.handleDurationCheck()},this.handlePlay=()=>{this.isPlaying=!0,this.isLoading=!1;const{onStart:e,onPlay:t,playbackRate:i}=this.props;this.startOnPlay&&(this.player.setPlaybackRate&&1!==i&&this.player.setPlaybackRate(i),null==e||e(),this.startOnPlay=!1),null==t||t(),this.seekOnPlay&&(this.seekTo(this.seekOnPlay),this.seekOnPlay=null),this.handleDurationCheck()},this.handlePause=e=>{var t,i;this.isPlaying=!1,this.isLoading||null===(i=(t=this.props).onPause)||void 0===i||i.call(t,e)},this.handleEnded=()=>{const{activePlayer:e,loop:t,onEnded:i}=this.props;e.loopOnEnded&&t&&this.seekTo(0),t||(this.isPlaying=!1,null==i||i())},this.handleError=(...e)=>{var t,i;this.isLoading=!1,null===(i=(t=this.props).onError)||void 0===i||i.call(t,e[0],e[1],e[2],e[3])},this.handleDurationCheck=()=>{var e,t;clearTimeout(this.durationCheckTimeout);const i=this.getDuration();i?this.onDurationCalled||(null===(t=(e=this.props).onDuration)||void 0===t||t.call(e,i),this.onDurationCalled=!0):this.durationCheckTimeout=window.setTimeout(this.handleDurationCheck,100)},this.handleLoaded=()=>{this.isLoading=!1}}componentDidMount(){this.mounted=!0}componentWillUnmount(){clearTimeout(this.progressTimeout),clearTimeout(this.durationCheckTimeout),this.mounted=!1}componentDidUpdate(e){if(!this.player)return;const{src:t,playing:i,volume:s,muted:r,playbackRate:n,loop:a,activePlayer:o}=this.props;if(e.src!==t){if(this.isLoading&&!o.forceLoad&&!ld(t))return console.warn(`StormcloudPlayer: the attempt to load ${t} is being deferred until the player has loaded`),void(this.loadOnReady=t||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(t,this.isReady)}e.playing||!i||this.isPlaying||this.player.play(),e.playing&&!i&&this.isPlaying&&this.player.pause(),e.volume!==s&&null!==s&&this.player.setVolume(s),e.muted!==r&&(r?this.player.mute():(this.player.unmute(),null!==s&&setTimeout(()=>this.player.setVolume(s)))),e.playbackRate!==n&&this.player.setPlaybackRate&&this.player.setPlaybackRate(n),e.loop!==a&&this.player.setLoop&&this.player.setLoop(a)}getDuration(){return this.isReady?this.player.getDuration():null}getCurrentTime(){return this.isReady?this.player.getCurrentTime():null}getSecondsLoaded(){return this.isReady?this.player.getSecondsLoaded():null}seekTo(e,t,i){if(!this.isReady)return void(0!==e&&(this.seekOnPlay=e,setTimeout(()=>{this.seekOnPlay=null},5e3)));if(t?"fraction"===t:e>0&&e<1){const t=this.player.getDuration();return t?void this.player.seekTo(t*e,i):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,i)}render(){const e=this.props.activePlayer;return e?g.createElement(e,{...this.props,onMount:this.handlePlayerMount,onReady:this.handleReady,onPlay:this.handlePlay,onPause:this.handlePause,onEnded:this.handleEnded,onLoaded:this.handleLoaded,onError:this.handleError}):null}}Ld.displayName="Player",Ld.defaultProps=nd;const Rd="undefined"!=typeof window&&window.document,Id="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,kd=Rd||Id?f.Suspense:()=>null,Pd=["src","playing","loop","controls","volume","muted","playbackRate","width","height","style","progressInterval","playsInline","autoplay","preload","poster","className","wrapperClassName","wrapperStyle","allowNativeHls","lowLatencyMode","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","licenseKey","adFailsafeTimeoutMs","minSegmentsBeforePlay","onReady","onStart","onPlay","onPause","onBuffer","onBufferEnd","onEnded","onError","onDuration","onSeek","onProgress","onVolumeToggle","onFullscreenToggle","onControlClick"],wd=[],Dd=(e,t)=>{var i;return i=class extends f.Component{constructor(){super(...arguments),this.state={showPreview:!1},this.references={wrapper:e=>{this.wrapper=e},player:e=>{this.player=e}},this.getActivePlayer=i=>{if(!i)return null;for(const t of[...wd,...e])if(t.canPlay(i))return t;return t||null},this.getAttributes=e=>od(this.props,Pd),this.handleReady=()=>{var e,t;null===(t=(e=this.props).onReady)||void 0===t||t.call(e,this)},this.seekTo=(e,t,i)=>{if(!this.player)return null;this.player.seekTo(e,t,i)},this.getCurrentTime=()=>this.player?this.player.getCurrentTime():null,this.getSecondsLoaded=()=>this.player?this.player.getSecondsLoaded():null,this.getDuration=()=>this.player?this.player.getDuration():null,this.getInternalPlayer=(e="player")=>this.player?this.player.getInternalPlayer(e):null,this.renderActivePlayer=e=>{if(!e)return null;const t=this.getActivePlayer(e);return t?g.createElement(Ld,{...this.props,key:t.key,ref:this.references.player,activePlayer:t.lazyPlayer||t,onReady:this.handleReady}):null}}render(){const{src:e,style:t,width:i,height:s,fallback:r,wrapper:n}=this.props,a=this.getAttributes(e),o="string"==typeof n?this.references.wrapper:void 0;return g.createElement(n,{ref:o,style:{...t,width:i,height:s},...a},g.createElement(kd,{fallback:r},this.renderActivePlayer(e)))}},i.displayName="StormcloudPlayer",i.defaultProps={...nd,fallback:null,wrapper:"div"},i.addCustomPlayer=e=>{wd.push(e)},i.removeCustomPlayers=()=>{wd.length=0},i.canPlay=t=>{for(const i of[...wd,...e])if(i.canPlay(t))return!0;return!1},i.canEnablePIP=t=>{for(const i of[...wd,...e])if(i.canEnablePIP&&i.canEnablePIP(t))return!0;return!1},i},xd=Dd(bd,bd[bd.length-1]);e.IS_BROWSER=cd,e.IS_GLOBAL=ud,e.IS_IOS=fd,e.IS_SAFARI=gd,e.SUPPORTS_DASH=()=>{if(!cd)return!1;const e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=()=>{if(!cd)return!1;const e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=xd,e.StormcloudVideoPlayer=Fl,e.StormcloudVideoPlayerComponent=sd,e.canPlay=Ed,e.createHlsAdPlayer=wl,e.createImaController=Pl,e.createStormcloudPlayer=Dd,e.default=sd,e.detectBrowser=Ll,e.getBrowserConfigOverrides=kl,e.getBrowserID=Cl,e.getClientInfo=xl,e.getRecommendedAdPlayer=function(){return Ll().recommendedAdPlayer},e.initializePolyfills=Ol,e.isMediaStream=ld,e.lazy=ad,e.logBrowserInfo=Il,e.merge=dd,e.omit=od,e.parseQuery=e=>{const t={},i=e.split("?")[1]||"";if(!i)return t;const s=e=>{e.split("&").forEach(e=>{const[i,s]=e.split("=");if(i)try{t[decodeURIComponent(i)]=s?decodeURIComponent(s.replace(/\+/g," ")):""}catch(e){t[i]=s||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(i).forEach((e,i)=>{t[i]=e}),t}catch(e){s(i)}else s(i);return t},e.players=bd,e.randomString=()=>Math.random().toString(36).substr(2,9),e.sendHeartbeat=Ml,e.sendInitialTracking=_l,e.supportsFeature=function(e){switch(e){case"ima":return Rl();case"urlsearchparams":return"undefined"!=typeof URLSearchParams;case"textencoder":return"undefined"!=typeof TextEncoder;case"promises":return"undefined"!=typeof Promise;case"fetch":return"undefined"!=typeof fetch;case"crypto":return"undefined"!=typeof crypto&&void 0!==crypto.subtle;default:return!1}},e.supportsGoogleIMA=Rl,e.supportsModernJS=function(){try{return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set&&void 0!==Array.from&&void 0!==Object.assign&&void 0!==Array.prototype.forEach&&void 0!==String.prototype.includes}catch(e){return!1}},e.supportsWebKitPresentationMode=()=>{if("undefined"==typeof window)return!1;return"webkitSupportsPresentationMode"in document.createElement("video")},Object.defineProperty(e,"__esModule",{value:!0})});
|