@jaaq/jaaq-sdk-js 1.1.1 → 1.2.0-dev-ec79f7e-20260605
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/README.md +18 -7
- package/dist/embed/embed-collection.html +17 -4
- package/dist/embed/embed.html +15 -3
- package/dist/index.cjs +57 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +100 -24
- package/dist/index.mjs +56 -12
- package/dist/index.mjs.map +1 -1
- package/dist/jaaq-sdk.min.js +1 -1
- package/dist/jaaq-sdk.min.js.map +1 -1
- package/dist/ui/index.cjs +102 -17
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.d.ts +89 -10
- package/dist/ui/index.mjs +102 -17
- package/dist/ui/index.mjs.map +1 -1
- package/dist/ui/jaaq-ui-bundled.min.js +2 -2
- package/dist/ui/jaaq-ui-bundled.min.js.map +1 -1
- package/dist/ui/jaaq-ui.min.js +2 -2
- package/dist/ui/jaaq-ui.min.js.map +1 -1
- package/dist/ui/react/index.cjs +78 -18
- package/dist/ui/react/index.cjs.map +1 -1
- package/dist/ui/react/index.d.ts +84 -7
- package/dist/ui/react/index.mjs +78 -18
- package/dist/ui/react/index.mjs.map +1 -1
- package/dist/ui/react/jaaq-ui-react.min.js +2 -2
- package/dist/ui/react/jaaq-ui-react.min.js.map +1 -1
- package/dist/ui/vanilla/index.cjs +102 -17
- package/dist/ui/vanilla/index.cjs.map +1 -1
- package/dist/ui/vanilla/index.d.ts +89 -10
- package/dist/ui/vanilla/index.mjs +102 -17
- package/dist/ui/vanilla/index.mjs.map +1 -1
- package/dist/ui/vanilla/jaaq-vanilla-bundled.min.js +2 -2
- package/dist/ui/vanilla/jaaq-vanilla-bundled.min.js.map +1 -1
- package/dist/ui/vanilla/jaaq-vanilla.min.js +2 -2
- package/dist/ui/vanilla/jaaq-vanilla.min.js.map +1 -1
- package/dist/ui/webcomponents/index.cjs +74 -14
- package/dist/ui/webcomponents/index.cjs.map +1 -1
- package/dist/ui/webcomponents/index.d.ts +86 -9
- package/dist/ui/webcomponents/index.mjs +74 -14
- package/dist/ui/webcomponents/index.mjs.map +1 -1
- package/dist/ui/webcomponents/jaaq-webcomponents-bundled.min.js +2 -2
- package/dist/ui/webcomponents/jaaq-webcomponents-bundled.min.js.map +1 -1
- package/dist/ui/webcomponents/jaaq-webcomponents.min.js +2 -2
- package/dist/ui/webcomponents/jaaq-webcomponents.min.js.map +1 -1
- package/package.json +38 -35
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).JaaqWebComponents={})}(this,function(t){"use strict";const e=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},i=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=s},s=Number.MAX_SAFE_INTEGER||9007199254740991;let r=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),n=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),a=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var o="manifest",l="level",d="audioTrack",h="subtitleTrack",c="main",u="audio",f="subtitle";class g{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class m{constructor(t,e,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 g(t),this.fast_=new g(e),this.defaultTTFB_=s,this.ttfb_=new g(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new g(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new g(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new g(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const i=(t=Math.max(t,this.minDelayMs_))/1e3,s=8*e/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,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 p(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var s=i.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function v(){return v=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)({}).hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},v.apply(null,arguments)}function y(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,s)}return i}function E(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?y(Object(i),!0).forEach(function(e){p(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):y(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}class T{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${t}]:`;this.trace=S,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const S=function(){},b={trace:S,debug:S,log:S,warn:S,info:S,error:S};function A(){return v({},b)}function L(t,e,i){return e[t]?e[t].bind(e):function(t,e){const i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):S}(t,i)}const I=A();const R=I;function k(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function _(t,e){const i=Object.keys(t),s=Object.keys(e),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(t=>-1===s.indexOf(t))}function D(t,e=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(t);if(e){const t=i.indexOf("\0");return-1!==t?i.substring(0,t):i}return i.replace(/\0/g,"")}const i=t.length;let s,r,n,a="",o=0;for(;o<i;){if(s=t[o++],0===s&&e)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=t[o++],a+=String.fromCharCode((31&s)<<6|63&r);break;case 14:r=t[o++],n=t[o++],a+=String.fromCharCode((15&s)<<12|(63&r)<<6|63&n)}}return a}function w(t){let e="";for(let i=0;i<t.length;i++){let s=t[i].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function P(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function C(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var x,M={exports:{}};var O=(x||(x=1,function(t){var e,i,s,r,n;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var r=n.parseURL(t);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(e);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)):e;var o=n.parseURL(t);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(t){var i=e.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(s,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=n}(M)),M.exports);class F{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 N="audio",B="video",U="audiovideo";class ${constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const i=V(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let s;s=1===i.length?(null==e?void 0:e.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={[N]:null,[B]:null,[U]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new F),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=O.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[N]=null,t[B]=null,t[U]=null}}function G(t){return"initSegment"!==t.sn}class K extends ${constructor(t,e){super(e),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=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],i=this.byteRange[1];if(e(t)&&e(i))return i-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const i=this._decryptdata=e[t[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=e(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){e(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return G(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var i;const s=e[t];!s||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=s.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:n}}}class H extends ${constructor(t,e,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=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const n=t.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:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function V(t,e){const i=Object.getPrototypeOf(t);if(i){const t=Object.getOwnPropertyDescriptor(i,e);return t||V(i,e)}}const j=Math.pow(2,32)-1,q=[].push,Y={video:1,audio:2,id3:3,text:4};function W(t){return String.fromCharCode.apply(null,t)}function z(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function X(t,e){const i=Z(t,e);return i<0?4294967296+i:i}function Q(t,e){let i=X(t,e);return i*=Math.pow(2,32),i+=X(t,e+4),i}function Z(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function J(t,e){const i=[];if(!e.length)return i;const s=t.byteLength;for(let r=0;r<s;){const n=X(t,r),a=n>1?r+n:s;if(W(t.subarray(r+4,r+8))===e[0])if(1===e.length)i.push(t.subarray(r+8,a));else{const s=J(t.subarray(r+8,a),e.slice(1));s.length&&q.apply(i,s)}r=a}return i}function tt(t){const e=[],i=t[0];let s=8;const r=X(t,s);s+=4;let n=0,a=0;0===i?(n=X(t,s),a=X(t,s+4),s+=8):(n=Q(t,s),a=Q(t,s+8),s+=16),s+=2;let o=t.length+a;const l=z(t,s);s+=2;for(let i=0;i<l;i++){let i=s;const n=X(t,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return R.warn("SIDX has hierarchical references (not supported)"),null;const l=X(t,i);i+=4,e.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:e}}function et(t){const e=[],i=J(t,["moov","trak"]);for(let t=0;t<i.length;t++){const s=i[t],r=J(s,["tkhd"])[0];if(r){let t=r[0];const i=X(r,0===t?12:20),n=J(s,["mdia","mdhd"])[0];if(n){t=n[0];const r=X(n,0===t?12:20),a=J(s,["mdia","hdlr"])[0];if(a){const t=W(a.subarray(8,12)),n={soun:N,vide:B}[t],o=it(J(s,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:r,type:n,stsd:o},e[n]=E({timescale:r,id:i},o)):e[i]={timescale:r,type:t,stsd:o}}}}}return J(t,["moov","mvex","trex"]).forEach(t=>{const i=X(t,4),s=e[i];s&&(s.default={duration:X(t,12),flags:X(t,20)})}),e}function it(t){const e=t.subarray(8),i=e.subarray(86),s=W(e.subarray(4,8));let r,n=s;const a="enca"===s||"encv"===s;if(a){const t=J(e,[s])[0];J(t.subarray("enca"===s?28:78),["sinf"]).forEach(t=>{const e=J(t,["schm"])[0];if(e){const i=W(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=J(t,["frma"])[0];e&&(n=W(e))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=J(i,["avcC"])[0];t&&t.length>3&&(n+="."+nt(t[1])+nt(t[2])+nt(t[3]),r=st("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=J(e,[s])[0],i=J(t.subarray(28),["esds"])[0];if(i&&i.length>7){let t=4;if(3!==i[t++])break;t=rt(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=rt(i,t);const s=i[t++];if(64!==s)break;if(n+="."+nt(s),t+=12,5!==i[t++])break;t=rt(i,t);const r=i[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=J(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],s=31&e,r=X(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+i+s,n+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}n+=d}r=st("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=st(n,i)||n;break;case"vp09":{const t=J(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],s=t[6]>>4&15;n+="."+at(e)+"."+at(i)+"."+at(s)}break}case"av01":{const t=J(i,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,s=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,h=(16&t[2])>>4,c=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+at(s)+a+"."+at(d)+"."+h+"."+c+u+f+"."+at(g)+"."+at(m)+"."+at(p)+"."+v,r=st("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:r}}function st(t,e){const i=J(e,["dvvC"]),s=i.length?i[0]:J(e,["dvcC"])[0];if(s){const e=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return t+"."+at(e)+"."+at(i)}}function rt(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function nt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function at(t){return(t<10?"0":"")+t}function ot(t,e){J(t,["moov","trak"]).forEach(t=>{const i=J(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let r=J(s,["enca"]);const n=r.length>0;n||(r=J(s,["encv"])),r.forEach(t=>{J(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const i=lt(t);i&&e(i,n)})})})}function lt(t){const e=J(t,["schm"])[0];if(e){const i=W(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=J(t,["schi","tenc"])[0];if(e)return e}}}function dt(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function ht(t,e){const i=[],s=e.samples,r=e.timescale,n=e.id;let a=!1;return J(s,["moof"]).map(o=>{const l=o.byteOffset-8;J(o,["traf"]).map(o=>{const d=J(o,["tfdt"]).map(t=>{const e=t[0];let i=X(t,4);return 1===e&&(i*=Math.pow(2,32),i+=X(t,8)),i/r})[0];return void 0!==d&&(t=d),J(o,["tfhd"]).map(d=>{const h=X(d,4),c=16777215&X(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=X(d,p),p+=4),f&&(g=X(d,p),p+=4),m&&(p+=4),"video"===e.type&&(a=ct(e.codec)),J(o,["trun"]).map(n=>{const o=n[0],d=16777215&X(n,0),h=!!(1&d);let c=0;const f=!!(4&d),m=!!(256&d);let p=0;const v=!!(512&d);let y=0;const E=!!(1024&d),T=!!(2048&d);let S=0;const b=X(n,4);let A=8;h&&(c=X(n,A),A+=4),f&&(A+=4);let L=c+l;for(let l=0;l<b;l++){if(m?(p=X(n,A),A+=4):p=u,v?(y=X(n,A),A+=4):y=g,E&&(A+=4),T&&(S=0===o?X(n,A):Z(n,A),A+=4),e.type===B){let e=0;for(;e<y;){const n=X(s,L);if(L+=4,ut(a,s[L])){ft(s.subarray(L,L+n),a?2:1,t+S/r,i)}L+=n,e+=n+4}}t+=p/r}}))})})}),i}function ct(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function ut(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function ft(t,e,i,s){const r=gt(t);let n=0;n+=e;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 t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){R.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=z(r,e);if(e+=2,49===t){const t=X(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=r[e++]}s.push({type:t,payloadType:a,pts:i,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const s=r[e++].toString(16);t.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=r[e++];s.push({payloadType:a,pts:i,uuid:t.join(""),userData:D(l),userDataBytes:l})}}}function gt(t){const e=t.byteLength,i=[];let s=1;for(;s<e-2;)0===t[s]&&0===t[s+1]&&3===t[s+2]?(i.push(s+2),s+=2):s++;if(0===i.length)return t;const r=e-i.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===i[0]&&(a++,i.shift()),n[s]=t[a];return n}function mt(t,e,i){if(16!==t.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(t,...e){const i=e.length;let s=8,r=i;for(;r--;)s+=e[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(t,4),r=0,s=8;r<i;r++)n.set(e[r],s),s+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,i)}function pt(t){const e=t.getUint32(0),i=t.byteOffset,s=t.byteLength;if(s<e)return{offset:i,size:s};if(1886614376!==t.getUint32(4))return{offset:i,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:e};const n=t.buffer,a=w(new Uint8Array(n,i+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=t.getUint32(28);if(!r||s<32+16*r)return{offset:i,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(n,i+32+16*t,16));d=32+16*r}if(!d)return{offset:i,size:e};const h=t.getUint32(d);return e-32<h?{offset:i,size:e}:(l=new Uint8Array(n,i+d+4,h),{version:r,systemId:a,kids:o,data:l,offset:i,size:e})}const vt=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),yt={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 Et(t,e){const i=yt[e];return!!i&&!!i[t.slice(0,4)]}function Tt(t,e,i=!0){return!t.split(",").some(t=>!St(t,e,i))}function St(t,e,i=!0){var s;const r=k(i);return null!=(s=null==r?void 0:r.isTypeSupported(bt(t,e)))&&s}function bt(t,e){return`${e}/mp4;codecs=${t}`}function At(t){if(t){const e=t.substring(0,4);return yt.video[e]}return 2}function Lt(t){const e=vt();return t.split(",").reduce((t,i)=>{const s=e&&ct(i)?9:yt.video[i];return s?(2*s+t)/(t?3:2):(yt.audio[i]+t)/(t?2:1)},0)}const It={};const Rt=/flac|opus|mp4a\.40\.34/i;function kt(t,e=!0){return t.replace(Rt,t=>function(t,e=!0){if(It[t])return It[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<i.length;r++){var s;if(St(i[r],"audio",e))return It[t]=i[r],i[r];if("mp3"===i[r]&&null!=(s=k(e))&&s.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function _t(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Dt(t,"audio")||Dt(t,"video")))return t;if(e){const i=e.split(",");if(i.length>1){if(t)for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e];return i[0]}}return e||t}function Dt(t,e){return Et(t,e)&&St(t,e)}function wt(t){if(t.startsWith("av01.")){const e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}function Pt(t){const e=k(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ct(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const xt={supported:!1,smooth:!1,powerEfficient:!1},Mt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Ot(t,e){return{supported:!1,configurations:e,decodingInfoResults:[xt],error:t}}function Ft(t,i,s,r,n,a){const o=t.videoCodec,l=t.audioCodec?t.audioGroups:null,d=null==a?void 0:a.audioCodec,h=null==a?void 0:a.channels,c=h?parseInt(h):d?1/0:2;let u=null;if(null!=l&&l.length)try{u=1===l.length&&l[0]?i.groups[l[0]].channels:l.reduce((t,e)=>{if(e){const s=i.groups[e];if(!s)throw new Error(`Audio track group ${e} not found`);Object.keys(s.channels).forEach(e=>{t[e]=(t[e]||0)+s.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==o&&(o.split(",").some(t=>ct(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(n,8e6))||!!u&&e(c)&&Object.keys(u).some(t=>parseInt(t)>c)}function Nt(t,e,i,s={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!i)return Promise.resolve(Mt);const n=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),s=Ut(t),r=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map(t=>{const e={contentType:bt(wt(t),"video"),width:r,height:n,bitrate:s,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,i){var s;const r=null==(s=t.audioCodec)?void 0:s.split(","),n=Ut(t);if(r&&t.audioGroups)return t.audioGroups.reduce((t,s)=>{var a;const o=s?null==(a=e.groups[s])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===s){const s=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:bt(e,"audio"),bitrate:i?Bt(e,n):n};s&&(r.channels=""+s),t.push(r)})}return t},t):t},[]);return[]}(t,e,o>0),d=l.length;for(let t=o||1*d||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),d){e.audio=l[t%d];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}n.push(e)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>ct(t))&&vt())return Promise.resolve(Ot(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:i,video:s}=t;if(s){e+=`${Ct(s.contentType)}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){e+=`${s?"_":""}${Ct(i.contentType)}_c${i.channels}`}return e}(t);return s[e]||(s[e]=i.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function Bt(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function Ut(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}const $t=["NONE","TYPE-0","TYPE-1",null];const Gt=["SDR","PQ","HLG"];var Kt="",Ht="YES",Vt="v2";function jt(t){const{canSkipUntil:e,canSkipDateRanges:i,age:s}=t;return e&&s<e/2?i?Vt:Ht:Kt}class qt{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class Yt{constructor(t){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=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.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(t){return Wt(this._audioGroups,t)}hasSubtitleGroup(t){return Wt(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function Wt(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function zt(t,e){let i=!1,s=[];if(t&&(i="SDR"!==t,s=[t]),e){s=e.allowedVideoRanges||Gt.slice(0);const t="SDR"!==s.join("")&&!e.videoCodec;i=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}const Xt=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(i,s)=>{if(t&&(s=t(i,s)),"object"==typeof s&&null!==s){if(e.has(s))return;e.add(s)}return s}})(e));function Qt(t,e){R.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Zt(t){return t.reduce((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const s=e.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Jt(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}=t;return{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function te(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let s=0;s<e.length;s++){if(ee(t,e[s],i))return s}return-1}function ee(t,e,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===s||e.groupId===s)&&(void 0===r||e.name===r)&&(void 0===n||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===n||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const i=t.split(","),s=e.split(",");return i.length===s.length&&!i.some(t=>-1===s.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function ie(t,e){const{audioCodec:i,channels:s}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(e.channels||"2"))}function se(t,e,i){for(let s=e;s>-1;s--)if(i(t[s]))return s;for(let s=e+1;s<t.length;s++)if(i(t[s]))return s;return-1}function re(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}const ne=function(t,e){let i=0,s=t.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=t[r];const a=e(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function ae(t,e,i=0,s=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const s=t.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===oe(i,s,n)||function(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),i);return t.start<=s}return!1}(n,t,Math.min(r,s))))return n;const a=ne(e,oe.bind(null,i,s));return!a||a===t&&n?n:a}function oe(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const s=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=t?1:i.start-s>t&&i.start?-1:0}function le(t,e,i){const s=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>t}function de(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let s=t.fragments;const{fragmentHint:r}=t;let n;return r&&(s=s.concat(r)),ne(s,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=i?1:t.start>i?-1:0)),n||null}return null}function he(t){switch(t.details){case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_TIMEOUT:case n.LEVEL_LOAD_TIMEOUT:case n.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ce(t){return t.details.startsWith("key")}function ue(t){return ce(t)&&!!t.frag&&!t.frag.decryptdata}function fe(t,e){const i=he(e);return t.default[(i?"timeout":"error")+"Retry"]}function ge(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function me(t){return E(E({},t),{errorRetry:null,timeoutRetry:null})}function pe(t,e,i,s){if(!t)return!1;const r=null==s?void 0:s.code,n=e<t.maxNumRetry&&(function(t){return ve(t)||!!t&&(t<400||t>499)}(r)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,s,n):n}function ve(t){return 0===t&&!1===navigator.onLine}var ye=0,Ee=2,Te=3,Se=5,be=0,Ae=1,Le=2,Ie=4;function Re(t){const e={action:ye,flags:be};return t&&(e.resolved=!0),e}var ke="NOT_LOADED",_e="APPENDING",De="PARTIAL",we="OK";class Pe{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const s=i[e];if(!s)break;if(s.start<=t&&t<=s.end&&s.loaded)return s}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,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)===e&&(!i||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,s,r){this.timeRanges&&(this.timeRanges[t]=e);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[t];o&&(0!==o.time.length?o.time.some(t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(a.body),i}):this.removeFragment(a.body))})}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const i=t.frag,s=xe(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const n=!i.relurl;Object.keys(e).forEach(s=>{const a=i.elementaryStreams[s];if(!a)return;const o=e[s],l=n||!0===a.partial;r.range[s]=this.getBufferedTimes(i,t.part,l,o)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),Ce(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Me(i,e=>e.fragment.sn>=t))}fragBuffered(t,e){const i=xe(t);let s=this.fragments[i];!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,t))}getBufferedTimes(t,e,i,s){const r={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<s.length;t++){const e=s.start(t)-this.bufferPadding,i=s.end(t)+this.bufferPadding;if(l>=e&&o<=i){r.time.push({startPTS:Math.max(n,s.start(t)),endPTS:Math.min(a,s.end(t))});break}if(n<i&&a>e){const e=Math.max(n,s.start(t)),i=Math.min(a,s.end(t));i>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return r}getPartialFragment(t){let e,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&Ce(d)&&(i=d.body.start-a,s=d.body.end+a,t>=i&&t<=s&&(e=Math.min(t-i,s-t),n<=e&&(r=d.body,n=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Ce(e))}getState(t){const e=xe(t),i=this.fragments[e];return i?i.buffered?Ce(i)?De:we:_e:ke}isTimeBuffered(t,e,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,t>=s&&e<=r)return!0;if(e<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const i=e.frag,s=e.part?null:e,r=xe(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:r,type:n}=e;if("initSegment"===i.sn)return;const a=i.type;if(s){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(s)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,s)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=xe(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let s=i.length;s--;){const r=e[i[s]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,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<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=xe(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=Me(i,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function Ce(t){var e,i,s;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(s=t.range.audiovideo)&&s.partial)}function xe(t){return`${t.type}_${t.level}_${t.sn}`}function Me(t,e){return t.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Oe=0,Fe=1;class Ne{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case Oe:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case Fe:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Be{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_(t){const e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=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,t[f]=i,e[i]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[i]^16843008*i;s[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,d[i]=v<<16|v>>>16,h[i]=v<<8|v>>>24,c[i]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s<e.length&&i;)i=e[s]===this.key[s],s++;if(i)return;this.key=e;const r=this.keySize=e.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 v,y;for(a=0;a<n;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^m[h[y>>>8&255]]^p[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,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(t),v=new Int32Array(p.length);let y,E,T,S,b,A,L,I,R,k,_,D,w,P;const C=this.networkToHostOrderSwap;for(;e<p.length;){for(R=C(p[e]),k=C(p[e+1]),_=C(p[e+2]),D=C(p[e+3]),b=R^r[0],A=D^r[1],L=_^r[2],I=k^r[3],w=4,P=1;P<s;P++)y=o[b>>>24]^l[A>>16&255]^d[L>>8&255]^h[255&I]^r[w],E=o[A>>>24]^l[L>>16&255]^d[I>>8&255]^h[255&b]^r[w+1],T=o[L>>>24]^l[I>>16&255]^d[b>>8&255]^h[255&A]^r[w+2],S=o[I>>>24]^l[b>>16&255]^d[A>>8&255]^h[255&L]^r[w+3],b=y,A=E,L=T,I=S,w+=4;y=n[b>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&I]^r[w],E=n[A>>>24]<<24^n[L>>16&255]<<16^n[I>>8&255]<<8^n[255&b]^r[w+1],T=n[L>>>24]<<24^n[I>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^r[w+2],S=n[I>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^r[w+3],v[e]=C(y^u),v[e+1]=C(S^f),v[e+2]=C(T^g),v[e+3]=C(E^m),u=R,f=k,g=_,m=D,e+=4}return v.buffer}}class Ue{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=function(t){switch(t){case Oe:return"AES-CBC";case Fe:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class $e{constructor(t,{removePKCS7Padding:e=!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=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}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:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,s){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==Oe||16!==e.byteLength)return R.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=dt(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Be),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,i,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,s));this.key=e,this.fastAesKey=new Ue(this.subtle,e,s)}return this.fastAesKey.expandKey().then(e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Ne(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,e)}).catch(r=>(R.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(R.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Ge=Math.pow(2,17);class Ke{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const i=t.url;if(!i)return Promise.reject(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const s=this.config,a=s.fLoader,o=s.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void d(Ve(t));t.gap=!1}const h=this.loader=a?new a(s):new o(s),c=He(t);t.loader=h;const u=me(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Ge};t.stats=h.stats;const g={onSuccess:(e,i,s,r)=>{this.resetLoader(t,h);let n=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),l({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,s,a,o)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:E({url:i,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:a,stats:o}))},onAbort:(e,i,s)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:(e,i,s)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:s,stats:e}))}};e&&(g.onProgress=(i,s,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})),h.load(c,f,g)})}loadPart(t,e,i){this.abort();const s=this.config,a=s.fLoader,o=s.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void d(Ve(t,e));const h=this.loader=a?new a(s):new o(s),c=He(t,e);t.loader=h;const u=me(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ge};e.stats=h.stats,h.load(c,f,{onSuccess:(s,r,n,a)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:s.data,networkDetails:a};i(o),l(o)},onError:(i,s,a,o)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:E({url:c.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:a,stats:o}))},onAbort:(i,s,a)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:a,stats:i}))},onTimeout:(i,s,a)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:a,stats:i}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(t.duration/e.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(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function He(t,i=null){const s=i||t,r={frag:t,part:i,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=s.byteRangeStartOffset,a=s.byteRangeEndOffset;if(e(n)&&e(a)){var o;let e=n,i=a;if("initSegment"===t.sn&&("AES-128"===(l=null==(o=t.decryptdata)?void 0:o.method)||"AES-256"===l)){const t=a-n;t%16&&(i=a+(16-t%16)),0!==n&&(r.resetIV=!0,e=n-16)}r.rangeStart=e,r.rangeEnd=i}var l;return r}function Ve(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:r.MEDIA_ERROR,details:n.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(s.part=e),(e||t).stats.aborted=!0,new je(s)}class je extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class qe extends T{constructor(t,e){super(t,e),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(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!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 Ye{constructor(t,e,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=t,this.sn=e,this.id=i,this.size=s,this.part=r,this.partial=n}}const We={length:0,start:()=>0,end:()=>0};class ze{static isBuffered(t,e){if(t){const i=ze.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=ze.getBuffered(t);return ze.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const s=ze.bufferedRanges(t);if(s.length)return ze.bufferedInfo(s,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let s=-1,r=[];if(i)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(s=n);const a=r.length;if(a){const e=r[a-1].end;t[n].start-e<i?t[n].end>e&&(r[a-1].end=t[n].end):r.push(t[n])}else r.push(t[n])}else r=t;let n,a=0,o=e,l=e;for(let t=0;t<r.length;t++){const d=r[t].start,h=r[t].end;if(-1===s&&e>=d&&e<=h&&(s=t),e+i>=d&&e<h)o=d,l=h,a=l-e;else if(e+i<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||We}catch(t){return R.log("failed to get media.buffered",t),We}}}const Xe=/\{\$([a-zA-Z0-9-_]+)\}/g;function Qe(t){return Xe.test(t)}function Ze(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(Xe,e=>{const s=e.substring(2,e.length-1),r=null==i?void 0:i[s];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),e):r})}return e}function Je(t,e,i){let s,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){s=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=t.get(s)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else s=e.NAME,r=e.VALUE;s in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function ti(t,e,i){const s=e.IMPORT;if(i&&s in i){let e=t.variableList;e||(t.variableList=e={}),e[s]=i[s]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const ei=/^(\d+)x(\d+)$/,ii=/(.+?)=(".*?"|.*?)(?:,|$)/g;class si{constructor(t,e){"string"==typeof t&&(t=si.parseAttrList(t,e)),v(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=ei.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const s={};for(ii.lastIndex=0;null!==(i=ii.exec(t));){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(e&&(a||o))n=Ze(e,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":R.warn(`${t}: attribute ${r} is missing quotes`)}s[r]=n}return s}}function ri(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function ni(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class ai{constructor(t,i,s=0){var r;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==i?void 0:i.tagAnchor)||null,this.tagOrder=null!=(r=null==i?void 0:i.tagOrder)?r:s,i){const e=i.attr;for(const i in e)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==e[i]){R.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=i;break}t=v(new si({}),e,t)}if(this.attr=t,i?(this._startDate=i._startDate,this._cue=i._cue,this._endDate=i._endDate,this._dateAtEnd=i._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==i?void 0:i.endDate)||new Date(this.attr["END-DATE"]);e(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(R.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(e(t))return t}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&&e(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 oi{constructor(t){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=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&e(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.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 t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function li(t,e){return t.length===e.length&&!t.some((t,i)=>t!==e[i])}function di(t,e){return!t&&!e||!(!t||!e)&&li(t,e)}function hi(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function ci(t){switch(t){case"AES-128":case"AES-256":return Oe;case"AES-256-CTR":return Fe;default:throw new Error(`invalid full segment method ${t}`)}}function ui(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function fi(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function gi(t){const e=function(t,e,i){const s=t[e];t[e]=t[i],t[i]=s};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function mi(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),s=t[t.length-1].split(",");if(2===s.length){const e="base64"===s[0],r=s[1];e?(t.splice(-1,1),i=ui(r)):i=function(t){const e=fi(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(r)}}return i}const pi="undefined"!=typeof self?self:void 0;var vi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},yi="org.w3.clearkey",Ei="com.apple.streamingkeydelivery",Ti="com.microsoft.playready",Si="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function bi(t){switch(t){case Ei:return vi.FAIRPLAY;case Ti:return vi.PLAYREADY;case Si:return vi.WIDEVINE;case yi:return vi.CLEARKEY}}function Ai(t){switch(t){case vi.FAIRPLAY:return Ei;case vi.PLAYREADY:return Ti;case vi.WIDEVINE:return Si;case vi.CLEARKEY:return yi}}function Li(t){const{drmSystems:e,widevineLicenseUrl:i}=t,s=e?[vi.FAIRPLAY,vi.WIDEVINE,vi.PLAYREADY,vi.CLEARKEY].filter(t=>!!e[t]):[];return!s[vi.WIDEVINE]&&i&&s.push(vi.WIDEVINE),s}const Ii=null!=pi&&null!=(Ri=pi.navigator)&&Ri.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Ri;function ki(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),i=String.fromCharCode.apply(null,Array.from(e)),s=i.substring(i.indexOf("<"),i.length),r=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const t=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(t){const e=ui(t).subarray(0,16);return gi(e),e}}return null}let _i={};class Di{static clearKeyUriToKeyIdMap(){_i={}}static setKeyIdForUri(t,e){_i[t]=e}static addKeyIdForUri(t){const e=Object.keys(_i).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),_i[t]=i,i}constructor(t,e,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=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!hi(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(P(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&li(t.keyFormatVersions,this.keyFormatVersions)&&di(t.iv,this.iv)&&di(t.keyId,this.keyId)}isSupported(){if(this.method){if(hi(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Ei:case Si:case Ti:case yi:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(hi(this.method)){let e=this.iv;e||("number"!=typeof t&&(R.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),e=function(t){const e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t));return new Di(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){const t=_i[this.uri];if(t&&!li(this.keyId,t)&&Di.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=mi(this.uri);if(i)switch(this.keyFormat){case Si:if(this.pssh=i,!this.keyId){const t=function(t){const e=[];if(t instanceof ArrayBuffer){const i=t.byteLength;let s=0;for(;s+32<i;){const i=pt(new DataView(t,s));e.push(i),s+=i.size}}return e}(i.buffer);if(t.length){var s;const e=t[0];this.keyId=null!=(s=e.kids)&&s.length?e.kids[0]:null}}this.keyId||(this.keyId=wi(e));break;case Ti:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mt(t,0,i),this.keyId=ki(i);break}default:{let t=i.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t;t=function(t){const e=null==t?void 0:t[Si];if(e)return e.keyId;return null}(e),t||(t=wi(e),t||(t=_i[this.uri])),t&&(this.keyId=t,Di.setKeyIdForUri(this.uri,t))}return this}}function wi(t){const e=null==t?void 0:t[Ti];if(e){const t=mi(e.uri);if(t)return ki(t)}return null}const Pi=/#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,Ci=/#EXT-X-MEDIA:(.*)/g,xi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Mi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Oi=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 Fi{static findGroup(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(s.id===e)return s}}static resolve(t,e){return O.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return xi.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Qe(t)},s=[];if(Pi.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=Pi.exec(t));)if(r[1]){var n;const t=new si(r[1],i),a=Ze(i,r[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Fi.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Gi(t.CODECS,o);const d=t["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},Gi(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||s.push(o),i.levels.push(o)}else if(r[3]){const t=r[3],s=r[4];switch(t){case"SESSION-DATA":{const t=new si(s,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Ui(s,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):R.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${s}"`);break}case"DEFINE":Je(i,new si(s,i),e);break;case"CONTENT-STEERING":{const t=new si(s,i);i.contentSteering={uri:Fi.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=$i(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(t,e,i){let s;const r={},n=i.levels,a={AUDIO:n.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:n.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(Ci.lastIndex=0;null!==(s=Ci.exec(t));){const t=new si(s[1],i),n=t.TYPE;if(n){const i=a[n],s=r[n]||[];r[n]=s;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],h=t.CHANNELS,c=t.CHARACTERISTICS,u=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Fi.resolve(t.URI,e):""};if(d&&(f.assocLang=d),h&&(f.channels=h),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=i&&i.length){const t=Fi.findGroup(i,f.groupId)||i[0];Ki(f,t,"audioCodec"),Ki(f,t,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(t,i,s,r,n,a){var o;const l={url:i},d=new oi(i),h=d.fragments,c=[];let u,f,g,m,p=null,y=0,E=0,T=0,S=0,b=0,A=null,L=new K(r,l),I=-1,k=!1,_=null;if(Mi.lastIndex=0,d.m3u8=t,d.hasVariableRefs=Qe(t),"#EXTM3U"!==(null==(o=Mi.exec(t))?void 0:o[0]))return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;null!==(u=Mi.exec(t));){k&&(k=!1,L=new K(r,l),L.playlistOffset=T,L.setStart(T),L.sn=y,L.cc=S,b&&(L.bitrate=b),L.level=s,p&&(L.initSegment=p,p.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),_&&(L.setByteRange(_),_=null)));const t=u[1];if(t){L.duration=parseFloat(t);const e=(" "+u[2]).slice(1);L.title=e||null,L.tagList.push(e?["INF",t,e]:["INF",t])}else if(u[3]){if(e(L.duration)){L.playlistOffset=T,L.setStart(T),g&&ji(L,g,d),L.sn=y,L.level=s,L.cc=S,h.push(L);const t=(" "+u[3]).slice(1);L.relurl=Ze(d,t),Hi(L,A,c),A=L,T+=L.duration,y++,E=0,k=!0}}else{if(u=u[0].match(Oi),!u){R.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<u.length&&void 0===u[f];f++);const t=(" "+u[f]).slice(1),n=(" "+u[f+1]).slice(1),o=u[f+2]?(" "+u[f+2]).slice(1):null;switch(t){case"BYTERANGE":A?L.setByteRange(n,A):L.setByteRange(n);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=n,L.tagList.push(["PROGRAM-DATE-TIME",n]),-1===I&&(I=h.length);break;case"PLAYLIST-TYPE":d.type&&qi(d,t,u),d.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":0!==d.startSN?qi(d,t,u):h.length>0&&Yi(d,t,u),y=d.startSN=parseInt(n);break;case"SKIP":{d.skippedSegments&&qi(d,t,u);const i=new si(n,d),s=i.decimalInteger("SKIPPED-SEGMENTS");if(e(s)){d.skippedSegments+=s;for(let t=s;t--;)h.push(null);y+=s}const r=i.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(r.split("\t")));break}case"TARGETDURATION":0!==d.targetduration&&qi(d,t,u),d.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==d.version&&qi(d,t,u),d.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||qi(d,t,u),d.live=!1;break;case"#":(n||o)&&L.tagList.push(o?[n,o]:[n]);break;case"DISCONTINUITY":S++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([t]);break;case"BITRATE":L.tagList.push([t,n]),b=1e3*parseInt(n),e(b)?L.bitrate=b:b=0;break;case"DATERANGE":{const t=new si(n,d),e=new ai(t,d.dateRanges[t.ID],d.dateRangeTagCount);d.dateRangeTagCount++,e.isValid||d.skippedSegments?d.dateRanges[e.id]=e:R.warn(`Ignoring invalid DATERANGE tag: "${n}"`),L.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new si(n,d);"IMPORT"in t?ti(d,t,a):Je(d,t,i)}break;case"DISCONTINUITY-SEQUENCE":0!==d.startCC?qi(d,t,u):h.length>0&&Yi(d,t,u),d.startCC=S=parseInt(n);break;case"KEY":{const t=Ui(n,i,d);if(t.isSupported()){if("NONE"===t.method){g=void 0;break}g||(g={});const e=g[t.keyFormat];null!=e&&e.matches(t)||(e&&(g=v({},g)),g[t.keyFormat]=t)}else R.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${n}"`);break}case"START":d.startTimeOffset=$i(n);break;case"MAP":{const t=new si(n,d);if(L.duration){const e=new K(r,l);Vi(e,t,s,g),p=e,L.initSegment=p,p.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime)}else{const e=L.byteRangeEndOffset;if(e){const t=L.byteRangeStartOffset;_=`${e-t}@${t}`}else _=null;Vi(L,t,s,g),p=L,k=!0}p.cc=S;break}case"SERVER-CONTROL":m&&qi(d,t,u),m=new si(n),d.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),d.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{d.partTarget&&qi(d,t,u);const e=new si(n);d.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=d.partList;t||(t=d.partList=[]);const e=E>0?t[t.length-1]:void 0,i=E++,s=new si(n,d),r=new H(s,L,l,i,e);t.push(r),L.duration+=r.duration;break}case"PRELOAD-HINT":{const t=new si(n,d);d.preloadHint=t;break}case"RENDITION-REPORT":{const t=new si(n,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(t);break}default:R.warn(`line parsed but not handled: ${u}`)}}}A&&!A.relurl?(h.pop(),T-=A.duration,d.partList&&(d.fragmentHint=A)):d.partList&&(Hi(L,A,c),L.cc=S,d.fragmentHint=L,g&&ji(L,g,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const D=h.length,w=h[0],P=h[D-1];if(T+=d.skippedSegments*d.targetduration,T>0&&D&&P){d.averagetargetduration=T/D;const t=P.sn;d.endSN="initSegment"!==t?t:0,d.live||(P.endList=!0),I>0&&(!function(t,e){let i=t[e];for(let s=e;s--;){const e=t[s];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(h,I),w&&c.unshift(w))}return d.fragmentHint&&(T+=d.fragmentHint.duration),d.totalduration=T,c.length&&d.dateRangeTagCount&&w&&Ni(c,d),d.endCC=S,d}}function Ni(t,e){let i=t.length;if(!i){if(!e.hasProgramDateTime)return;{const s=e.fragments[e.fragments.length-1];t.push(s),i++}}const s=t[i-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let s=i;s--;){var a;if((null==(a=t[s])?void 0:a.sn)<e.startSN)break;const i=Bi(e,d,t,s,r);if(-1!==i){l.tagAnchor=e.fragments[i].ref;break}}}}function Bi(t,e,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(e>=o||0===s){var a;if(e<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||r)-n.start)){const r=i[s].sn-t.startSN;if(r<0)return-1;const n=t.fragments;if(n.length>i.length){for(let a=(i[s+1]||n[n.length-1]).sn-t.startSN;a>r;a--){const t=n[a].programDateTime;if(e>=t&&e<t+1e3*n[a].duration)return a}}return r}}}return-1}function Ui(t,e,i){var s,r;const n=new si(t,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&&R.error(`Invalid IV: ${n.IV}`);const c=o?Fi.resolve(o,e):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Di(a,c,h,u,l,n.KEYID)}function $i(t){const i=new si(t).decimalFloatingPoint("TIME-OFFSET");return e(i)?i:null}function Gi(t,e){let i=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const s=i.filter(e=>Et(e,t));s.length&&(e[`${t}Codec`]=s.map(t=>t.split("/")[0]).join(","),i=i.filter(t=>-1===s.indexOf(t)))}),e.unknownCodecs=i}function Ki(t,e,i){const s=e[i];s&&(t[i]=s)}function Hi(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Vi(t,e,i,s){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",s&&(t.levelkeys=s),t.initSegment=null}function ji(t,e,i){t.levelkeys=e;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||s.push(t)}function qi(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function Yi(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function Wi(t,i){const s=i.startPTS;if(e(s)){let e,r=0;i.sn>t.sn?(r=s-t.start,e=t):(r=t.start-s,e=i),e.duration!==r&&e.setDuration(r)}else if(i.sn>t.sn){t.cc===i.cc&&t.minEndPTS?i.setStart(t.start+(t.minEndPTS-t.start)):i.setStart(t.start+t.duration)}else i.setStart(Math.max(t.start-i.duration,0))}function zi(t,i,s,r,n,a,o){r-s<=0&&(o.warn("Fragment should have a positive duration",i),r=s+i.duration,a=n+i.duration);let l=s,d=r;const h=i.startPTS,c=i.endPTS;if(e(h)){const u=Math.abs(h-s);t&&u>t.totalduration?o.warn(`media timestamps and playlist times differ by ${u}s for level ${i.level} ${t.url}`):e(i.deltaPTS)?i.deltaPTS=Math.max(u,i.deltaPTS):i.deltaPTS=u,l=Math.max(s,h),s=Math.min(s,h),n=void 0!==i.startDTS?Math.min(n,i.startDTS):n,d=Math.min(r,c),r=Math.max(r,c),a=void 0!==i.endDTS?Math.max(a,i.endDTS):a}const u=s-i.start;0!==i.start&&i.setStart(s),i.setDuration(r-i.start),i.startPTS=s,i.maxStartPTS=l,i.startDTS=n,i.endPTS=r,i.minEndPTS=d,i.endDTS=a;const f=i.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let g;const m=f-t.startSN,p=t.fragments;for(p[m]=i,g=m;g>0;g--)Wi(p[g],p[g-1]);for(g=m;g<p.length-1;g++)Wi(p[g],p[g+1]);return t.fragmentHint&&Wi(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function Xi(t,i,s){if(t===i)return;let r=null;const n=t.fragments;for(let t=n.length-1;t>=0;t--){const e=n[t].initSegment;if(e){r=e;break}}let a;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){const s=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(s?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let d=r;d<=n;d++){const r=l[a+d];let n=o[d];if(s&&!n&&r&&(n=e.fragments[d]=r),r&&n){i(r,n,d,o);const s=r.relurl,a=n.relurl;if(s&&ns(s,a))return void(e.playlistParsingError=Qi(`media sequence mismatch ${n.sn}:`,t,e,r,n));if(r.cc!==n.cc)return void(e.playlistParsingError=Qi(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,t,e,r,n))}}}(t,i,(t,s,n,o)=>{if((!i.startCC||i.skippedSegments)&&s.cc!==t.cc){const e=t.cc-s.cc;for(let t=n;t<o.length;t++)o[t].cc+=e;i.endCC=o[o.length-1].cc}e(t.startPTS)&&e(t.endPTS)&&(s.setStart(s.startPTS=t.startPTS),s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.setDuration(t.endPTS-t.startPTS),s.duration&&(a=s),i.PTSKnown=i.alignedSliding=!0),t.hasStreams&&(s.elementaryStreams=t.elementaryStreams),s.loader=t.loader,t.hasStats&&(s.stats=t.stats),t.initSegment&&(s.initSegment=t.initSegment,r=t.initSegment)});const o=i.fragments,l=i.fragmentHint?o.concat(i.fragmentHint):o;if(r&&l.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=r)?void 0:e.relurl)||(t.initSegment=r)}),i.skippedSegments){if(i.deltaUpdateFailed=o.some(t=>!t),i.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=i.skippedSegments;t--;)o.shift();i.startSN=o[0].sn}else{i.canSkipDateRanges&&(i.dateRanges=function(t,e,i){const{dateRanges:s,recentlyRemovedDateranges:r}=e,n=v({},t);r&&r.forEach(t=>{delete n[t]});const a=Object.keys(n).length;if(!a)return s;return Object.keys(s).forEach(t=>{const e=n[t],r=new ai(s[t].attr,e);r.isValid?(n[t]=r,e||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Xt(s[t].attr)}"`)}),n}(t.dateRanges,i,s));const e=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!i.hasProgramDateTime)for(let t=1;t<l.length;t++)null===l[t].programDateTime&&Hi(l[t],l[t-1],e);Ni(e,i)}i.endCC=o[o.length-1].cc}if(!i.startCC){var d;const e=es(t,i.startSN-1);i.startCC=null!=(d=null==e?void 0:e.cc)?d:o[0].cc}!function(t,e,i){if(t&&e){let s=0;for(let r=0,n=t.length;r<=n;r++){const n=t[r],a=e[r+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):s--}}}(t.partList,i.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),a?zi(i,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,s):Zi(t,i),o.length&&(i.totalduration=i.edge-o[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const h=i.advancedDateTime;if(i.advanced&&h){const t=i.edge;i.driftStart||(i.driftStartTime=h,i.driftStart=t),i.driftEndTime=h,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime;-1===i.requestScheduled&&(i.requestScheduled=t.requestScheduled)}function Qi(t,e,i,s,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function Zi(t,e,i=!0){const s=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&i)a=t.fragmentStart+s*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}Ji(e,a)}function Ji(t,e){if(e){const i=t.fragments;for(let s=t.skippedSegments;s<i.length;s++)i[s].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function ts(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const s=t.fragments,r=4;if(s.length&&i*r>e){const t=1e3*s[s.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}function es(t,e,i){if(!t)return null;let s=t.fragments[e-t.startSN];return s||(s=t.fragmentHint,s&&s.sn===e?s:e<t.startSN&&i&&i.sn===e?i:null)}function is(t,e,i){return t?ss(t.partList,e,i):null}function ss(t,e,i){if(t)for(let s=t.length;s--;){const r=t[s];if(r.index===i&&r.fragment.sn===e)return r}return null}function rs(t){t.forEach((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function ns(t,e){return!(t===e||!e)&&as(t)!==as(e)}function as(t){return t.replace(/\?[^?]*$/,"")}function os(t,e){for(let s=0,r=t.length;s<r;s++){var i;if((null==(i=t[s])?void 0:i.cc)===e)return t[s]}return null}function ls(t,e){const i=t.start+e;t.startPTS=i,t.setStart(i),t.endPTS=i+t.duration}function ds(t,e){const i=e.fragments;for(let e=0,s=i.length;e<s;e++)ls(i[e],t);e.fragmentHint&&ls(e.fragmentHint,t),e.alignedSliding=!0}function hs(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const i=Math.min(e.endCC,t.endCC),s=os(e.fragments,i),r=os(t.fragments,i);if(!s||!r)return;R.log(`Aligning playlist at start of dicontinuity sequence ${i}`);ds(s.start-r.start,t)}function cs(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,s=e.fragments;if(!i.length||!s.length)return;let r,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(r=os(s,a),n=os(i,a)),r&&n||(r=s[Math.floor(s.length/2)],n=os(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;ds((l-o)/1e3-(n.start-r.start),t)}function us(t,e,i){fs(t,e,i),t.addEventListener(e,i)}function fs(t,e,i){t.removeEventListener(e,i)}const gs=function(t){let e="";const i=t.length;for(let s=0;s<i;s++)e+=`[${t.start(s).toFixed(3)}-${t.end(s).toFixed(3)}]`;return e},ms="STOPPED",ps="IDLE",vs="KEY_LOADING",ys="FRAG_LOADING",Es="FRAG_LOADING_WAITING_RETRY",Ts="WAITING_TRACK",Ss="PARSING",bs="PARSED",As="ENDED",Ls="ERROR",Is="WAITING_INIT_PTS",Rs="WAITING_LEVEL";class ks extends qe{constructor(t,i,s,r,n){super(r,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ms,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:t,fragCurrent:i,media:s,mediaBuffer:r,state:n}=this,a=s?s.currentTime:0,o=ze.bufferInfo(r||s,a,t.maxBufferHole),l=!o.len;if(this.log(`Media seeking to ${e(a)?a.toFixed(3):a}, state: ${n}, ${l?"out of":"in"} buffer`),this.state===As)this.resetLoadingState();else if(i){const e=t.maxFragLookUpTolerance,s=i.start-e,r=i.start+i.duration+e;if(l||r<o.start||s>o.end){const t=a>r;(a<s||t)&&(t&&i.loader&&(this.log(`Cancelling fragment load for seek (sn: ${i.sn})`),i.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s){this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0);if(a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts){const t=Math.max(o.end,a),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}}this.hls.hasEnoughToStart||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${a} for seek without enough to start`),this.nextLoadPosition=a,l&&(this.startPosition=a)),l&&this.state===ps&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=t,this.fragmentLoader=new Ke(t.config),this.keyLoader=s,this.fragmentTracker=i,this.config=t.config,this.decrypter=new $e(t.config)}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===ms)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ms}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const i=t.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=ze.bufferedInfo(r,t.start,0));const n=t.nextStart;if(n&&n>s&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return ze.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;us(i,"seeking",this.onMediaSeeking),us(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===ms&&this.startLoad(s.startPosition)}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(null!==s){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),fs(s,"seeking",this.onMediaSeeking),fs(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(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ms,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(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,i=t.frag;this.fragContextChanged(i)?(e===ys||!this.fragCurrent&&e===Ss)&&(this.fragmentTracker.removeFragment(i),this.state=ps):("payload"in t&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(a.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==ms&&this.state!==Ls&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===_e){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,s?s.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===De&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(a.BUFFER_FLUSHING,s)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t}).then(t=>{const{hls:e}=this,{frag:i,payload:s}=t,o=i.decryptdata;if(s&&s.byteLength>0&&null!=o&&o.key&&o.iv&&hi(o.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),o.key.buffer,o.iv.buffer,ci(o.method)).catch(t=>{throw e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t}).then(s=>{const r=self.performance.now();return e.trigger(a.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:l,tdecrypt:r}}),t.payload=s,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)}).catch(e=>{this.state!==ms&&this.state!==Ls&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state!==ms&&(this.state=ps),t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var i,s;const o=t.tracks;if(o&&!e.encrypted&&(null!=(i=o.audio)&&i.encrypted||null!=(s=o.video)&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(i.message),!t||t.mediaKeys?!1:(this.hls.trigger(a.ERROR,{type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?gs(ze.getBuffered(i)):"(detached)"})`),G(t)){var s;if(t.type!==f){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=ps)}const e=null==(s=this.levels)?void 0:s[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=ps}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:r}=t,n=!r||0===r.length||r.some(t=>!t),a=new Ye(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,i,s=null,r){var n;this.fragCurrent=t;const o=i.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let l=null;if(!t.encrypted||null!=(n=t.decryptdata)&&n.key)t.encrypted||(l=this.keyLoader.loadClear(t,o.encryptedFragments,this.startFragRequested),l&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${t.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=vs,this.fragCurrent=t,l=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(a.KEY_LOADED,t),this.state===vs&&(this.state=ps),t}),this.hls.trigger(a.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const d=this.fragPrevious;if(G(t)&&(!d||t.sn!==d.sn)){const e=this.shouldLoadParts(i.details,t.end);e!==this.loadingParts&&(this.log(`LL-Part loading ${e?"ON":"OFF"} loading sn ${null==d?void 0:d.sn}->${t.sn}`),this.loadingParts=e)}if(s=Math.max(t.start,s||0),this.loadingParts&&G(t)){const e=o.partList;if(e&&r){s>o.fragmentEnd&&o.fragmentHint&&(t=o.fragmentHint);const n=this.getNextPart(e,t,s);if(n>-1){const d=e[n];let h;return t=this.fragCurrent=d.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${d.index} (${n}/${e.length-1}) of ${this.fragInfo(t,!1,d)}) cc: ${t.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=ys,h=l?l.then(e=>!e||this.fragContextChanged(e.frag)?null:this.doFragPartsLoad(t,d,i,r)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,d,i,r).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,part:d,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(e,s))return Promise.resolve(null)}}var h;if(G(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(h=o.partList)?void 0:h.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),e(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ys;const c=this.config.progressive&&t.type!==f;let u;return u=c&&l?l.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,r)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,c?r:void 0),l]).then(([t])=>(!c&&r&&r(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(t,e,i,s){return new Promise((r,n)=>{var o;const l=[],d=null==(o=i.details)?void 0:o.partList,h=e=>{this.fragmentLoader.loadPart(t,e,s).then(s=>{l[e.index]=s;const n=s.part;this.hls.trigger(a.FRAG_LOADED,s);const o=is(i.details,t.sn,e.index+1)||ss(d,t.sn,e.index+1);if(!o)return r({frag:t,part:n,partsLoaded:l});h(o)}).catch(n)};h(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===n.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===r.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger(a.ERROR,e)}else this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Ss)return void(this.fragCurrent||this.state===ms||this.state===Ls||(this.state=ps));const{frag:i,part:s,level:r}=e,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,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var i;const r=t.partList[0];if(r.fragment.type===f)return!1;if(e>=r.end+((null==(i=t.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(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:n}=t;if(null==e||!e[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=e[s],o=a.details,l=n>-1?is(o,r,n):null,d=l?l.fragment:es(o,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,i,s,r){if(this.state!==Ss)return;const{data1:n,data2:o}=t;let l=n;if(o&&(l=dt(n,o)),!l.length)return;const d=this.initPTS[e.cc],h=d?-d.baseTime/d.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:s,offset:h,parent:e.type,data:l};if(this.hls.trigger(a.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!ze.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,s=ze.bufferInfo(e,i,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,s.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,i){var s;const r=this.getLoadPosition();if(!e(r))return null;const n=this.lastCurrentTime>r||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,r,i,n)}getFwdBufferInfoAtPos(t,e,i,s){const r=ze.bufferInfo(t,e,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&(r.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(r.nextStart,n.end)-e,s);return ze.bufferInfo(t,e,i)}}return r}getMaxBufferLength(t){const{config:e}=this;let i;return i=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e),r=Math.max(t-3*e,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=c){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=i[0].start,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=r.initialLiveManifestSize;if(s<i)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${i})`),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);const i=this.hls.startPosition,s=this.hls.liveSyncPosition,r=o?(-1!==i&&i>=n?i:s)||o.start:t;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 t<=n&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let d=this.filterReplacedPrimary(o,e);if(!d&&o){const t=o.sn-e.startSN;d=this.filterReplacedPrimary(i[t+1]||null,e)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===we||i===De&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,s,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==t&&i.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(_s(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(_s(this.config)&&t.type!==f){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(t.start-s.start)>1||0===s.start)return null}else{if(t.end<=s.start&&!1===(null==e?void 0:e.live))return null;if(t.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||t.start-s.end>1))return null}}const r=null==i?void 0:i.playerQueue;if(r)for(let e=r.length;e--;){const i=r[e].interstitial;if(i.appendInPlace&&t.start>=i.startTime&&t.end<=i.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let s=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[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===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${o.start}`),s=a),r=l}return s}loadedEndOfParts(t,e){let i;for(let s=t.length;s--;){if(i=t[s],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const i=t.fragments,s=this.fragPrevious;let r=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=function(t,i,s){if(null===i||!Array.isArray(t)||!t.length||!e(i))return null;if(i<(t[0].programDateTime||0))return null;if(i>=(t[t.length-1].endProgramDateTime||0))return null;for(let e=0;e<t.length;++e){const r=t[e];if(le(i,s,r))return r}return null}(i,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const e=s.sn+1;if(e>=t.startSN&&e<=t.endSN){const n=i[e-t.startSN];s.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=de(t,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,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),t<e){var u;c=ae(r,n,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const t=c.sn-i.startSN,e=this.fragmentTracker.getState(c);if((e===we||e===De&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!h||d[0].fragment.sn>c.sn||!i.live)){if(c.level===r.level){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==we?e:null}}}return c}alignPlaylists(t,i,s){const r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=t.fragmentStart,a=!i,o=t.alignedSliding&&e(n);if(a||!o&&!n){!function(t,e){t&&(hs(e,t),e.alignedSliding||cs(e,t),e.alignedSliding||e.skippedSegments||Zi(t,e,!1))}(s,t);const e=t.fragmentStart;return this.log(`Live playlist sliding: ${e.toFixed(2)} start-sn: ${i?i.startSN:"na"}->${t.startSN} fragments: ${r}`),e}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,i){let s=this.startPosition;s<i&&(s=-1);const r=this.timelineOffset;if(-1===s){const n=null!==this.startTimeOffset,a=n?this.startTimeOffset:t.startTimeOffset;null!==a&&e(a)?(s=i+a,a<0&&(s+=t.edge),s=Math.min(Math.max(i,s),i+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):t.live?(s=this.hls.liveSyncPosition||i,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var t;const{media:e}=this;let i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&G(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===Es)||(this.state=ps)}onFragmentOrKeyLoadError(t,e){var i;if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const s=e.frag;if(!s||s.type!==t||!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 a=e.details===n.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);const o=e.errorAction;if(!o)return void(this.state=Ls);const{action:l,flags:d,retryCount:h=0,retryConfig:c}=o,u=!!c,f=u&&l===Se,g=u&&!o.resolved&&d===Ae,m=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!f&&g&&G(s)&&!s.endList&&m&&!ue(e))this.resetFragmentErrors(t),this.treatAsGap(s),o.resolved=!0;else if((f||g)&&h<c.maxNumRetry){var p;const i=ve(null==(p=e.response)?void 0:p.code),r=ge(c,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=Es,o.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${h+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(t),!(h<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${h})`);a||l===Te||(o.resolved=!0)}else this.state=l===Ee?Rs:Ls;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,i=e===1/0;(!e||t>=e||i&&!ve(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ps)}reduceLengthAndFlushBuffer(t){if(this.state===Ss||this.state===bs){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===u&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ms&&(this.state=ps)}afterBufferFlushed(t,e,i){if(!t)return;const s=ze.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===As&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ms&&(this.state=ps)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){const o=i.details;if(!o)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce((e,r)=>{const n=t.elementaryStreams[r];if(n){const l=n.endPTS-n.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${l})`),e||!1;const d=s?0:zi(o,t,n.startPTS,n.endPTS,n.startDTS,n.endDTS,this);return this.hls.trigger(a.LEVEL_PTS_UPDATED,{details:o,level:i,drift:d,type:r,frag:t,start:n.startPTS,end:n.endPTS}),!0}return e},!1)){var l;const e=null===(null==(l=this.transmuxer)?void 0:l.error);if((0===i.fragmentError||e&&(i.fragmentError<2||t.endList))&&this.treatAsGap(t,i),e){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=bs,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(a.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===c?"level":"track"}fragInfo(t,e=!0,i){var s,r;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${(null!=(s=e&&!i?t.startPTS:(i||t).start)?s:NaN).toFixed(3)}-${(null!=(r=e&&!i?t.endPTS:(i||t).end)?r:NaN).toFixed(3)}]${i&&"main"===t.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function _s(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Ds{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let s=0;for(let e=0;e<t.length;e++){const r=t[e];i.set(r,s),s+=r.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var ws,Ps={exports:{}};var Cs=(ws||(ws=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0===--t._eventsCount?t._events=new s:delete t._events[e]}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 t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];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(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},o.prototype.emit=function(t,e,s,r,n,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,s),!0;case 4:return h.fn.call(h.context,e,s,r),!0;case 5:return h.fn.call(h.context,e,s,r,n),!0;case 6:return h.fn.call(h.context,e,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(t,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,e);break;case 3:h[d].fn.call(h[d].context,e,s);break;case 4:h[d].fn.call(h[d].context,e,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(t,e,i){return n(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||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!==e||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(t){var e;return t?(e=i?i+t:t,this._events[e]&&a(this,e)):(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,t.exports=o}(Ps)),Ps.exports),xs=C(Cs);const Ms="1.6.15",Os={};function Fs(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Ns(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Bs(t,e){let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i}function Us(t,e){const i=e;let s=0;for(;Ns(t,e);){s+=10;s+=Bs(t,e+6),Fs(t,e+10)&&(s+=10),e+=s}if(s>0)return t.subarray(i,i+s)}function $s(t,e){return 255===t[e]&&240==(246&t[e+1])}function Gs(t,e){return 1&t[e+1]?7:9}function Ks(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Hs(t,e){return e+1<t.length&&$s(t,e)}function Vs(t,e){if(Hs(t,e)){const i=Gs(t,e);if(e+i>=t.length)return!1;const s=Ks(t,e);if(s<=i)return!1;const r=e+s;return r===t.length||Hs(t,r)}return!1}function js(t,e,i,s,o){if(!t.samplerate){const l=function(t,e,i,s){const o=e[i+2],l=o>>2&15;if(l>12){const e=new Error(`invalid ADTS sampling index:${l}`);return void t.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const d=1+(o>>6&3),h=e[i+3]>>6&3|(1&o)<<2,c="mp4a.40."+d,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][l];let f=l;5!==d&&29!==d||(f-=3);const g=[d<<3|(14&f)>>1,(1&f)<<7|h<<3];return R.log(`manifest codec:${s}, parsed codec:${c}, channels:${h}, rate:${u} (ADTS object type:${d} sampling index:${l})`),{config:g,samplerate:u,channelCount:h,codec:c,parsedCodec:c,manifestCodec:s}}(e,i,s,o);if(!l)return;v(t,l)}}function qs(t){return 9216e4/t}function Ys(t,e,i,s,r){const n=s+r*qs(t.samplerate),a=function(t,e){const i=Gs(t,e);if(e+i<=t.length){const s=Ks(t,e)-i;if(s>0)return{headerLength:i,frameLength:s}}}(e,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,d=Math.max(0,i+l-e.length);d?(o=new Uint8Array(l-r),o.set(e.subarray(i+r,e.length),0)):o=e.subarray(i+r,i+l);const h={unit:o,pts:n};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Ws(t,e){return Ns(t,e)&&Bs(t,e+6)+10<=t.length-e}function zs(t,e=0,i=1/0){return function(t,e,i,s){const r=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=(c=t,c&&c.buffer instanceof ArrayBuffer&&void 0!==c.byteLength&&void 0!==c.byteOffset?t.byteOffset:0),o=(a+t.byteLength)/n,l=(a+e)/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)}(t,e,i,Uint8Array)}function Xs(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=t.data.subarray(1).indexOf(0);if(-1===i)return;const s=D(zs(t.data,1,i)),r=t.data[2+i],n=t.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=D(zs(t.data,3+i,n));let o;return o="--\x3e"===s?D(zs(t.data,4+i+n)):function(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}(t.data.subarray(4+i+n)),e.mimeType=s,e.pictureType=r,e.description=a,e.data=o,e}function Qs(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=D(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=D(t.data.subarray(e),!0);e+=i.length+1;const s=D(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=D(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?Xs(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const i=D(t.data.subarray(e),!0);e+=i.length+1;const s=D(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=D(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function Zs(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=Bs(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}function Js(t){let e=0;const i=[];for(;Ns(t,e);){const s=Bs(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+s;for(;e+10<r;){const s=Zs(t.subarray(e)),r=Qs(s);r&&i.push(r),e+=s.size+10}Fs(t,e)&&(e+=10)}return i}function tr(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function er(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}function ir(t){const e=Js(t);for(let t=0;t<e.length;t++){const i=e[t];if(tr(i))return er(i)}}let sr=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function rr(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class nr{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(t,e,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,i){this.cachedData&&(t=dt(this.cachedData,t),this.cachedData=null);let s,r=Us(t,0),n=r?r.length:0;const a=this._audioTrack,o=this._id3Track,l=r?ir(r):void 0,d=t.length;for((null===this.basePTS||0===this.frameIndex&&e(l))&&(this.basePTS=ar(l,i,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:sr.audioId3,duration:Number.POSITIVE_INFINITY});n<d;){if(this.canParse(t,n)){const e=this.appendFrame(a,t,n);e?(this.frameIndex++,this.lastPTS=e.sample.pts,n+=e.length,s=n):n=d}else Ws(t,n)?(r=Us(t,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:sr.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,s=n):n++;if(n===d&&s!==d){const e=t.slice(s);this.cachedData?this.cachedData=dt(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:rr(),id3Track:o,textTrack:rr()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:rr(),id3Track:this._id3Track,textTrack:rr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const ar=(t,i,s)=>{if(e(t))return 90*t;return 9e4*i+(s?9e4*s.baseTime/s.timescale:0)};let or=null;const lr=[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],dr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],hr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],cr=[0,1,1,4];function ur(t,e,i,s,r){if(i+24>e.length)return;const n=fr(e,i);if(n&&i+n.frameLength<=e.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function fr(t,e){const i=t[e+1]>>3&3,s=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*lr[14*(3===i?3-s:3===s?3:4)+r-1],d=dr[3*(3===i?0:2===i?1:2)+n],h=3===o?1:2,c=hr[i][s],u=cr[s],f=8*c*u,g=Math.floor(c*l/d+a)*u;if(null===or){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);or=t?parseInt(t[1]):0}return!!or&&or<=87&&2===s&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function gr(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function mr(t,e){return e+1<t.length&&gr(t,e)}function pr(t,e){if(e+1<t.length&&gr(t,e)){const i=4,s=fr(t,e);let r=i;null!=s&&s.frameLength&&(r=s.frameLength);const n=e+r;return n===t.length||mr(t,n)}return!1}const vr=(t,e)=>{let i=0,s=5;e+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=t[e];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],e+=1,s-=o}return i};class yr extends nr{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const s=Er(t,e,i,this.basePTS,this.frameIndex);if(-1!==s){return{sample:t.samples[t.samples.length-1],length:s,missing:0}}}static probe(t){if(!t)return!1;const e=Us(t,0);if(!e)return!1;const i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==ir(e)&&vr(t,i)<16}}function Er(t,e,i,s,r){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const n=e[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[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>e.length)return-1;const d=e[i+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(e[i+6]<<8|e[i+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=e[i+5]>>3,g=7&e[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),v=e.subarray(i,i+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}const Tr=/\/emsg[-/]ID3/i;function Sr(t,i){return e(t.presentationTime)?t.presentationTime/t.timeScale:i+t.presentationTimeDelta/t.timeScale}class br{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new $e(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,Oe)}decryptAacSample(t,e,i){const s=t[e].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(t,e+1,i)}).catch(i)}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)i.set(t.subarray(e,e+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)t.set(i.subarray(s,s+16),e);return t}decryptAvcSample(t,e,i,s,r){const n=gt(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)}).catch(s)}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void s();const r=t[e].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,s,n),this.decrypter.isSync())))return}}}}class Ar{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i,s=this.VideoSample;if(s&&0!==s.units.length||(s=t[t.length-1]),null!=(e=s)&&e.units){const t=s.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,s=i.length;if(!s)return void e.dropped++;{const e=i[s-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,i){const s=e.byteLength;let r=t.naluState||0;const n=r,a=[];let o,l,d,h=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(e,0),r=0,h=1);h<s;)if(o=e[h++],r)if(1!==r)if(o)if(1===o){if(l=h-r-1,c>=0){const t={data:e.subarray(c,l),type:u};a.push(t)}else{const i=this.getLastNalUnit(t.samples);i&&(n&&h<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=dt(i.data,e.subarray(0,l)),i.state=0))}h<s?(d=this.getNALuType(e,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 t={data:e.subarray(c,s),type:u,state:r};a.push(t)}if(0===a.length){const i=this.getLastNalUnit(t.samples);i&&(i.data=dt(i.data,e))}return t.naluState=r,a}}class Lr{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");s.set(t.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&R.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Ir extends Ar{parsePES(t,e,i,s){const r=this.parseNALu(t,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 1:{let e=!1;n=!0;const r=s.data;if(o&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;if(e)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),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,ft(s.data,1,i.pts,e.samples);break;case 7:{var h,c;n=!0,o=!0;const e=s.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(h=t.pixelRatio)?void 0:h[0])!==i.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e];const s=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=s[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:n=!0,t.pps=[s.data];break;case 9:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),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,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new Lr(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,s=8,r=8;for(let n=0;n<t;n++)0!==r&&(i=e.readEG(),r=(s+i+256)%256),s=0===r?s:r}readSPS(t){const e=new Lr(t);let i,s,r,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),h=e.readBits.bind(e),c=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=c();if(3===t&&f(1),m(),m(),f(1),u())for(s=3!==t?8:12,r=0;r<s;r++)u()&&p(r<6?16:64,e)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),i=c(),r=0;r<i;r++)g();m(),f(1);const E=c(),T=c(),S=h(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let b=[1,1];if(u()&&u()){switch(d()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}class Rr extends Ar{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,s){const r=this.parseNALu(t,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),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,t),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,t),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,ft(s.data,2,i.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=v(t.params,this.readVPS(s.data)),this.initVPS=s.data),t.vps=[s.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],s.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(s.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const i in e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,s.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(s.data);for(const i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,s.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),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,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let s=0;s<t.byteLength;s++)s>=2&&3===t[s]&&0===t[s-1]&&0===t[s-2]||(e[i]=t[s],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new Lr(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new Lr(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const s=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),d=e.readUByte(),h=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let t=0;t<i;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),S=e.readUEG(),b=e.readBoolean();let A=0,L=0,I=0,R=0;b&&(A+=e.readUEG(),L+=e.readUEG(),I+=e.readUEG(),R+=e.readUEG());const k=e.readUEG(),_=e.readUEG(),D=e.readUEG();for(let t=e.readBoolean()?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBoolean()){const i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const w=e.readUEG();let P=0;for(let t=0;t<w;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===w&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=P;t++){const t=e.readBoolean();let s=!1;t||(s=e.readBoolean()),(t||s)&&i++}P=i}else{const t=e.readUEG(),i=e.readUEG();P=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<D+4;t++)e.readBits(1);e.readBits(1)}}let C=0,x=1,M=1,O=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let B=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(x=e.readBits(16),M=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),B=e.readBoolean(),B&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),s=e.readBoolean();let r=!1;(t||s)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){O=e.readBoolean();let i=!1;O||e.readBoolean()?e.readEG():i=e.readBoolean();const n=i?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(s)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),C=e.readUEG())}let U=T,$=S;if(b){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),U=T-t*L-t*A,$=S-e*R-e*I}const G=s?["A","B","C"][s]:"",K=a<<24|o<<16|l<<8|d;let H=0;for(let t=0;t<32;t++)H=(H|(K>>t&1)<<31-t)>>>0;let V=H.toString(16);1===n&&"2"===V&&(V="6");return{codecString:`hvc1.${G}${n}.${V}.${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:_,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:O,fps:N/F}},width:U,height:$,pixelRatio:[x,M]}}readPPS(t){const e=new Lr(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const i=e.readBoolean(),s=e.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}}const kr=188;class _r{constructor(t,e,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=t,this.config=e,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(t,e){const i=_r.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let i=Math.min(940,e-kr)+1,s=0;for(;s<i;){let r=!1,n=-1,a=0;for(let o=s;o<e;o+=kr){if(71!==t[o]||e-o!==kr&&71!==t[o+kr]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,t.length-kr)+1)),r||(r=0===Dr(t,o)),r&&a>1&&(0===n&&a>2||o+kr>i))return n}s++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Y[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=_r.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=_r.createTrack("audio",s),this._id3Track=_r.createTrack("id3"),this._txtTrack=_r.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,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,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=dt(this.remainderData,t)).length,this.remainderData=null),y<kr&&!s)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,_r.syncOffset(t));y-=(y-E)%kr,y<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let e=E;e<y;e+=kr)if(71===t[e]){const s=!!(64&t[e+1]),y=Dr(t,e);let T;if((48&t[e+3])>>4>1){if(T=e+5+t[e+4],T===e+kr)continue}else T=e+4;switch(y){case d:s&&(h&&(r=Mr(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(t.subarray(T,e+kr)),h.size+=e+kr-T);break;case c:if(s){if(f&&(r=Mr(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(t.subarray(T,e+kr)),f.size+=e+kr-T);break;case u:s&&(g&&(r=Mr(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+kr)),g.size+=e+kr-T);break;case 0:s&&(T+=t[T]+1),v=this._pmtId=wr(t,T);break;case v:{s&&(T+=t[T]+1);const r=Pr(t,T,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 ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&Cr(this.observer,new Error(`Found ${T} 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:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:s,textTrack:r}=t,n=i.pesData,a=e.pesData,o=s.pesData;let l;if(n&&(l=Mr(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=Mr(a,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=Mr(o,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=o}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),r=this.sampleAes=new br(this.observer,this.config,e);return this.decrypt(s,r)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new Ir:"hevc"===t&&(this.videoParser=new Rr))}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=t;s.samples&&"aac"===s.segmentCodec?e.decryptAacSamples(s.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{i(t)}):i(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{i(t)})})}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(t,e){let i=0;const s=this.aacOverFlow;let r,n,a,o=e.data;if(s){this.aacOverFlow=null;const e=s.missing,r=s.sample.unit.byteLength;if(-1===e)o=dt(s.sample.unit,o);else{const n=r-e;s.sample.unit.set(o.subarray(0,e),n),t.samples.push(s.sample),i=s.missing}}for(r=i,n=o.length;r<n-1&&!Hs(o,r);r++);if(r!==i){let t;const e=r<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",Cr(this.observer,new Error(t),e,this.logger),!e)return}if(js(t,this.observer,o,r,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=qs(t.samplerate);a=s.sample.pts+e}}let l,d=0;for(;r<n;){if(l=Ys(t,o,r,a,d),r+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;r<n-1&&!Hs(o,r);r++);}}parseMPEGPES(t,e){const i=e.data,s=i.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<s;)if(mr(i,n)){const e=ur(t,i,n,a,r);if(!e)break;n+=e.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,s=e.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=Er(t,i,o,s,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=v({},e,{type:this._videoTrack?sr.emsg:sr.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function Dr(t,e){return((31&t[e+1])<<8)+t[e+2]}function wr(t,e){return(31&t[e+10])<<8|t[e+11]}function Pr(t,e,i,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<o;){const o=Dr(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!s){xr("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){xr("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){xr("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=e+5,r=l;for(;r>2;){if(106===t[s])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const e=t[s+1]+2;s+=e,r-=e}}break;case 194:case 135:return Cr(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"))}e+=l+5}return a}function Cr(t,e,i,s){s.warn(`parsing error: ${e.message}`),t.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function xr(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Mr(t,e){let i,s,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=dt(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>t.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&&(e.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(t.size<=h)return null;t.size-=h;const c=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(h){if(h>e){h-=e;continue}i=i.subarray(h),e-=h,h=0}c.set(i,o),o+=e}return s&&(s-=r+3),{data:c,pts:n,dts:a,len:s}}return null}class Or{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)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===e)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===e)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===e)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===e)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 Fr=Math.pow(2,32)-1;class Nr{static init(){let t;for(t in Nr.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:[]},Nr.types)Nr.types.hasOwnProperty(t)&&(Nr.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=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]);Nr.HDLR_TYPES={video:e,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]);Nr.STTS=Nr.STSC=Nr.STCO=r,Nr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Nr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Nr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Nr.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]);Nr.FTYP=Nr.box(Nr.types.ftyp,n,o,n,a),Nr.DINF=Nr.box(Nr.types.dinf,Nr.box(Nr.types.dref,s))}static box(t,...e){let i=8,s=e.length;const r=s;for(;s--;)i+=e[s].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),s=0,i=8;s<r;s++)n.set(e[s],i),i+=e[s].byteLength;return n}static hdlr(t){return Nr.box(Nr.types.hdlr,Nr.HDLR_TYPES[t])}static mdat(t){return Nr.box(Nr.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Fr+1)),s=Math.floor(e%(Fr+1));return Nr.box(Nr.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,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(t){return Nr.box(Nr.types.mdia,Nr.mdhd(t.timescale||0,t.duration||0),Nr.hdlr(t.type),Nr.minf(t))}static mfhd(t){return Nr.box(Nr.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Nr.box(Nr.types.minf,Nr.box(Nr.types.smhd,Nr.SMHD),Nr.DINF,Nr.stbl(t)):Nr.box(Nr.types.minf,Nr.box(Nr.types.vmhd,Nr.VMHD),Nr.DINF,Nr.stbl(t))}static moof(t,e,i){return Nr.box(Nr.types.moof,Nr.mfhd(t),Nr.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Nr.trak(t[e]);return Nr.box.apply(null,[Nr.types.moov,Nr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Nr.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Nr.trex(t[e]);return Nr.box.apply(null,[Nr.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Fr+1)),s=Math.floor(e%(Fr+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,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 Nr.box(Nr.types.mvhd,r)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,r;for(s=0;s<e.length;s++)r=e[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Nr.box(Nr.types.sdtp,i)}static stbl(t){return Nr.box(Nr.types.stbl,Nr.stsd(t),Nr.box(Nr.types.stts,Nr.STTS),Nr.box(Nr.types.stsc,Nr.STSC),Nr.box(Nr.types.stsz,Nr.STSZ),Nr.box(Nr.types.stco,Nr.STCO))}static avc1(t){let e,i,s,r=[],n=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=Nr.box(Nr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return Nr.box(Nr.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,Nr.box(Nr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Nr.box(Nr.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(t){const e=t.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,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Nr.box(Nr.types.mp4a,Nr.audioStsd(t),Nr.box(Nr.types.esds,Nr.esds(t)))}static mp3(t){return Nr.box(Nr.types[".mp3"],Nr.audioStsd(t))}static ac3(t){return Nr.box(Nr.types["ac-3"],Nr.audioStsd(t),Nr.box(Nr.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.mp4a(t));if("ac3"===e&&t.config)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.avc1(t));if("hevc"===e&&t.vps)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),s=t.width||0,r=t.height||0,n=Math.floor(i/(Fr+1)),a=Math.floor(i%(Fr+1));return Nr.box(Nr.types.tkhd,new Uint8Array([1,0,0,7,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,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(t,e){const i=Nr.sdtp(t),s=t.id,r=Math.floor(e/(Fr+1)),n=Math.floor(e%(Fr+1));return Nr.box(Nr.types.traf,Nr.box(Nr.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Nr.box(Nr.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])),Nr.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Nr.box(Nr.types.trak,Nr.tkhd(t),Nr.mdia(t))}static trex(t){const e=t.id;return Nr.box(Nr.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r);let a,o,l,d,h,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,e>>>24&255,e>>>16&255,e>>>8&255,255&e],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 Nr.box(Nr.types.trun,n)}static initSegment(t){Nr.types||Nr.init();const e=Nr.moov(t);return dt(Nr.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],s=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let r=s.length;for(let t=0;t<i.length;t+=1){r+=3;for(let e=0;e<i[t].length;e+=1)r+=2+i[t][e].length}const n=new Uint8Array(r);n.set(s,0),r=s.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),r),r+=3;for(let e=0;e<i[t].length;e+=1)n.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),r),r+=2,n.set(i[t][e],r),r+=i[t][e].length}const o=Nr.box(Nr.types.hvcC,n),l=t.width,d=t.height,h=t.pixelRatio[0],c=t.pixelRatio[1];return Nr.box(Nr.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,Nr.box(Nr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Nr.box(Nr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}}Nr.types=void 0,Nr.HDLR_TYPES=void 0,Nr.STTS=void 0,Nr.STSC=void 0,Nr.STCO=void 0,Nr.STSZ=void 0,Nr.VMHD=void 0,Nr.SMHD=void 0,Nr.STSD=void 0,Nr.FTYP=void 0,Nr.DINF=void 0;function Br(t,e,i=1,s=!1){const r=t*e*i;return s?Math.round(r):r}function Ur(t,e=!1){return Br(t,1e3,1/9e4,e)}function $r(t){const{baseTime:e,timescale:i,trackId:s}=t;return`${e/i} (${e}/${i}) trackId: ${s}`}let Gr,Kr=null,Hr=null;function Vr(t,e,i,s){return{duration:e,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class jr extends T{constructor(t,e,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=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===Kr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Kr=t?parseInt(t[1]):0}if(null===Hr){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Hr=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?$r(e):e} > ${t?$r(t):t}`),this._initPTS=this._initDTS=t}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(t){let e=!1;const i=t[0].pts,s=t.reduce((t,s)=>{let r=s.pts,n=r-t;return n<-4294967296&&(e=!0,r=qr(r,i),n=r-t),n>0?t:r},i);return e&&this.debug("PTS rollover detected"),s}remux(t,e,i,s,r,n,a,o){let l,d,h,c,f,g,m=r,p=r;const v=t.pid>-1,y=e.pid>-1,E=e.samples.length,T=t.samples.length>0,S=a&&E>0||E>1;if((!v||T)&&(!y||S)||this.ISGenerated||a){if(this.ISGenerated){var b,A,L,I;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(b=e.pixelRatio)?void 0:b[0])!==(null==(A=t.pixelRatio)?void 0:A[0])||(null==(L=e.pixelRatio)?void 0:L[1])!==(null==(I=t.pixelRatio)?void 0:I[1]))||!t&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,e,r,n));const i=this.isVideoContiguous;let s,a=-1;if(S&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,a>0){this.warn(`Dropped ${a} out of ${E} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,p+=(e.samples[0].pts-t)/e.inputTimeScale,s=p}else-1===a&&(this.warn(`No keyframe found out of ${E} video samples`),g=!1);if(this.ISGenerated){if(T&&S){const i=this.getVideoStartPts(e.samples),s=(qr(t.samples[0].pts,i)-i)/e.inputTimeScale;m+=Math.max(0,s),p+=Math.max(0,-s)}if(T){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,e,r,n)),d=this.remuxAudio(t,m,this.isAudioContiguous,n,y||S||o===u?p:void 0),S){const s=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,p,i,s)}}else S&&(l=this.remuxVideo(e,p,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Yr(i,r,this._initPTS,this._initDTS)),s.samples.length&&(c=Wr(s,r,this._initPTS))),{audio:d,video:l,initSegment:h,independent:g,text:c,id3:f}}computeInitPts(t,e,i,s){const r=Math.round(i*e);let n=qr(t,r);if(n<r+e)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${s}`);n<r+e;)n+=8589934592;return n-r}generateIS(t,e,i,s){const r=t.samples,n=e.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),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Nr.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(g=t.id,c=t.inputTimeScale,l&&c===l.timescale?u=!1:d=h=this.computeInitPts(r[0].pts,c,i,"audio"))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Nr.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(g=e.id,c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=qr(n[0].dts,t),s=this.computeInitPts(e,c,i,"video"),r=this.computeInitPts(t,c,i,"video");h=Math.min(h,s),d=Math.min(d,r)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.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(t,e,i,s){const o=t.inputTimeScale,l=t.samples,d=[],h=l.length,c=this._initPTS,u=c.baseTime*o/c.timescale;let f,g,m=this.nextVideoTs,p=8,y=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!i||null===m){const t=u+e*o,s=l[0].pts-qr(l[0].dts,l[0].pts);Kr&&null!==m&&Math.abs(t-s-(m+u))<15e3?i=!0:m=t-s-u}const b=m+u;for(let t=0;t<h;t++){const e=l[t];e.pts=qr(e.pts,b),e.dts=qr(e.dts,b),e.dts<l[t>0?t-1:t].dts&&(S=!0)}S&&l.sort(function(t,e){const i=t.dts-e.dts,s=t.pts-e.pts;return i||s}),f=l[0].dts,g=l[l.length-1].dts;const A=g-f,L=A?Math.round(A/(h-1)):y||t.inputTimeScale/30;if(i){const i=f-b,s=i>L,r=i<-1;if((s||r)&&(s?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ur(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ur(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||b>=l[0].pts||Kr)){f=b;const t=l[0].pts-i;if(s)l[0].dts=f,l[0].pts=t;else{let e=!0;for(let s=0;s<l.length&&!(l[s].dts>t&&e);s++){const t=l[s].pts;if(l[s].dts-=i,l[s].pts-=i,s<l.length-1){const i=l[s+1].pts;e=i<=l[s].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ur(t,!0)}/${Ur(f,!0)}, delta: ${Ur(i,!0)} ms`)}}f=Math.max(0,f);let I=0,R=0,k=f;for(let t=0;t<h;t++){const e=l[t],i=e.units,s=i.length;let r=0;for(let t=0;t<s;t++)r+=i[t].data.length;R+=r,I+=s,e.length=r,e.dts<k?(e.dts=k,k+=L/4|0||1):k=e.dts,E=Math.min(e.pts,E),T=Math.max(e.pts,T)}g=l[h-1].dts;const _=R+4*I+8;let D;try{D=new Uint8Array(_)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:r.MUX_ERROR,details:n.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:_,reason:`fail allocating video mdat ${_}`})}const w=new DataView(D.buffer);w.setUint32(0,_),D.set(Nr.types.mdat,4);let P=!1,C=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<h;t++){const e=l[t],i=e.units;let r,n=0;for(let t=0,e=i.length;t<e;t++){const e=i[t],s=e.data,r=e.data.byteLength;w.setUint32(p,r),p+=4,D.set(s,p),p+=r,n+=4+r}if(t<h-1)y=l[t+1].dts-e.dts,r=l[t+1].pts-e.pts;else{const i=this.config,n=t>0?e.dts-l[t-1].dts:L;if(r=t>0?e.pts-l[t-1].pts:L,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*o),r=(s?E+s*o:this.nextAudioTs+u)-e.pts;r>t?(y=r-n,y<0?y=n:P=!0,this.log(`It is approximately ${r/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=n}else y=n}const a=Math.round(e.pts-e.dts);C=Math.min(C,y),M=Math.max(M,y),x=Math.min(x,r),O=Math.max(O,r),d.push(Vr(e.key,y,n,a))}if(d.length)if(Kr){if(Kr<70){const t=d[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Hr&&O-x<M-C&&L/M<.025&&0===d[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=f;for(let e=0,i=d.length;e<i;e++){const s=t+d[e].duration,r=t+d[e].cts;if(e<i-1){const t=s+d[e+1].cts;d[e].duration=t-r}else d[e].duration=e?d[e-1].duration:L;d[e].cts=0,t=s}}y=P||!y?L:y;const F=g+y;this.nextVideoTs=m=F-u,this.videoSampleDuration=y,this.isVideoContiguous=!0;const N={data1:Nr.moof(t.sequenceNumber++,f,v(t,{samples:d})),data2:D,startPTS:(E-u)/o,endPTS:(T+y-u)/o,startDTS:(f-u)/o,endDTS:m/o,type:"video",hasAudio:!1,hasVideo:!0,nb:d.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,s,o){const l=t.inputTimeScale,d=l/(t.samplerate?t.samplerate:l),h=this.getSamplesPerFrame(t),c=h*d,u=this._initPTS,f="mp3"===t.segmentCodec&&this.typeSupported.mpeg,g=[],m=void 0!==o;let p=t.samples,y=f?0:8,E=this.nextAudioTs||-1;const T=u.baseTime*l/u.timescale,S=T+e*l;if(this.isAudioContiguous=i=i||p.length&&E>0&&(s&&Math.abs(S-(E+T))<9e3||Math.abs(qr(p[0].pts,S)-(E+T))<20*c),p.forEach(function(t){t.pts=qr(t.pts,S)}),!i||E<0){const t=p.length;if(p=p.filter(t=>t.pts>=0),t!==p.length&&this.warn(`Removed ${p.length-t} of ${t} samples (initPTS ${T} / ${l})`),!p.length)return;E=0===o?0:s&&!m?Math.max(0,S-T):p[0].pts-T}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,s=E+T;i<p.length;i++){const r=p[i],n=r.pts,a=n-s,o=Math.abs(1e3*a/l);if(a<=-e*c&&m)0===i&&(this.warn(`Audio frame @ ${(n/l).toFixed(3)}s overlaps marker by ${Math.round(1e3*a/l)} ms.`),this.nextAudioTs=E=n-T,s=n);else if(a>=e*c&&o<1e4&&m){let e=Math.round(a/c);for(s=n-e*c;s<0&&e&&c;)e--,s+=c;0===i&&(this.nextAudioTs=E=s-T),this.warn(`Injecting ${e} audio frames @ ${((s-T)/l).toFixed(3)}s due to ${Math.round(1e3*a/l)} ms gap.`);for(let n=0;n<e;n++){let e=Or.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),p.splice(i,0,{unit:e,pts:s}),s+=c,i++}}r.pts=s,s+=c}}let b,A=null,L=null,I=0,R=p.length;for(;R--;)I+=p[R].unit.byteLength;for(let e=0,s=p.length;e<s;e++){const s=p[e],o=s.unit;let l=s.pts;if(null!==L){g[e-1].duration=Math.round((l-L)/d)}else{if(i&&"aac"===t.segmentCodec&&(l=E+T),A=l,!(I>0))return;I+=y;try{b=new Uint8Array(I)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:r.MUX_ERROR,details:n.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:I,reason:`fail allocating audio mdat ${I}`})}if(!f){new DataView(b.buffer).setUint32(0,I),b.set(Nr.types.mdat,4)}}b.set(o,y);const c=o.byteLength;y+=c,g.push(Vr(!0,h,c,0)),L=l}const k=g.length;if(!k)return;const _=g[g.length-1];E=L-T,this.nextAudioTs=E+d*_.duration;const D=f?new Uint8Array(0):Nr.moof(t.sequenceNumber++,A/d,v({},t,{samples:g}));t.samples=[];const w=(A-T)/l,P=this.nextAudioTs/l,C={data1:D,data2:b,startPTS:w,endPTS:P,startDTS:w,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,C}}function qr(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=i;return t}function Yr(t,e,i,s){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=qr(r.pts-i.baseTime*n/i.timescale,e*n)/n,r.dts=qr(r.dts-s.baseTime*n/s.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Wr(t,e,i){const s=t.samples.length;if(!s)return;const r=t.inputTimeScale;for(let n=0;n<s;n++){const s=t.samples[n];s.pts=qr(s.pts-i.baseTime*r/i.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function zr(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Xr(t,e,i){const s=t.codec;if(s&&s.length>4)return s;if(e===N){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return kt(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{Gr=self.performance.now.bind(self.performance)}catch(t){Gr=Date.now}const Qr=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,i,s){const r=this.videoTrack=rr("video",1),n=this.audioTrack=rr("audio",1),a=this.txtTrack=rr("text",1);if(this.id3Track=rr("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=et(t);if(o.video){const{id:t,timescale:e,codec:i,supplemental:s}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=i,r.supplemental=s}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;n.id=t,n.timescale=e,n.codec=i}a.id=Y.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let i=0;i<e;){const s=X(t,i);if(s>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=s>1?i+s:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=dt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=J(t,["moof"]);if(i.length<2)return e.remainder=t,e;const s=i[i.length-1];return e.valid=t.slice(0,s.byteOffset-8),e.remainder=t.slice(s.byteOffset-8),e}(i);this.remainderData=e.remainder,s.samples=e.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,e);return r.samples=ht(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return i.samples=ht(t,e),{videoTrack:e,audioTrack:rr(),id3Track:s,textTrack:rr()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const r=J(t.samples,["emsg"]);r&&r.forEach(t=>{const r=function(t){const e=t[0];let s="",r="",n=0,a=0,o=0,l=0,d=0,h=0;if(0===e){for(;"\0"!==W(t.subarray(h,h+1));)s+=W(t.subarray(h,h+1)),h+=1;for(s+=W(t.subarray(h,h+1)),h+=1;"\0"!==W(t.subarray(h,h+1));)r+=W(t.subarray(h,h+1)),h+=1;r+=W(t.subarray(h,h+1)),h+=1,n=X(t,12),a=X(t,16),l=X(t,20),d=X(t,24),h=28}else if(1===e){h+=4,n=X(t,h),h+=4;const e=X(t,h);h+=4;const a=X(t,h);for(h+=4,o=2**32*e+a,i(o)||(o=Number.MAX_SAFE_INTEGER,R.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=X(t,h),h+=4,d=X(t,h),h+=4;"\0"!==W(t.subarray(h,h+1));)s+=W(t.subarray(h,h+1)),h+=1;for(s+=W(t.subarray(h,h+1)),h+=1;"\0"!==W(t.subarray(h,h+1));)r+=W(t.subarray(h,h+1)),h+=1;r+=W(t.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:r,timeScale:n,presentationTime:o,presentationTimeDelta:a,eventDuration:l,id:d,payload:t.subarray(h,t.byteLength)}}(t);if(Tr.test(r.schemeIdUri)){const t=Sr(r,e);let i=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=r.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:sr.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=Sr(r,e);s.samples.push({data:r.payload,len:r.payload.byteLength,dts:t,pts:t,type:sr.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(t,e,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 T{constructor(t,e,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(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(t,s),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:i,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=et(t);if(e)!function(t,e){if(!t||!e)return;const i=e.keyId;i&&e.isCommonEncryption&&ot(t,(t,e)=>{const s=t.subarray(8,24);s.some(t=>0!==t)||(R.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${w(s)} -> ${w(i)}`),t.set(i,8))})}(t,e);else{const t=r||n;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}r&&(i=Xr(r,N,this)),n&&(s=Xr(n,B,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:r?a.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:t,id:"audio"}:n?a.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(t,i,s,r,n,a){var o,l;let{initPTS:d,lastEndTime:h}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};e(h)||(h=this.lastEndTime=n||0);const u=i.samples;if(!u.length)return c;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if(null!=(o=g)&&o.length||(this.generateInitSegment(u),g=this.initData),null==(l=g)||!l.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,i,s){const r={},n=J(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=J(a,["tfhd"])[0],l=X(o,4),d=i[l];if(!d)continue;r[l]||(r[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});const h=r[l],c=J(a,["tfdt"])[0];if(c){const t=c[0];let i=X(c,4);1===t&&(i===j?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(i*=j+1,i+=X(c,8))),e(i)&&(!e(h.start)||i<h.start)&&(h.start=i)}const u=d.default,f=X(o,0)|(null==u?void 0:u.flags);let g=(null==u?void 0:u.duration)||0;8&f&&(g=X(o,2&f?12:8));const m=J(a,["trun"]);let p=h.start||0,v=0,y=g;for(let t=0;t<m.length;t++){const e=m[t],i=X(e,4),s=h.sampleCount;h.sampleCount+=i;const r=1&e[3],n=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],d=8&e[2];let c=8,u=i;for(r&&(c+=4),n&&i&&(1&e[c+1]||void 0!==h.keyFrameIndex||(h.keyFrameIndex=s),c+=4,a?(y=X(e,c),c+=4):y=g,o&&(c+=4),d&&(c+=4),p+=y,v+=y,u--);u--;)a?(y=X(e,c),c+=4):y=g,o&&(c+=4),l&&(1&e[c+1]||void 0===h.keyFrameIndex&&(h.keyFrameIndex=h.sampleCount-(u+1),h.keyFrameStart=p),c+=4),d&&(c+=4),p+=y,v+=y;!v&&g&&(v+=g*i)}h.duration+=v}if(!Object.keys(r).some(t=>r[t].duration)){let i=1/0,s=0;const n=J(t,["sidx"]);for(let t=0;t<n.length;t++){const e=tt(n[t]);if(null!=e&&e.references){i=Math.min(i,e.earliestPresentationTime/e.timescale);const t=e.references.reduce((t,e)=>t+e.info.duration||0,0);s=Math.max(s,t+e.earliestPresentationTime/e.timescale)}}s&&e(s)&&Object.keys(r).forEach(t=>{r[t].duration||(r[t].duration=s*r[t].timescale-r[t].start)})}return r}(u,g,this),p=g.audio?m[g.audio.id]:null,v=g.video?m[g.video.id]:null,y=zr(v,1/0),E=zr(p,1/0),T=zr(v,0,!0),S=zr(p,0,!0);let b=n,A=0;const L=p&&(!v||!d&&E<y||d&&d.trackId===g.audio.id),I=L?p:v;if(I){const t=I.timescale,e=I.start-n*t,i=L?g.audio.id:g.video.id;b=I.start/t,A=L?S-E:T-y,!a&&d||!function(t,e,i,s){if(null===t)return!0;const r=Math.max(s,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>r}(d,b,n,A)&&t===d.timescale||(d&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${e/t} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${b-n} (${e}/${t}) trackId: ${i}`),d=null,f.initPTS=e,f.timescale=t,f.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):(f.timescale&&void 0!==f.trackId&&void 0!==f.initPTS||(this.warn("Could not set initPTS"),f.initPTS=b,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const R=b-d.baseTime/d.timescale,k=R+A;A>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const _=!!g.audio,D=!!g.video;let w="";_&&(w+="audio"),D&&(w+="video");const P={data1:u,startPTS:R,startDTS:R,endPTS:k,endDTS:k,type:w,hasAudio:_,hasVideo:D,nb:1,dropped:0,encrypted:!!g.audio&&g.audio.encrypted||!!g.video&&g.video.encrypted};c.audio=_&&!D?P:void 0,c.video=D?P:void 0;const C=null==v?void 0:v.sampleCount;if(C){const t=v.keyFrameIndex,e=-1!==t;P.nb=C,P.dropped=0===t||this.isVideoContiguous?0:e?t:C,P.independent=e,P.firstKeyFrame=t,e&&v.keyFrameStart&&(P.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(c.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),P.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${C} dropped: ${P.dropped} start: ${P.firstKeyFramePTS||"NA"}`)}return c.initSegment=f,c.id3=Yr(s,n,d,d),r.samples.length&&(c.text=Wr(r,n,d)),c}}},{demux:_r,remux:jr},{demux:class extends nr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=Us(t,0);let s=(null==i?void 0:i.length)||0;if(pr(t,s))return!1;for(let i=t.length;s<i;s++)if(Vs(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&$s(t,e)&&Ks(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){js(t,this.observer,e,i,t.manifestCodec);const s=Ys(t,e,i,this.basePTS,this.frameIndex);if(s&&0===s.missing)return s}},remux:jr},{demux:class extends nr{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Us(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==ir(e)&&vr(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(pr(t,i))return R.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return gr(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return ur(t,e,i,this.basePTS,this.frameIndex)}},remux:jr}];Qr.splice(2,0,{demux:yr,remux:jr});class Zr{constructor(t,e,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=t,this.typeSupported=e,this.config=i,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){const o=i.transmuxing;o.executeStart=Gr();let l=new Uint8Array(t);const{currentTransmuxState:d,transmuxConfig:h}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:u,trackSwitch:f,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=s||d,{audioCodec:v,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=h,b=function(t,e){let i=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(l,e);if(b&&hi(b.method)){const t=this.getDecrypter(),e=ci(b.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(l,b.key.buffer,b.iv.buffer,e).then(t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e}),this.decryptionPromise;{let s=t.softwareDecrypt(l,b.key.buffer,b.iv.buffer,e);if(i.part>-1){const e=t.flush();s=e?e.buffer:e}if(!s)return o.executeEnd=Gr(),Jr(i);l=new Uint8Array(s)}}const A=this.needsProbing(u,f);if(A){const t=this.configureTransmuxer(l);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),o.executeEnd=Gr(),Jr(i)}(u||f||p||A)&&this.resetInitSegment(S,v,y,T,e),(u||p||A)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const L=this.transmux(l,b,m,g,i);this.asyncResult=tn(L);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,o.executeEnd=Gr(),L}flush(t){const e=t.transmuxing;e.executeStart=Gr();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const n=[],{timeOffset:a}=s;if(i){const e=i.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Gr();const i=[Jr(t)];return this.asyncResult?Promise.resolve(i):i}const d=o.flush(a);return tn(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=e,{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===c?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Gr()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,s,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,i,s),a.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,s,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,s,r):this.transmuxUnencrypted(t,i,s,r),n}transmuxUnencrypted(t,e,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){return this.demuxer.demuxSampleAes(t,e,i).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s}=this;let r;for(let e=0,i=Qr.length;e<i;e++){var n;if(null!=(n=Qr[e].demux)&&n.probe(t,this.logger)){r=Qr[e];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,e,s,this.logger)),a&&a instanceof d||(this.demuxer=new d(i,e,s,this.logger),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new $e(this.config)),t}}const Jr=t=>({remuxResult:{},chunkMeta:t});function tn(t){return"then"in t&&t.then instanceof Function}class en{constructor(t,e,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=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class sn{constructor(t,e,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=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}let rn=0;class nn{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=rn++,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=t=>{const e=t.data,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var s;const t=null==(s=this.workerContext)?void 0:s.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,i.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const o=t.config;this.hls=t,this.id=e,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const l=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===a.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new xs,this.observer.on(a.FRAG_DECRYPTED,l),this.observer.on(a.ERROR,l);const d=Pt(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(i.log(`loading Web Worker ${o.workerPath} for "${e}"`),this.workerContext=function(t){const e=Os[t];if(e)return e.clientCount++,e;const i=new self.URL(t,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Os[t]=s,s}(o.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Os[Ms];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(e),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return Os[Ms]=s,s}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:d,id:e,config:Xt(o)})}catch(s){i.warn(`Error setting up "${e}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new Zr(this.observer,d,o,"",e,t.logger)}return}}this.transmuxer=new Zr(this.observer,d,o,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=rn++;const e=this.hls.config,i=Pt(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:Xt(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Os[t||Ms];if(e&&1===e.clientCount--){const{worker:i,objectURL:s}=e;delete Os[t||Ms],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,s,r,n,a,o,l,d){var h,u;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,m=n?n.start:r.start,p=r.decryptdata,v=this.frag,y=!(v&&r.cc===v.cc),E=!(v&&l.level===v.level),T=v?l.sn-v.sn:-1,S=this.part?l.part-this.part.index:-1,b=0===T&&l.id>1&&l.id===(null==v?void 0:v.stats.chunkCount),A=!E&&(1===T||0===T&&(1===S||b&&S<=0)),L=self.performance.now();(E||T||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),!n||!S&&A||(n.stats.parsing.start=L);const I=!(v&&(null==(h=r.initSegment)?void 0:h.url)===(null==(u=v.initSegment)?void 0:u.url)),R=new sn(y,A,o,E,m,I);if(!A||y||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===c?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${y}\n trackSwitch: ${E}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${m}\n initSegmentChange: ${I}`);const t=new en(i,s,e,a,d);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:R},t instanceof ArrayBuffer?[t]:[]);else if(g){const e=g.push(t,p,l,R);tn(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const e=i.flush(t);tn(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class an extends T{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}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(t,e,i){const s=null==e?void 0:e.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,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=s[r],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=i&&jt(i);return new qt(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,i){const{details:s,stats:o}=e,l=self.performance.now(),d=o.loading.first?Math.max(0,l-o.loading.first):0;s.advancedDateTime=Date.now()-d;const h=this.hls.config.timelineOffset;if(h!==s.appliedTimelineOffset){const t=Math.max(h||0,0);s.appliedTimelineOffset=t,s.fragments.forEach(e=>{e.setStart(e.playlistOffset+t)})}if(s.live||null!=i&&i.live){const h="levelInfo"in e?e.levelInfo:e.track;if(s.reloaded(i),i&&s.fragments.length>0){Xi(i,s,this);const t=s.playlistParsingError;if(t){this.warn(t);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var c;const{networkDetails:l}=e;return void i.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(c=s.fragments[0])?void 0:c.type,networkDetails:l,stats:o})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=o.loading.start);const u=this.hls.mainForwardBufferInfo,f=u?u.end-u.len:0,g=ts(s,1e3*(s.edge-f));if(s.requestScheduled+g<l?s.requestScheduled=l:s.requestScheduled+=g,this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let m,p,v;if(s.canBlockReload&&s.endSN&&s.advanced){const t=this.hls.config.lowLatencyMode,r=s.lastPartSn,n=s.endSN,a=s.lastPartIndex,o=r===n;-1!==a?o?(p=n+1,v=t?0:a):(p=r,v=t?a+1:s.maxPartIndex):p=n+1;const d=s.age,c=d+s.ageHeader;let u=Math.min(c-s.partTarget,1.5*s.targetduration);if(u>0){if(c>3*s.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(null!=i&&i.tuneInGoal&&c-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${u} with playlist age: ${s.age}`),u=0;else{const t=Math.floor(u/s.targetduration);if(p+=t,void 0!==v){v+=Math.round(u%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${u} skip sn ${t} to part ${v}`)}s.tuneInGoal=u}if(m=this.getDeliveryDirectives(s,e.deliveryDirectives,p,v),t||!o)return s.requestScheduled=l,void this.loadingPlaylist(h,m)}else(s.canBlockReload||s.canSkipUntil)&&(m=this.getDeliveryDirectives(s,e.deliveryDirectives,p,v));m&&void 0!==p&&s.canBlockReload&&(s.requestScheduled=o.loading.first+Math.max(g-2*d,g/2)),this.scheduleLoading(h,m,s)}else this.clearTimer()}scheduleLoading(t,e,i){const s=i||t.details;if(!s)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=s.requestScheduled;if(r>=n)return void this.loadingPlaylist(t,e);const a=n-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,i,s){let r=jt(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,r=Kt),new qt(i,s,r)}checkRetry(t){const e=t.details,i=he(t),s=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===Se||!s.resolved&&r===Ee);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=ge(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,s.resolved=!0}return o}}function on(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!ln(t[i].attrs,e[i].attrs))return!1;return!0}function ln(t,e,i){const s=t["STABLE-RENDITION-ID"];return s&&!i?s===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>t[i]!==e[i])}function dn(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class hn{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;const s=this.queues[e];s.push(t),1!==s.length||i||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const i=null==(e=t[0])?void 0:e.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(null===this.queues)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){var i;if(s.onError(e),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[t])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=null==(e=this.tracks)?void 0:e[t],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const cn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,un="HlsJsTrackRemovedError";class fn extends Error{constructor(t){super(t),this.name=un}}function gn(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function mn(t){return"audio"===t?1:0}class pn{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,i){this.timer&&e(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.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 t=this.hls.levels;if(t.length){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter((e,i)=>this.isLevelAllowed(e)&&i<=t);return this.clientRect=null,pn.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 t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,i){if(null==t||!t.length)return-1;const s=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let r=t.length-1;const n=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=n||i.height>=n)&&s(i,t[e+1])){r=e;break}}return r}}const vn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},yn={HLS:"h"};class En{constructor(t,e){Array.isArray(t)&&(t=t.map(t=>t instanceof En?t:new En(t))),this.value=t,this.params=e}}function Tn(t,e,i,s){return new Error(`failed to ${t} "${r=e,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 Sn(t,e,i){return Tn("serialize",t,e,i)}class bn{constructor(t){this.description=t}}const An="Bare Item";function Ln(t){if(!1===ArrayBuffer.isView(t))throw Sn(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function In(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw Sn(t,"Integer");return t.toString()}function Rn(t,e){if(t<0)return-Rn(-t,e);const i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){const e=Math.floor(t*i);return(e%2==0?e:e+1)/i}return Math.round(t*i)/i}function kn(t){const e=Rn(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Sn(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}const _n=/[\x00-\x1f\x7f]+/;function Dn(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Sn(e,"Token");return e}function wn(t){switch(typeof t){case"number":if(!e(t))throw Sn(t,An);return Number.isInteger(t)?In(t):kn(t);case"string":return function(t){if(_n.test(t))throw Sn(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Dn(t);case"boolean":return function(t){if("boolean"!=typeof t)throw Sn(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${In(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return Ln(t);if(t instanceof bn)return Dn(t);default:throw Sn(t,An)}}function Pn(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Sn(t,"Key");return t}function Cn(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${Pn(t)}`:`;${Pn(t)}=${wn(e)}`).join("")}function xn(t){return t instanceof En?`${wn(t.value)}${Cn(t.params)}`:wn(t)}function Mn(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw Sn(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),s=(null==e?void 0:e.whitespace)?" ":"";return Array.from(i).map(([t,e])=>{e instanceof En==!1&&(e=new En(e));let i=Pn(t);var s;return!0===e.value?i+=Cn(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(s=e).value.map(xn).join(" ")})${Cn(s.params)}`:i+=xn(e)),i}).join(`,${s}`)}function On(t,e){return Mn(t,e)}const Fn="CMCD-Object",Nn="CMCD-Request",Bn="CMCD-Session",Un="CMCD-Status",$n={br:Fn,ab:Fn,d:Fn,ot:Fn,tb:Fn,tpb:Fn,lb:Fn,tab:Fn,lab:Fn,url:Fn,pb:Nn,bl:Nn,tbl:Nn,dl:Nn,ltc:Nn,mtp:Nn,nor:Nn,nrr:Nn,rc:Nn,sn:Nn,sta:Nn,su:Nn,ttfb:Nn,ttfbb:Nn,ttlb:Nn,cmsdd:Nn,cmsds:Nn,smrt:Nn,df:Nn,cs:Nn,ts:Nn,cid:Bn,pr:Bn,sf:Bn,sid:Bn,st:Bn,v:Bn,msd:Bn,bs:Un,bsd:Un,cdn:Un,rtp:Un,bg:Un,pt:Un,ec:Un,e:Un},Gn=Nn;function Kn(t,e){const i={};if(!t)return i;const s=Object.keys(t),r=e?(n=e,Object.keys(n).reduce((t,e)=>{var i;return null===(i=n[e])||void 0===i||i.forEach(i=>t[i]=e),t},{})):{};var n;return s.reduce((e,i)=>{var s;const n=$n[i]||r[i]||Gn;return(null!==(s=e[n])&&void 0!==s?s:e[n]={})[i]=t[i],e},i)}const Hn="event";const Vn=t=>Math.round(t),jn=(t,e)=>Array.isArray(t)?t.map(t=>jn(t,e)):t instanceof En&&"string"==typeof t.value?new En(jn(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){const i=new URL(t),s=new URL(e);if(i.origin!==s.origin)return t;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}(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),qn=t=>100*Vn(t/100),Yn={br:Vn,d:Vn,bl:qn,dl:qn,mtp:qn,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof En&&"string"==typeof t.value?i=new En([t]):"string"==typeof t&&(i=[t])),jn(i,e)},rtp:qn,tb:Vn},Wn="request",zn="response",Xn=["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"],Qn=["e"],Zn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Jn(t){return Zn.test(t)}const ta=["d","dl","nor","ot","rtp","su"];const ea=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const ia=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function sa(t){return ia.includes(t)||Jn(t)}const ra={[zn]:function(t){return Xn.includes(t)||ta.includes(t)||ea.includes(t)||Jn(t)},[Hn]:function(t){return Xn.includes(t)||Qn.includes(t)||Jn(t)},[Wn]:function(t){return Xn.includes(t)||ta.includes(t)||Jn(t)}};function na(t,i={}){const s={};if(null==t||"object"!=typeof t)return s;const r=i.version||t.v||1,n=i.reportingMode||Wn,a=1===r?sa:ra[n];let o=Object.keys(t).filter(a);const l=i.filter;"function"==typeof l&&(o=o.filter(l));const d=n===zn||n===Hn;d&&!o.includes("ts")&&o.push("ts"),r>1&&!o.includes("v")&&o.push("v");const h=v({},Yn,i.formatters),c={version:r,reportingMode:n,baseUrl:i.baseUrl};return o.sort().forEach(i=>{let n=t[i];const a=h[i];if("function"==typeof a&&(n=a(n,c)),"v"===i){if(1===r)return;n=r}"pr"==i&&1===n||(d&&"ts"===i&&!e(n)&&(n=Date.now()),function(t){return"number"==typeof t?e(t):null!=t&&""!==t&&!1!==t}(n)&&(function(t){return["ot","sf","st","e","sta"].includes(t)}(i)&&"string"==typeof n&&(n=new bn(n)),s[i]=n))}),s}function aa(t,e,i){return v(t,function(t,e={}){const i={};if(!t)return i;const s=Kn(na(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(s).reduce((t,[e,i])=>{const s=On(i,{whitespace:!1});return s&&(t[e]=s),t},i)}(e,i))}function oa(t,e={}){if(!t)return"";const i=function(t,e={}){return t?On(na(t,e),{whitespace:!1}):""}(t,e);return encodeURIComponent(i)}const la=/CMCD=[^&#]+/;function da(t,e,i){const s=function(t,e={}){return t?`CMCD=${oa(t,e)}`:""}(e,i);if(!s)return t;if(la.test(t))return t.replace(la,s);const r=t.includes("?")?"&":"?";return`${t}${r}${s}`}function ha(t,e,i,s){t&&Object.keys(e).forEach(r=>{const n=t.filter(t=>t.groupId===r).map(t=>{const n=v({},t);return n.details=void 0,n.attrs=new si(n.attrs),n.url=n.attrs.URI=ca(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=s,n});t.push(...n)})}function ca(t,e,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(t=>{t&&l.searchParams.set(t,n[t])}),l.href}class ua extends T{constructor(t){super("eme",t.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=ua.CDMCleanupPromise?[ua.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:e,initData:i}=t,s=`"${t.type}" event: init data type: "${e}"`;if(this.debug(s),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Li(this.config));const e=t.map(Ai).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{const n=bi(r);if("sinf"!==e||n!==vi.FAIRPLAY)return void this.log(`Ignoring "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);let a;try{const t=W(new Uint8Array(i)),e=lt(ui(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${s} Failed to parse sinf: ${t}`)}const o=w(a),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this;let h=l[o];for(let t=0;t<d.length;t++){const s=d[t],r=s.decryptdata;if(!r.keyId)continue;const n=w(r.keyId);if(li(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,e,i,"encrypted-event-key-match")),h.catch(t=>this.handleError(t));break}}h||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(a.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(a.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(a.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(a.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(a.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(a.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,s=null==e?void 0:e[t];return s?s.licenseUrl:t===vi.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(t){const e=this.getLicenseServerUrl(t);if(void 0===e)throw new Error(`no license server URL configured for key-system "${t}"`);return e}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=null==e?void 0:e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,s=e.map(t=>t.audioCodec).filter(i),a=e.map(t=>t.videoCodec).filter(i);return s.length+a.length===0&&a.push("avc1.42e01e"),new Promise((e,i)=>{const o=t=>{const l=t.shift();this.getMediaKeysPromise(l,s,a).then(t=>e({keySystem:l,mediaKeys:t})).catch(e=>{t.length?o(t):i(e instanceof ma?e:new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};o(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Ii&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){var s;const r=function(t,e,i,s){let r;switch(t){case vi.FAIRPLAY:r=["cenc","sinf"];break;case vi.WIDEVINE:case vi.PLAYREADY:r=["cenc"];break;case vi.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,s){return[{initDataTypes:t,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}(r,e,i,s)}(t,e,i,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(s=n)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Xt(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,s.then(e=>e?this.setMediaKeysServerCertificate(i,t,e):i)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${w(t.keyId||[])} keyUri: ${t.uri}`);const s=i.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),s=fa(e),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,e){const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${w(t.decryptdata.keyId||[])}\n } (data length: ${e.byteLength})`),i.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Ai(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return new Promise((e,i)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const s=Ai(t);s?e(s):i(new Error(`Unable to find format for key-system "${t}"`))}).catch(i)})}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){const e=Li(this.config),i=t.map(bi).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(i)}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let i=0;i<e.length;i++){const s=ga(t,e[i]);if(s)return s}}loadKey(t){const e=t.keyInfo.decryptdata,i=fa(e),s=this.bannedKeyIds[i];if(s||"internal-error"===this.getKeyStatus(e)){const i=pa(s||"internal-error",e);return this.handleError(i,t.frag),Promise.reject(i)}const r=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[i];if(!n){const s=this.getKeySystemForKeyPromise(e).then(({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:e}))))).then(t=>{const i=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",i,"playlist-key")});return s.catch(e=>this.handleError(e,t.frag)),this.keyIdToKeySessionPromise[i]=s,s}return n.catch(i=>{if(i instanceof ma){const s=E({},i.data);"internal-error"===this.getKeyStatus(e)&&(s.decryptdata=e);const r=new ma(s,i.message);this.handleError(r,t.frag)}}),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof ma){e&&(t.data.frag=e);const i=t.data.decryptdata;this.error(`${t.message}${i?` (${w(i.keyId||[])})`:""}`),this.hls.trigger(a.ERROR,t.data)}else this.error(t.message),this.hls.trigger(a.ERROR,{type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=fa(t),i=this.keyIdToKeySessionPromise[e];if(!i){const e=bi(t.keyFormat),i=e?[e]:Li(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=Li(this.config)),0===t.length)throw new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Xt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(i)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===i.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,i,s){var a;const o=null==(a=this.config.drmSystems)||null==(a=a[t.keySystem])?void 0:a.generateRequest;if(o)try{const s=o.call(this.hls,e,i,t);if(!s)throw new Error("Invalid response from configured generateRequest filter");e=s.initDataType,i=s.initData?s.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(t){if(this.warn(t.message),this.hls&&this.hls.config.debug)throw t}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const l=fa(t.decryptdata),d=t.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${l} URI: ${d} (init data type: ${e} length: ${i.byteLength})`);const h=new xs,c=t._onmessage=e=>{const i=t.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));const{messageType:s,message:r}=e;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(t,r).catch(t=>{h.eventNames().length?h.emit("error",t):this.handleError(t)}):"license-release"===s?t.keySystem===vi.FAIRPLAY&&this.updateKeySession(t,fi("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${s}"`)},u=(t,e)=>{let i;e.keyStatus=t,t.startsWith("usable")?h.emit("resolved"):"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=pa(t,e.decryptdata):"expired"===t?i=new Error(`key expired (keyId: ${l})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${l})`),i&&(h.eventNames().length?h.emit("error",i):this.handleError(i))},f=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));const i=this.getKeyStatuses(t);if(!Object.keys(i).some(t=>"status-pending"!==i[t]))return;if("expired"===i[l])return this.log(`Expired key ${Xt(i)} in key-session "${t.mediaKeysSession.sessionId}"`),void this.renewKeySession(t);let s=i[l];if(s)u(s,t);else{var r;const e=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(r=t.keyStatusTimeouts)[l]||(r[l]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const i=this.getKeyStatus(t.decryptdata);if(i&&"status-pending"!==i)return this.log(`No status for keyId ${l} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${i} from other session.`),u(i,t);this.log(`key status for ${l} in key-session "${t.mediaKeysSession.sessionId}" timed out after ${e}ms`),s="internal-error",u(s,t)},e)),this.log(`No status for keyId ${l} (${Xt(i)}).`)}};us(t.mediaKeysSession,"message",c),us(t.mediaKeysSession,"keystatuseschange",f);const g=new Promise((t,e)=>{h.on("error",e),h.on("resolved",t)});return t.mediaKeysSession.generateRequest(e,i).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${l} URI: ${d}`)}).catch(e=>{throw new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>g).catch(e=>(h.removeAllListeners(),this.removeSession(t).then(()=>{throw e}))).then(()=>(h.removeAllListeners(),t))}getKeyStatuses(t){const e={};return t.mediaKeysSession.keyStatuses.forEach((i,s)=>{if("string"==typeof s&&"object"==typeof i){const t=s;s=i,i=t}const r="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);if(t.keySystem===vi.PLAYREADY&&16===r.length){const t=w(r);e[t]=i,gi(r)}const n=w(r);"internal-error"===i&&(this.bannedKeyIds[n]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${n} key-session "${t.mediaKeysSession.sessionId}"`),e[n]=i}),e}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),s=this.getServerCertificateUrl(t);return s?(this.log(`Fetching server certificate for "${t}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:s},d=e.certLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,i,s)=>{a(t.data)},onError:(e,i,a,d)=>{o(new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:E({url:l.url,data:void 0},e)},`"${t}" certificate request failed (${s}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,a)=>{o(new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${s})`))},onAbort:(t,e,i)=>{o(new Error("aborted"))}};i.load(l,h,c)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((s,a)=>{t.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),s(t)}).catch(t=>{a(new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(e=>this.updateKeySession(t,new Uint8Array(e)).catch(e=>{throw new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(t,e){const i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const s=(new DOMParser).parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let i=0,s=r.length;i<s;i++){var n,a;e=r[i];const s=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;s&&o&&t.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 fi(atob(l))}setupLicenseXHR(t,e,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,t,e,i,s)}).catch(n=>{if(!i.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,i,s)}).then(i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||s}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:s}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise((s,a)=>{const o=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${o}`);const l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return a(new Error("invalid state"));if(4===l.readyState)if(200===l.status){this._requestLicenseFailureCount=0;let e=l.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,l,o,t)}catch(t){this.error(t)}s(e)}else{const d=i.errorRetry,h=d?d.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>h||l.status>=400&&l.status<500)a(new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:l,response:{url:o,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${o}). Status: ${l.status} (${l.statusText})`));else{const i=h-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(t,e).then(s,a)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=l,this.setupLicenseXHR(l,o,t,e).then(({xhr:e,licenseChallenge:i})=>{t.keySystem==vi.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}).catch(a)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,us(i,"encrypted",this.onMediaEncrypted),us(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(fs(t,"encrypted",this.onMediaEncrypted),fs(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Di.clearKeyUriToKeyIdMap();const o=s.length;ua.CDMCleanupPromise=Promise.all(s.map(t=>this.removeSession(t)).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{o&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i,decryptdata:s}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}" keyId: ${w((null==s?void 0:s.keyId)||[])}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const o=this.mediaKeySessions.indexOf(t);o>-1&&this.mediaKeySessions.splice(o,1);const{keyStatusTimeouts:l}=t;l&&Object.keys(l).forEach(t=>self.clearTimeout(l[t]));const{drmSystemOptions:d}=this.config,h=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(d)?new Promise((t,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(i)}):Promise.resolve();return h.catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function fa(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return w(t.keyId)}function ga(t,e){return t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId)?e.mediaKeysSession.keyStatuses.get(t.keyId):t.matches(e.decryptdata)?e.keyStatus:void 0}ua.CDMCleanupPromise=void 0;class ma extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}function pa(t,e){const i="output-restricted"===t,s=i?n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ma({type:r.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},i?"HDCP level output restricted":`key status changed to "${t}"`)}function va(t,e){let i;try{i=new Event("addtrack")}catch(t){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function ya(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){R.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){R.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function Ea(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)e&&t.cues[i].removeEventListener("enter",e),t.removeCue(t.cues[i]);"disabled"===i&&(t.mode=i)}function Ta(t,e,i,s){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,i){const s=[],r=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let s,r=0,n=i;for(;r<=n;)if(s=Math.floor((n+r)/2),e<t[s].startTime)n=s-1;else{if(!(e>t[s].startTime&&r<i))return s;r=s+1}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(t.cues,e,i);for(let e=0;e<r.length;e++)s&&!s(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function Sa(t){const e=[];for(let i=0;i<t.length;i++){const s=t[i];"subtitles"!==s.kind&&"captions"!==s.kind||!s.label||e.push(t[i])}return e}function ba(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}const Aa=.025;let La=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Ia(t,e,i){return`${t.identifier}-${i+1}-${ba(e)}`}class Ra{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const i=this.playoutLimit;if(t<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return ka(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-ka(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,i=e(t)?t:this.duration;return this.cumulativeDuration+i}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return ka(t,e)}return t}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)<Aa))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?La.Range:La.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`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function ka(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<Aa)?e.start:e.start+e.duration}function _a(t,e,i){const s=new self.URL(t,i);return"data:"!==s.protocol&&s.searchParams.set("_HLS_primary_id",e),s}function Da(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function wa(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class Pa{constructor(t,e,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(a.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(a.LEVEL_LOADED,n),r.once(a.AUDIO_TRACK_LOADED,n),r.once(a.SUBTITLE_TRACK_LOADED,n),r.on(a.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(a.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger(a.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=_a(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,r=ze.bufferInfo(t,s,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=ze.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const i=e-this.startOffset;if(i>0&&i<t)return i}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const i=t-e;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=t}}}getAssetTime(t){const e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,i){var s;null==(s=this.hls)||s.on(t,e)}once(t,e,i){var s;null==(s=this.hls)||s.once(t,e)}off(t,e,i){var s;null==(s=this.hls)||s.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${wa(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class Ca extends T{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((i,s)=>t<=s.startOffset&&e>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(e&&"primary"!==e&&(r=r[e]),t===r.start||t>r.start&&t<r.end)return s}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let s=t;s<=e&&i[s];s++){const t=i[s].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return s}return-1}findEventIndex(t){const e=this.items;if(e)for(let s=e.length;s--;){var i;if((null==(i=e[s].event)?void 0:i.identifier)===t)return s}return-1}findAssetIndex(t,e){const i=t.assetList,s=i.length;if(s>1)for(let t=0;t<s;t++){const r=i[t];if(!r.error){const i=r.timelineStart;if(e===i||e>i&&(e<i+(r.duration||0)||t===s-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e){const i=t.main.details,{dateRanges:s}=i,r=this.events,n=this.parseDateRanges(s,{url:i.url},e),a=Object.keys(s),o=r?r.filter(t=>!a.includes(t.identifier)):[];n.length&&n.sort((t,e)=>{const i=t.cue.pre,s=t.cue.post,r=e.cue.pre,n=e.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=t.startTime,s=e.startTime;if(i!==s)return i-s}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=n,o.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,o)}updateSchedule(t,e=[],i=!1){const s=this.events||[];if(s.length||e.length||this.length<2){const r=this.items,n=this.parseSchedule(s,t);(i||e.length||(null==r?void 0:r.length)!==n.length||n.some((t,e)=>Math.abs(t.playout.start-r[e].playout.start)>.005||Math.abs(t.playout.end-r[e].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(e,r))}}parseDateRanges(t,e,i){const s=[],r=Object.keys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new Ra(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),s.push(t)}}return s}parseSchedule(t,e){const i=[],s=e.main.details,r=s.live?1/0:s.edge;let n=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let s=0,o=0;if(t.forEach((e,a)=>{const l=e.cue.pre,d=e.cue.post,h=t[a-1]||null,c=e.appendInPlace,u=d?r:e.startOffset,f=e.duration,g=e.timelineOccupancy===La.Range?f:0,m=e.resumptionOffset,p=(null==h?void 0:h.startTime)===u,v=u+e.cumulativeDuration;let y=c?v+f:u+m;if(l||!d&&u<=0){const t=o;o+=g,e.timelineStart=v;const s=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:s,end:n},integrated:{start:t,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:t[a-1]||null,nextEvent:e,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&&(y=v),e.timelineStart=v;const r=o;o+=g;const l=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const E=e.resumeTime;s=d||E>r?r:E}),s<r){var a;const t=s,e=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:t+l,playout:{start:d,end:n},integrated:{start:e,end:o}})}this.setDurations(r,n,o)}else{const t=0;i.push({previousEvent:null,nextEvent:null,start:t,end:r,playout:{start:t,end:r},integrated:{start:t,end:r}}),this.setDurations(r,r,r)}return i}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,i){const s=i.main.details,r=s.live?1/0:s.edge;let n=0,a=-1;t.forEach((o,l)=>{const d=o.cue.pre,h=o.cue.post,c=d?0:h?r:o.startTime;this.updateAssetDurations(o);if(a===c?o.cumulativeDuration=n:(n=0,a=c),!h&&o.snapOptions.in&&(o.resumeAnchor=ae(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(o,i)||(o.appendInPlace=!1)}if(!o.appendInPlace&&l+1<t.length){t[l+1].startTime-t[l].resumeTime<.033&&(t[l+1].appendInPlace=!1,t[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`))}const u=e(o.resumeOffset)?o.resumeOffset:o.duration;n+=u})}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,s=t.startTime+t.resumptionOffset;if(Math.abs(i-s)>Aa)return this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1;return!Object.keys(e).some(s=>{const r=e[s].details,n=r.edge;if(i>=n)return this.log(`"${t.identifier}" resumption ${i} past ${s} playlist end ${n}`),!1;const a=ae(null,r.fragments,i);if(!a)return this.log(`"${t.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)<Aa+o||Math.abs(a.end-i)<Aa+o)&&(this.log(`"${t.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}t.duration=s&&!r?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function xa(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class Ma{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let s;try{s=_a(i,this.hls.sessionId,t.baseUrl)}catch(e){const s=this.assignAssetListError(t,n.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(a.ERROR,s)}e&&"data:"!==s.protocol&&s.searchParams.set("_HLS_start_offset",""+e);const r=this.hls.config,o=new(0,r.loader)(r),l={responseType:"json",url:s.href},d=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,i,s,r)=>{const o=e.data,l=null==o?void 0:o.ASSETS;if(!Array.isArray(l)){const e=this.assignAssetListError(t,n.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,r);return void this.hls.trigger(a.ERROR,e)}t.assetListResponse=o,this.hls.trigger(a.ASSET_LIST_LOADED,{event:t,assetListResponse:o,networkDetails:r})},onError:(e,i,s,r)=>{const o=this.assignAssetListError(t,n.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,r,s);this.hls.trigger(a.ERROR,o)},onTimeout:(e,i,s)=>{const r=this.assignAssetListError(t,n.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,s);this.hls.trigger(a.ERROR,r)}};return o.load(l,h,c),this.hls.trigger(a.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,e,i,s,n,a){return t.error=i,{type:r.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:s,error:i,networkDetails:a,stats:n}}}function Oa(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function Fa(t,e){return`[${t}] Advancing timeline position to ${e}`}class Na{constructor(t){this.buffered=void 0;const e=(e,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}const Ba={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},Ua=t=>String.fromCharCode(Ba[t]||t),$a=15,Ga=100,Ka={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ha={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Va={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ja={25:2,26:4,29:6,30:8,31:10,27:13,28:15},qa=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ya{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;R.log(`${this.time} [${t}] ${i}`)}}}const Wa=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class za{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(t){const e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){const s=e[i];t.hasOwnProperty(s)&&(this[s]=t[s])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Xa{constructor(){this.uchar=" ",this.penState=new za}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Qa{constructor(t){this.chars=[],this.pos=0,this.currPenState=new za,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ga;t++)this.chars.push(new Xa);this.logger=t}equals(t){for(let e=0;e<Ga;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Ga;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Ga;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ga&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ga)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Ua(t);this.pos>=Ga?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<Ga;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<Ga;i++){const s=this.chars[i].uchar;" "!==s&&(e=!1),t.push(s)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class Za{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<$a;e++)this.rows.push(new Qa(t));this.logger=t}reset(){for(let t=0;t<$a;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<$a;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<$a;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<$a;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+Xt(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<$a;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[t].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[e-this.nrRollUpRows+s+1].copy(i.rows[t+s])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,s=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[s].penState.foreground}const s={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+Xt(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}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 t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",s=-1;for(let i=0;i<$a;i++){const r=this.rows[i].getTextString();r&&(s=i+1,t?e.push("Row "+s+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class Ja{constructor(t,e,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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Za(i),this.nonDisplayedMemory=new Za(i),this.lastOutputScreen=new Za(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(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"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=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+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(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}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 t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=s[i]}this.logger.log(2,"MIDROW: "+Xt(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class to{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new Ya;this.channels=[null,new Ja(t,e,s),new Ja(t+1,i,s)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],s=127&e[t+1];let r=!1,n=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+Wa([e[t],e[t+1]])+"] -> ("+Wa([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(io(i,s,a)){eo(null,null,a),this.logger.log(3,()=>"Repeated command ("+Wa([i,s])+") is dropped");continue}eo(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 eo(null,null,a);if(!r&&(n=this.parseChars(i,s),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+Wa([i,s])+" orig: "+Wa([e[t],e[t+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const i=20===t||21===t||23===t?1:2,s=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?s.ccRCL():33===e?s.ccBS():34===e?s.ccAOF():35===e?s.ccAON():36===e?s.ccDER():37===e?s.ccRU(2):38===e?s.ccRU(3):39===e?s.ccRU(4):40===e?s.ccFON():41===e?s.ccRDC():42===e?s.ccTR():43===e?s.ccRTD():44===e?s.ccEDM():45===e?s.ccCR():46===e?s.ccENM():47===e&&s.ccEOC():s.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?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(e),this.logger.log(3,()=>"MIDROW ("+Wa([t,e])+")"),!0)}return!1}parsePAC(t,e){let i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const s=t<=23?1:2;i=e>=64&&e<=95?1===s?Ka[t]:Va[t]:1===s?Ha[t]:ja[t];const r=this.channels[s];return!!r&&(r.setPAC(this.interpretPAC(i,e)),this.currentChannel=s,!0)}interpretPAC(t,e){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-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(t,e){let i,s=null,r=null;if(t>=25?(i=2,r=t-8):(i=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,()=>"Special char '"+Ua(t)+"' in channel "+i),s=[t]}else t>=32&&t<=127&&(s=0===e?[t]:[t,e]);return s&&this.logger.log(3,()=>"Char codes = "+Wa(s).join(",")),s}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const s={};16===t||24===t?(i=Math.floor((e-32)/2),s.background=qa[i],e%2==1&&(s.background=s.background+"_semi")):45===e?s.background="transparent":(s.foreground="black",47===e&&(s.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(s),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}eo(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function eo(t,e,i){i.a=t,i.b=e}function io(t,e,i){return i.a===t&&i.b===e}var so=function(){if(null!=pi&&pi.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function s(t){return i(e,t)}function r(t,...e){let i=1;for(;i<arguments.length;i++){const e=arguments[i];for(const i in e)t[i]=e[i]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=e,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,b="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(e){const s=function(e){return i(t,e)}(e);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(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return b},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");b=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class ro{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function no(t){function e(t,e,i,s){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(s||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class ao{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let s=0;s<i.length;++s)if(e===i[s]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function oo(t,e,i,s){const r=s?t.split(s):[t];for(const t in r){if("string"!=typeof r[t])continue;const s=r[t].split(i);if(2!==s.length)continue;e(s[0],s[1])}}const lo=new so(0,0,""),ho="middle"===lo.align?"middle":"center";function co(t,e,i){const s=t;function r(){const e=no(t);if(null===e)throw new Error("Malformed timestamp: "+s);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const s=new ao;oo(t,function(t,e){let r;switch(t){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===e){s.set(t,i[r].region);break}break;case"vertical":s.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),s.integer(t,r[0]),s.percent(t,r[0])&&s.set("snapToLines",!1),s.alt(t,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",ho,"end"]);break;case"position":r=e.split(","),s.percent(t,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",ho,"end","line-left","line-right","auto"]);break;case"size":s.percent(t,e);break;case"align":s.alt(t,e,["start",ho,"end","left","right"])}},/:/,/\s/),e.region=s.get("region",null),e.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===lo.line&&(r=-1),e.line=r,e.lineAlign=s.get("lineAlign","start"),e.snapToLines=s.get("snapToLines",!0),e.size=s.get("size",100),e.align=s.get("align",ho);let n=s.get("position","auto");"auto"===n&&50===lo.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function uo(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class fo{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ro,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=uo(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const s=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),s}function s(t){oo(t,function(t,e){},/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=i();const s=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=i(),e.state){case"HEADER":/:/.test(t)?s(t):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new so(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{co(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==t.indexOf("--\x3e");if(!t||i&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const go=/\r\n|\n\r|\n|\r/g,mo=function(t,e,i=0){return t.slice(i,i+e.length)===e};function po(t,e,i){return ba(t.toString())+ba(e.toString())+ba(i)}function vo(t,i,s,r,n,a,o){const l=new fo,d=D(new Uint8Array(t)).trim().replace(go,"\n").split("\n"),h=[],c=i?function(t,e=1){return Br(t,9e4,1/e)}(i.baseTime,i.timescale):0;let u,f="00:00.000",g=0,m=0,p=!0;l.oncue=function(t){const e=s[r];let a=s.ccOffset;const o=(g-c)/9e4;if(null!=e&&e.new&&(void 0!==m?a=s.ccOffset=e.start:function(t,e,i){let s=t[e],r=t[s.prevCC];if(!r||!r.new&&s.new)return t.ccOffset=t.presentationOffset=s.start,void(s.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=s.start-r.start,s.new=!1,s=r,r=t[s.prevCC]}t.presentationOffset=i}(s,r,o)),o){if(!i)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,d=qr(9e4*(t.startTime+a-m),9e4*n)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+l,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id||(t.id=po(t.startTime,t.endTime,f)),t.endTime>0&&h.push(t)},l.onparsingerror=function(t){u=t},l.onflush=function(){u?o(u):a(h)},d.forEach(t=>{if(p){if(mo(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach(t=>{mo(t,"LOCAL:")?f=t.slice(6):mo(t,"MPEGTS:")&&(g=parseInt(t.slice(7)))});try{m=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(e(i)&&e(s)&&e(r)&&e(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*r,i+=36e5*n,i}(f)/1e3}catch(t){u=t}return}""===t&&(p=!1)}l.parse(t+"\n")}),l.flush()}const yo="stpp.ttml.im1t",Eo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,To=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,So={left:"start",center:"center",right:"end",start:"start",end:"end"};function bo(t,e,i,s){const r=J(new Uint8Array(t),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map(t=>D(t)),a=function(t,e,i=1,s=!1){return Br(t,e,1/i,s)}(e.baseTime,1,e.timescale);try{n.forEach(t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"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((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||r[e],t),{}),a="preserve"!==s.getAttribute("xml:space"),o=Lo(Ao(s,"styling","style")),l=Lo(Ao(s,"layout","region")),d=Ao(s,"body","[begin]");return[].map.call(d,t=>{const i=Io(t,a);if(!i||!t.hasAttribute("begin"))return null;const s=_o(t.getAttribute("begin"),n),r=_o(t.getAttribute("dur"),n);let d=_o(t.getAttribute("end"),n);if(null===s)throw ko(t);if(null===d){if(null===r)throw ko(t);d=s+r}const h=new so(s-e,d-e,i);h.id=po(h.startTime,h.endTime,h.text);const c=function(t,e,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce((i,n)=>{const a=Ro(e,s,n)||Ro(t,s,n)||Ro(r,s,n);return a&&(i[n]=a),i},{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:u}=c;if(u){const t=So[u];t&&(h.lineAlign=t),h.align=u}return v(h,c),h}).filter(t=>null!==t)}(t,a)))}catch(t){s(t)}}function Ao(t,e,i){const s=t.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function Lo(t){return t.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function Io(t,e){return[].slice.call(t.childNodes).reduce((t,i,s)=>{var r;return"br"===i.nodeName&&s?t+"\n":null!=(r=i.childNodes)&&r.length?Io(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Ro(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function ko(t){return new Error(`Could not parse ttml timestamp ${t}`)}function _o(t,e){if(!t)return null;let i=no(t);return null===i&&(Eo.test(t)?i=function(t,e){const i=Eo.exec(t),s=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/e.frameRate}(t,e):To.test(t)&&(i=function(t,e){const i=To.exec(t),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/e.frameRate;case"t":return s/e.tickRate}return s}(t,e))),i}class Do{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function wo(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Po(t,e){return!!t&&t.kind===wo(e)&&dn(e,t)}function Co(t,e,i,s){return Math.min(e,s)-Math.max(t,i)}const xo=/\s/,Mo={newCue(t,e,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 t=0;t<n.chars.length;t++)xo.test(n.chars[t].uchar)&&o?l++:(d+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const s=uo(d.trim()),f=po(e,i,s);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new h(e,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 t&&r.length&&(r.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),r.forEach(e=>ya(t,e))),r}};const Oo=/(\d+)-(\d+)\/(\d+)/;class Fo{constructor(t){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=t.fetchSetup||No,this.controller=new self.AbortController,this.stats=new F}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 t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,i,s){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(v({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(t,this.controller.signal),a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=i.loadPolicy;this.context=t,this.config=i,this.callbacks=s,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),i.timeout=l&&e(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))},i.timeout);(tn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(s=>{var n;this.response=this.loader=s;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),i.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))},d-(o-r.loading.start)),!s.ok){const{status:t,statusText:e}=s;throw new Bo(e||"fetch, bad network response",t,s)}r.loading.first=o,r.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const e=Oo.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(i);if(e(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(s.headers)||r.total;const l=null==(n=this.callbacks)?void 0:n.onProgress;return l&&e(i.highWaterMark)?this.loadProgressively(s,r,t,i.highWaterMark,l):a?s.arrayBuffer():"json"===t.responseType?s.json():s.text()}).then(s=>{var n,a;const l=this.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const d=s[o];d&&(r.loaded=r.total=d);const h={url:l.url,data:s,code:l.status},c=null==(n=this.callbacks)?void 0:n.onProgress;c&&!e(i.highWaterMark)&&c(r,t,s,l),null==(a=this.callbacks)||a.onSuccess(h,r,t,l)}).catch(e=>{var i;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=e&&e.code||0,n=e?e.message:null;null==(i=this.callbacks)||i.onError({code:s,text:n},t,e?e.details:null,r)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,r){const n=new Ds,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(e,i,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<s||n.dataLength?(n.push(l),n.dataLength>=s&&r(e,i,n.flush().buffer,t)):r(e,i,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function No(t,e){return new self.Request(t.url,e)}class Bo extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Uo=/^age:\s*[\d.]+\s*$/im;class $o{constructor(t){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=t&&t.xhrSetup||null,this.stats=new F,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)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,e.url)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),r(i,e.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:t.message},e,i,s)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,i,s){t.readyState||t.open("GET",i.url,!0);const r=i.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[e]);i.rangeEnd&&t.setRequestHeader("Range","bytes="+i.rangeStart+"-"+(i.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=i.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&e(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const s=e.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),e.onreadystatechange=null,e.onprogress=null;const s=e.status,l="text"===e.responseType?e.responseText:null;if(s>=200&&s<300){const r=null!=l?l:e.response;if(null!=r){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.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,t,r,e);const d={url:e.responseURL,data:r,code:s};return void(null==(a=this.callbacks)||a.onSuccess(d,i,t,e))}}const d=r.loadPolicy.errorRetry;var o;if(pe(d,i.retry,!1,{url:t.url,data:void 0,code:s}))this.retry(d);else R.error(`${s} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:s,text:e.statusText},t,e,i)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(pe(t,this.stats.retry,!0))this.retry(t);else{var e;R.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=ge(t,i.retry),i.retry++,R.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Uo.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Go=E(E({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:$o,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends T{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:l}=n;if(!s||!l)return;const d=performance.now(),h=r?r.stats:s.stats,c=r?r.duration:s.duration,u=d-h.loading.start,f=n.minAutoLevel,g=s.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!o)return;const p=m>-1&&m!==g,v=!!t||p;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const y=n.mainForwardBufferInfo;if(!v&&null===y)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(u<=Math.max(E,c/(2*T)*1e3))return;const S=y?y.len/T:0,b=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&b>-1,L=this.getBwEstimate(),I=n.levels,R=I[g],k=Math.max(h.loaded,Math.round(c*(s.bitrate||R.averageBitrate)/8));let _=A?u-b:u;_<1&&A&&(_=Math.min(u,8*h.loaded/L));const D=A?1e3*h.loaded/_:0,w=E/1e3,P=D?(k-h.loaded)/D:8*k/L+w;if(P<=S)return;const C=D?8*D:L,x=!0===(null==(i=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:i.live),M=this.hls.config.abrBandWidthUpFactor;let O,F=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){const t=I[O].maxBitrate,e=!I[O].details||x;if(F=this.getTimeToLoadFrag(w,C,c*t,e),F<Math.min(S,c+w))break}if(F>=P)return;if(F>10*c)return;A?this.bwEstimator.sample(u-Math.min(E,b),h.loaded):this.bwEstimator.sampleTTFB(u);const N=I[O].maxBitrate;this.getBwEstimate()*M>N&&this.resetEstimator(N);const B=this.findBestLevel(N,f,O,0,S,1,1);B>-1&&(O=B),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${P.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|b} ms\n Current BW estimate: ${e(L)?0|L:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|N} bps`),n.nextLoadLevel=n.nextAutoLevel=O,this.clearTimer();const U=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===O&&O>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,O>f){let e=this.findBestLevel(this.hls.levels[f].bitrate,f,O,0,t,1,1);-1===e&&(e=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};p||P>2*F?U():this.timer=self.setInterval(U,1e3*F),n.trigger(a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:h})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new m(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(a.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){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(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=e.part)?s:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case n.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:s}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){const e=performance.now(),i=s?s.stats:t.stats,r=e-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,i,s){return t+i/e+(s?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:r}=i.stats,n=r.end-r.first;e(n)&&(this.lastLevelLoadSec=n/1e3),i.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(i.levelInfo)}onFragLoaded(t,{frag:e,part:i}){const s=i?i.stats:e.stats;if(e.type===c&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=i?i.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+s.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(a.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:s}=e,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(t){return t.type!==c||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,e,t,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);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 t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const s=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,s,l,0,d,h);if(t>=0)return this.rebufferNotice=-1,t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}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 t=this.hls,e=t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,i,s,r,n,a,o){var l;const d=r+n,h=this.lastLoadedFragLevel,c=-1===h?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:v}=this.hls;if(1===g.length)return 0;const y=g[c],E=!(null==(l=this.hls.latestLevelDetails)||!l.live),T=-1===p||-1===h;let S,b="SDR",A=(null==y?void 0:y.frameRate)||0;const{audioPreference:L,videoPreference:I}=v,R=this.audioTracksByGroup||(this.audioTracksByGroup=Zt(m));let k=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(t,e,i,s){return t.slice(i,s+1).reduce((t,i,s)=>{if(!i.codecSet)return t;const r=i.audioGroups;let n=t[i.codecSet];n||(t[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(t=>{if(!t)return;const i=e.groups[t];i&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach(t=>{n.channels[t]=(n.channels[t]||0)+i.channels[t]}))}),t},{})}(g,R,i,s)),n=function(t,i,s,r,n){const a=Object.keys(t),o=null==r?void 0:r.channels,l=null==r?void 0:r.audioCodec,d=null==n?void 0:n.videoCodec,h=o&&2===parseInt(o);let c=!1,u=!1,f=1/0,g=1/0,m=1/0,p=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=zt(i,n);for(let e=a.length;e--;){const i=t[a[e]];c||(c=i.channels[2]>0),f=Math.min(f,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter(t=>i.videoRanges[t]>0).length>0&&(u=!0)}f=e(f)?f:0,g=e(g)?g:0;const S=Math.max(1080,f),b=Math.max(30,g);m=e(m)?m:s,s=Math.max(m,s),u||(i=void 0);const A=a.length>1;return{codecSet:a.reduce((e,i)=>{const r=t[i];if(i===e)return e;if(y=u?T.filter(t=>r.videoRanges[t]>0):[],A){if(r.minBitrate>s)return Qt(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return Qt(i,"no renditions with default or auto-select sound found"),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Qt(i,`audio codec preference "${l}" not found`),e;if(o&&!h){if(!r.channels[o])return Qt(i,`no renditions with ${o} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!l||h)&&c&&0===r.channels[2])return Qt(i,"no renditions with stereo sound found"),e;if(r.minHeight>S)return Qt(i,`min resolution of ${r.minHeight} > maximum of ${S}`),e;if(r.minFramerate>b)return Qt(i,`min framerate of ${r.minFramerate} > maximum of ${b}`),e;if(!y.some(t=>r.videoRanges[t]>0))return Qt(i,`no variants with VIDEO-RANGE of ${Xt(y)} found`),e;if(d&&i.indexOf(d.substring(0,4))%5!=0)return Qt(i,`video codec preference "${d}" not found`),e;if(r.maxScore<v)return Qt(i,`max score of ${r.maxScore} < selected max of ${v}`),e}return e&&(Lt(i)>=Lt(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,v=r.maxScore,i)},void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:m,minIndex:p}}(r,b,t,L,I),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:d,minIndex:h,preferHDR:c}=n;k=h,S=a,b=c?o[o.length-1]:o[0],A=l,t=Math.max(t,d),this.log(`picked start tier ${Xt(n)}`)}else S=null==y?void 0:y.codecSet,b=null==y?void 0:y.videoRange;const _=f?f.duration:u?u.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let l=s;l>=i;l--){var P;const i=g[l],u=l>c;if(!i)continue;if(v.useMediaCapabilities&&!i.supportedResult&&!i.supportedPromise){const e=navigator.mediaCapabilities;"function"==typeof(null==e?void 0:e.decodingInfo)&&Ft(i,R,b,A,t,L)?(i.supportedPromise=Nt(i,R,e,this.supportedCache),i.supportedPromise.then(t=>{if(!this.hls)return;i.supportedResult=t;const e=this.hls.levels,s=e.indexOf(i);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${s} ${Xt(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${s} not smooth or powerEfficient: ${Xt(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${Xt(t)}`),s>-1&&e.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):i.supportedResult=Mt}if((S&&i.codecSet!==S||b&&i.videoRange!==b||u&&A>i.frameRate||!u&&A>0&&A<i.frameRate||null!=(P=i.supportedResult)&&null!=(P=P.decodingInfoResults)&&P.some(t=>!1===t.smooth))&&(!T||l!==k)){w.push(l);continue}const m=i.details,y=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||_;let I;I=u?o*t:a*t;const C=_&&r>=2*_&&0===n?i.averageBitrate:i.maxBitrate,x=this.getTimeToLoadFrag(D,I,C*y,void 0===m);if(I>=C&&(l===h||0===i.loadError&&0===i.fragmentError)&&(x<=D||!e(x)||E&&!this.bitrateTestDelay||x<d)){const t=this.forcedAutoLevel;return l===p||-1!==t&&t===p||(w.length&&this.trace(`Skipped level(s) ${w.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[w[0]].codecs}" ${g[w[0]].videoRange}; not compatible with "${S}" ${b}`),this.info(`switch candidate:${c}->${l} adjustedbw(${Math.round(I)})-bitrate=${Math.round(I-C)} ttfb:${D.toFixed(1)} avgDuration:${y.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${T} codecSet:${i.codecSet} videoRange:${i.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=l),l}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}},bufferController:class extends T{constructor(t,e){var i;super("buffer-controller",t.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=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:i}=this;t&&this.log("Media source opened"),e&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(a.MEDIA_ATTACHED,{media:e,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:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(i=k(t.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:t}=this;t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.BUFFER_EOS,this.onBufferEos,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.FRAG_PARSED,this.onFragParsed,this),t.on(a.FRAG_CHANGED,this.onFragChanged,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_EOS,this.onBufferEos,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.FRAG_PARSED,this.onFragParsed,this),t.off(a.FRAG_CHANGED,this.onFragChanged,this),t.off(a.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===e?v(i,s.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(i[e]=v({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,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(t,e){var i;let s=2;(e.audio&&!e.video||!e.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(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const s=k(this.appendSource);if(s){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(r),t)this._objectUrl=i.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&r instanceof e,gn(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,i;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(i=t.constructor)?void 0:i.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,s=e.tracks,r=s?Object.keys(s):null,n=r?r.length:0,o=()=>{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: ${Xt(i,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${Xt(s,(t,e)=>"initSegment"===t?void 0:e)}}`),!_(s,i)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,o=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return o-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${o}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${o} currentTime: ${r}`),this.onMediaDetaching(a.MEDIA_DETACHING,{}),this.onMediaAttaching(a.MEDIA_ATTACHING,e),void(t.currentTime=o))}this.transferData=void 0,r.forEach(t=>{const e=t,i=s[e];if(i){const t=i.buffer;if(t){const s=this.fragmentTracker,r=i.id;if(s.hasFragments(r)||s.hasParts(r)){const i=ze.getBuffered(t);s.detectEvictedFragments(e,i,r,null,!0)}const n=mn(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,i)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const i=!!e.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(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),r.removeSourceBuffer(e[i]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.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&&gn(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(a.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[mn(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new hn(this.tracks)}onBufferCodecs(t,e){var i;const s=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(t=>!s[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var i,r;const n=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:c}=n;let u=s[t];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[t],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[t]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:d,levelCodec:l,metadata:h,id:a});const v=_t(m,p),y=null==v?void 0:v.replace(cn,"$1");let E=_t(o,l);const T=null==(r=E)?void 0:r.replace(cn,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=kt(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=d,this.appendChangeType(t,d,E))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(i=e.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((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){const s=`${e};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),n.changeType(s),r.codec=i,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,s=i+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,c))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>s||null!=e&&e.buffer&&ze.isBuffered(e.buffer,s)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,c))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:r,frag:t},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,i){const{tracks:s}=this,{data:o,type:l,parent:d,frag:h,part:u,chunkMeta:f,offset:g}=i,m=f.buffering[l],{sn:p,cc:v}=h,y=self.performance.now();m.start=y;const E=h.stats.buffering,T=u?u.stats.buffering:null;0===E.start&&(E.start=y),T&&0===T.start&&(T.start=y);const S=s.audio;let b=!1;"audio"===l&&"audio/mpeg"===(null==S?void 0:S.container)&&(b=!this.lastMpegAudioChunk||1===f.id||this.lastMpegAudioChunk.sn!==f.sn,this.lastMpegAudioChunk=f);const A=s.video,L=null==A?void 0:A.buffer;if(L&&"initSegment"!==p){const t=u||h,e=this.blockedAudioAppend;if("audio"!==l||"main"===d||this.blockedAudioAppend||A.ending||A.ended){if("video"===l){const i=t.end;if(e){const t=e.frag.start;(i>t||i<this.lastVideoAppendEnd||ze.isBuffered(L,t))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const e=t.start+.05*t.duration,i=L.buffered,s=this.currentOp("video");i.length||s?!s&&!ze.isBuffered(L,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const I=(u||h).start,R={label:`append-${l}`,execute:()=>{var t;m.executeStart=self.performance.now();const i=null==(t=this.tracks[l])?void 0:t.buffer;i&&(b?this.updateTimestampOffset(i,I,.1,l,p,v):void 0!==g&&e(g)&&this.updateTimestampOffset(i,g,1e-6,l,p,v)),this.appendExecutor(o,l)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();m.executeEnd=m.end=t,0===E.first&&(E.first=t),T&&0===T.first&&(T.first=t);const e={};this.sourceBuffers.forEach(([t,i])=>{t&&(e[t]=ze.getBuffered(i))}),this.appendErrors[l]=0,"audio"===l||"video"===l?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(a.BUFFER_APPENDED,{type:l,frag:h,part:u,chunkMeta:f,parent:h.type,timeRanges:e})},onError:t=>{var e;const i={type:r.MEDIA_ERROR,parent:h.type,details:n.BUFFER_APPEND_ERROR,sourceBufferName:l,frag:h,part:u,chunkMeta:f,error:t,err:t,fatal:!1},s=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)i.details=n.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!s)i.errorAction=Re(!0);else if(t.name===un&&0===this.sourceBufferCount)i.errorAction=Re(!0);else{const t=++this.appendErrors[l];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${l}" sourceBuffer (${s||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}this.hls.trigger(a.ERROR,i)}};this.log(`queuing "${l}" append sn: ${p}${u?" p: "+u.index:""} of ${h.type===c?"level":"track"} ${h.level} cc: ${v}`),this.append(R,l,this.isPending(this.tracks[l]))}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(a.BUFFER_FLUSHED,{type:t})},onError:s=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,s)}}}onBufferFlushing(t,e){const{type:i,startOffset:s,endOffset:r}=e;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,s,r),t)})}onFragParsed(t,e){const{frag:i,part:s}=e,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[U]?r.push("audiovideo"):(n[N]&&r.push("audio"),n[B]&&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 t=self.performance.now();i.stats.buffering.end=t,s&&(s.stats.buffering.end=t);const e=s?s.stats:i.stats;this.hls.trigger(a.FRAG_BUFFERED,{frag:i,part:s,stats:e,id:i.type})},r).catch(t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(([t])=>{if(t){const i=this.tracks[t];e.type&&e.type!==t||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${t} buffer reached EOS`)))}});const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(a.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(a.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,i){if(i.details===n.BUFFER_APPEND_ERROR&&i.frag){var s;const t=null==(s=i.errorAction)?void 0:s.nextAutoLevel;e(t)&&t!==i.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:i,media:s}=this;if(!s||null===i)return;if(!this.sourceBufferCount)return;const r=t.config,n=s.currentTime,a=i.levelTargetDuration,o=i.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(e(o)&&o>=0){const t=Math.max(o,a),e=Math.floor(n/a)*a-t;this.flushBackBuffer(n,a,e)}const l=r.frontBufferFlushThreshold;if(e(l)&&l>0){const t=Math.max(r.maxBufferLength,l),e=Math.max(t,a),i=Math.floor(n/a)*a+e;this.flushFrontBuffer(n,a,i)}}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([t,e])=>{if(e){const r=ze.getBuffered(e);if(r.length>0&&i>r.start(0)){var s;this.hls.trigger(a.BACK_BUFFER_REACHED,{bufferEnd:i});const e=this.tracks[t];if(null!=(s=this.details)&&s.live)this.hls.trigger(a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([e,s])=>{if(s){const r=ze.getBuffered(s),n=r.length;if(n<2)return;const o=r.start(n-1),l=r.end(n-1);if(i>o||t>=o&&t<=l)return;this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:i,mediaSource:s}=this;if(!i||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const r=i.edge;if(i.live&&this.hls.config.liveDurationInfinity){if(i.fragments.length&&s.setLiveSeekableRange){const t=Math.max(0,i.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,r)}}return{duration:1/0}}const n=null==(t=this.overrides)?void 0:t.duration;if(n)return e(n)?{duration:n}:null;const a=this.media.duration;return r>(e(s.duration)?s.duration:0)&&r>a||!e(a)?{duration:r}:null}updateMediaSource({duration:t,start:i,end:s}){const r=this.mediaSource;this.media&&r&&"open"===r.readyState&&(r.duration!==t&&(e(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),r.duration=t),void 0!==i&&void 0!==s&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${i}-${s}.`),r.setLiveSeekableRange(i,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Xt(i)}`),this.tracksReady){var s;const t=null==(s=this.transferData)?void 0:s.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,i])=>{if(e){const s=this.tracks[e];t[e]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(a.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const o in t){const l=o,d=t[l];if(this.isPending(d)){const t=this.getTrackCodec(d,l),o=`${d.container};codecs=${t}`;d.codec=t,this.log(`creating sourceBuffer(${o})${this.currentOp(l)?" Queued":""} ${Xt(d)}`);try{const t=i.addSourceBuffer(o),s=mn(l),r=[l,t];e[s]=r,d.buffer=t}catch(t){var s;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(l),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[l],void this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:l,mimeType:o,parent:d.id})}this.trackSourceBuffer(l,d)}}this.bufferCreated()}getTrackCodec(t,e){const i=t.supplemental;let s=t.codec;i&&("video"===e||"audiovideo"===e)&&Tt(i,"video")&&(s=function(t,e){const i=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)Et(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(s,i));const r=_t(s,t.levelCodec);return r?"audio"===e.slice(0,5)?kt(r,this.appendSource):r:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const s=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:s,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(a.BUFFER_FLUSHED,{type:t})})}get mediaSrc(){var t,e;const i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const i=this.currentOp(t);i&&(i.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var i;const s=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,e),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:s,fatal:!1});const o=this.currentOp(t);o&&o.onError(s)}updateTimestampOffset(t,e,i,s,r,n){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,i,s){const{media:r,mediaSource:n}=this,a=this.tracks[t],o=null==a?void 0:a.buffer;if(!r||!n||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const l=e(r.duration)?r.duration:1/0,d=e(n.duration)?n.duration:1/0,h=Math.max(0,i),c=Math.min(s,l,d);c>h&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${h},${c}] from the ${t} SourceBuffer`),o.remove(h,c)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.tracks[e],s=null==i?void 0:i.buffer;if(!s)throw new fn(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,s=e.map(t=>this.appendBlocker(t));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;i&&!i.updating&&this.shiftAndExecuteNext(t)})}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,i){const s=this.tracks[t];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,t);s.listeners.push({event:e,listener:n}),r.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(t=>{i.removeEventListener(t.event,t.listener)}),e.listeners.length=0)}},capLevelController:pn,errorController:class extends T{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.ERROR,this.onError,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.ERROR,this.onError,this),t.off(a.ERROR,this.onErrorOut,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===c?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,i=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===i?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if(null!=(i=t.details)&&i.hasKey(e))return!0;const s=t.audioGroups;if(s){return this.hls.allAudioTracks.filter(t=>s.indexOf(t.groupId)>=0).some(t=>{var i;return null==(i=t.details)?void 0:i.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const s=this.hls,a=e.context;switch(e.details){case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case n.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=Re());case n.FRAG_GAP:case n.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ee);case n.LEVEL_EMPTY_ERROR:case n.LEVEL_PARSING_ERROR:{var o;const t=e.parent===c?e.level:s.loadLevel;e.details===n.LEVEL_EMPTY_ERROR&&null!=(o=e.context)&&null!=(o=o.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case n.LEVEL_LOAD_ERROR:case n.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==a?void 0:a.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level)));case n.AUDIO_TRACK_LOAD_ERROR:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.SUBTITLE_LOAD_ERROR:case n.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const t=s.loadLevelObj;if(t&&(a.type===d&&t.hasAudioGroup(a.groupId)||a.type===h&&t.hasSubtitleGroup(a.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=Ee,void(e.errorAction.flags=Ae)}return;case n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:Ee,flags:Le});case n.KEY_SYSTEM_SESSION_UPDATE_FAILED:case n.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case n.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:Ee,flags:Ie});case n.BUFFER_ADD_CODEC_ERROR:case n.REMUX_ALLOC_ERROR:case n.BUFFER_APPEND_ERROR:var l;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(l=e.level)?l:s.loadLevel);return;case n.INTERNAL_EXCEPTION:case n.BUFFER_APPENDING_ERROR:case n.BUFFER_FULL_ERROR:case n.LEVEL_SWITCH_ERROR:case n.BUFFER_STALLED_ERROR:case n.BUFFER_SEEK_OVER_HOLE:case n.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=Re())}e.type===r.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=Re())}getPlaylistRetryOrSwitchAction(t,e){const i=fe(this.hls.config.playlistLoadPolicy,t),s=this.playlistError++;if(pe(i,s,he(t),t.response))return{action:Se,flags:be,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(t,e);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=e.config,o=fe(ce(t)?a:r,t),l=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(s&&(t.details!==n.FRAG_GAP&&s.fragmentError++,!ue(t))){if(pe(o,l,he(t),t.response))return{action:Se,flags:be,retryConfig:o,retryCount:l}}const d=this.getLevelSwitchAction(t,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var r,a;const e=t.details;s.loadError++,e===n.BUFFER_APPEND_ERROR&&s.fragmentError++;let g=-1;const{levels:m,loadLevel:p,minAutoLevel:v,maxAutoLevel:y}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const E=null==(r=t.frag)?void 0:r.type,T=(E===u&&e===n.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===n.BUFFER_ADD_CODEC_ERROR||e===n.BUFFER_APPEND_ERROR))&&m.some(({audioCodec:t})=>s.audioCodec!==t),S="video"===t.sourceBufferName&&(e===n.BUFFER_ADD_CODEC_ERROR||e===n.BUFFER_APPEND_ERROR)&&m.some(({codecSet:t,audioCodec:e})=>s.codecSet!==t&&s.audioCodec===e),{type:b,groupId:A}=null!=(a=t.context)?a:{};for(let i=m.length;i--;){const r=(i+p)%m.length;if(r!==p&&r>=v&&r<=y&&0===m[r].loadError){var o,l;const i=m[r];if(e===n.FRAG_GAP&&E===c&&t.frag){const e=m[r].details;if(e){const i=ae(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(b===d&&i.hasAudioGroup(A)||b===h&&i.hasSubtitleGroup(A))continue;if(E===u&&null!=(o=s.audioGroups)&&o.some(t=>i.hasAudioGroup(t))||E===f&&null!=(l=s.subtitleGroups)&&l.some(t=>i.hasSubtitleGroup(t))||T&&s.audioCodec===i.audioCodec||S&&s.codecSet===i.codecSet||!T&&s.codecSet!==i.codecSet)continue}g=r;break}}if(g>-1&&i.loadLevel!==g)return t.levelRetry=!0,this.playlistError=0,{action:Ee,flags:be,nextAutoLevel:g}}return{action:Ee,flags:Ae}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case ye:break;case Ee:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===n.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:s}=i,r=i.nextAutoLevel;switch(s){case be:this.switchLevel(t,r);break;case Le:{const s=this.getVariantLevelIndex(t.frag),r=e.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){e.maxHdcpLevel=$t[$t.indexOf(n)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case Ie:{const e=t.decryptdata;if(e){const s=this.hls.levels,r=s.length;for(let i=r;i--;){var n,a;if(this.variantHasKey(s[i],e))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=t.frag)?void 0:a.type} fragment) ${w(e.keyId||[])}`),s[i].fragmentError++,s[i].loadError++,this.log(`Removing level ${i} with key error (${t.error})`),this.hls.removeLevel(i)}const o=t.frag;if(this.hls.levels.length<r)i.resolved=!0;else if(o&&o.type!==c){const t=o.decryptdata;t&&!e.matches(t)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(t,r)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===n.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Ct(t.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${s} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(s))}}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(a.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(a.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const t=s-this.lastTime,r=i-this.lastDroppedFrames,n=e-this.lastDecodedFrames,o=1e3*r/t,l=this.hls;if(l.trigger(a.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),o>0&&r>l.config.fpsDroppedMonitoringThreshold*n){let t=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=t)&&(t-=1,l.trigger(a.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:l.currentLevel}),l.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.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:Ii,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:Mo,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 ks{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",f),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=ps,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:s}=e;if(this.fragContextChanged(i)||(G(i)&&(this.fragPrevious=i),this.state=ps),!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let t=0;t<r.length;t++)if(a>=r[t].start&&a<=r[t].end){n=r[t];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(t,e){const{startOffset:i,endOffset:s}=e;if(0===i&&s!==Number.POSITIVE_INFINITY){const t=s-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{for(let i=0;i<e.length;)if(e[i].end<=t)e.shift();else{if(!(e[i].start<t))break;e[i].start=t,i++}}),this.fragmentTracker.removeFragmentsInRange(i,t,f)}}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===f&&(e.details===n.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ms&&(this.state=ps))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&on(this.levels,e)?this.levels=e.map(t=>new Yt(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new Yt(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,f),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.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!==ms&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:o}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${o}`);const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(n.live||null!=(i=l.details)&&i.live){if(n.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);const e=t.fragments[0];var h;if(l.details)d=this.alignPlaylists(n,l.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===d&&e&&(d=e.start,Ji(n,d));else n.hasProgramDateTime&&t.hasProgramDateTime?(cs(n,t),d=n.fragmentStart):e&&(d=e.start,Ji(n,d));t&&!this.startFragRequested&&this.setStartPosition(t,d)}if(l.details=n,this.levelLastLoaded=l,o===s&&(this.hls.trigger(a.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===ps)){ae(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,s=e.decryptdata,o=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&hi(s.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,ci(s.method)).catch(t=>{throw o.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(i=>{const s=performance.now();o.trigger(a.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:s}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=ps})}}doTick(){if(this.media){if(this.state===ps){const{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;if(this.waitForLive(i))return;const{config:s}=this,r=this.getLoadPosition(),n=ze.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 t=s.maxFragLookUpTolerance,e=a>c-t?0:t;u=ae(f,d,Math.max(d[0].start,a),e),!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)===ke&&(u=g),this.fragmentTracker.getState(u)===ke){const t=this.mapToInitFragWhenRequired(u);t&&this.loadFragment(t,i,a)}}}else this.state=ps}loadFragment(t,e,i){G(t)?super.loadFragment(t,e,i):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new Na(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends an{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Sa(this.media.textTracks);for(let i=0;i<e.length;i++)if("hidden"===e[i].mode)t=e[i];else if("showing"===e[i].mode){t=e[i];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.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(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const i=this.media;if(!i)return;const s=!!e.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;Sa(i.textTracks).forEach(t=>{Ea(t)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,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=e.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.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(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!i||-1!==i.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const i=te(e,t);if(i>-1)r=t[i];else{const t=te(e,this.tracks);r=this.tracks[t]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(a.SUBTITLE_TRACKS_UPDATED,n),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const r=e[s];if((!i||r.default)&&(i||t)&&(!t||ee(r,t)))return s}if(t){for(let i=0;i<e.length;i++){const s=e[i];if(ln(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(ln(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){if(dn(e[i],t))return i}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==h||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&ee(t,i))return i;const s=te(t,this.tracksInGroup);if(s>-1){const t=this.tracksInGroup[s];return this.setSubtitleTrack(s),t}if(i)return null;{const i=te(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,o=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(a.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Sa(t.textTracks),i=this.currentTrack;let s;if(i&&(s=e.filter(t=>dn(i,t))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach(t=>{"disabled"!==t.mode&&t!==s&&(t.mode="disabled")}),s){const t=this.subtitleDisplay?"showing":"hidden";s.mode!==t&&(s.mode=t)}}setSubtitleTrack(t){const i=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=i.length||!e(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,r=i[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t});const n=!!r.details&&!r.details.live;if(t===this.trackId&&r===s&&n)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:o,groupId:l="",name:d,type:h,url:c}=r;this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:d,type:h,url:c});const u=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(u)}},timelineController:class{constructor(t){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=t,this.config=t.config,this.Cues=t.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}},t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Do(this,"textTrack1"),e=new Do(this,"textTrack2"),i=new Do(this,"textTrack3"),s=new Do(this,"textTrack4");this.cea608Parser1=new to(1,t,e),this.cea608Parser2=new to(3,i,s)}addCues(t,e,i,s,r){let n=!1;for(let t=r.length;t--;){const s=r[t],a=Co(s[0],s[1],e,i);if(a>=0&&(s[0]=Math.min(s[0],e),s[1]=Math.max(s[1],i),n=!0,a/(i-e)>.5))return}if(n||r.push([e,i]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,i,s)}else{const r=this.Cues.newCue(null,e,i,s);this.hls.trigger(a.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r,trackId:n}){const{unparsedVttFrags:o}=this;i===c&&(this.initPTS[e.cc]={baseTime:s,timescale:r,trackId:n}),o.length&&(this.unparsedVttFrags=[],o.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(a.FRAG_LOADED,t):this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(Po(r,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:s}=this,{label:r,languageCode:n}=e[t],a=this.getExistingTrack(r,n);if(a)i[t]=a,Ea(i[t]),va(i[t],s);else{const e=this.createTextTrack("captions",r,n);e&&(e[t]=!0,i[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(t,e,i){const s=this.media;if(s)return s.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(t=>{Ea(s[t]),delete s[t]}),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:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)Ea(e[t])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],s=i.some(t=>t.textCodec===yo);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(on(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const t=this.media,e=t?Sa(t.textTracks):null;if(this.tracks.forEach((t,i)=>{let s;if(e){let i=null;for(let s=0;s<e.length;s++)if(e[s]&&Po(e[s],t)){i=e[s],e[s]=null;break}i&&(s=i)}if(s)Ea(s);else{const e=wo(t);s=this.createTextTrack(e,t.name,t.lang),s&&(s.mode="disabled")}s&&this.textTracks.push(s)}),null!=e&&e.length){const t=e.filter(t=>null!==t).map(t=>t.label);t.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const i=`textTrack${e[1]}`,s=this.captionsProperties[i];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===c){var i,s;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(s=e.part)?void 0:s.index)?i:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:s}=e;if(i.type===f)if(s.byteLength){const t=i.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=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),t&&t.textCodec===yo?this._parseIMSC1(i,s):this._parseVTTs(e)}}else this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;bo(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),i.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{i.logger.log(`Failed to parse IMSC1: ${e}`),i.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[i.cc]&&-1===o)return void n.push(t);const l=this.hls;vo(null!=(e=i.initSegment)&&e.data?dt(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,t=>{this._appendCues(t,i.level),l.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(i,s),l.logger.log(`Failed to parse VTT cue: ${e}`),r&&o>i.cc||l.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})})}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||bo(e,this.initPTS[t.cc],()=>{i.textCodec=yo,this._parseIMSC1(t,e)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach(t=>ya(i,t))}else{const s=this.tracks[e];if(!s)return;const r=s.default?"default":"subtitles"+e;i.trigger(a.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===f&&this.onFragLoaded(a.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=e;if(i.type!==c||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<s.length;t++){const e=s[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(e);this.cea608Parser1.addData(s[t].pts,i[0]),this.cea608Parser2.addData(s[t].pts,i[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!r||"video"===r){const{captionsTracks:t}=this;Object.keys(t).forEach(s=>Ta(t[s],e,i))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==s){const{textTracks:t}=this;Object.keys(t).forEach(i=>Ta(t[i],e,s))}}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let s=2;for(let r=0;r<i;r++){const i=t[s++],r=127&t[s++],n=127&t[s++];if(0===r&&0===n)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},audioStreamController:class extends ks{constructor(t,e,i){super(t,e,i,"audio-stream-controller",u),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:t}=this;t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r,trackId:n}){if(i===c){const t=e.cc,i=this.fragCurrent;if(this.initPTS[t]={baseTime:s,timescale:r,trackId:n},this.log(`InitPTS for cc: ${t} found from main: ${s/r} (${s}/${r}) trackId: ${n}`),this.mainAnchor=e,this.state===Is){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==t)&&this.syncWithAnchor(e,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==t?(i.abortRequests(),this.syncWithAnchor(e,i)):this.state===ps&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const s=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==s?void 0:s.cc)===e.cc)return;const r=(s||t).cc,n=de(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===ps&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=ms);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=ps):this.state=Ts,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case ps:this.doTickIdle();break;case Ts:{const{levels:t,trackId:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=Is}break}case Es:this.checkRetryDate();break;case Is:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:s,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=ys;const t={frag:e,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=ps}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:i,media:s,trackId:r}=this,n=e.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[r])return;const o=i[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l))return this.state=Ts,void(this.startFragRequested=!1);const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,N,u));const h=this.getFwdBufferInfo(d,u);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,l))return e.trigger(a.BUFFER_EOS,{type:"audio"}),void(this.state=As);const f=h.len,g=e.maxBufferLength,m=l.fragments,p=m[0].start,v=this.getLoadPosition(),y=this.flushing?v:h.end;if(this.switchingTrack&&s){const t=v;l.PTSKnown&&t<p&&(h.end>p||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=p+.05)}if(f>=g&&!this.switchingTrack&&y<m[m.length-1].start)return;let E=this.getNextFragment(y,l);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,l,h,c,g)),!E)return void(this.bufferFlushed=!0);let T=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&G(E)&&!E.endList&&(!l.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===we&&(this.mainFragLoading=T=null),T&&G(T))){if(E.start>T.end){const t=this.fragmentTracker.getFragAtPos(y,c);t&&t.end>T.end&&(T=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(E.start>T.end)return}this.loadFragment(E,o,y)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Yt(t))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==ms&&(this.setInterval(100),this.state=ps,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(a.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:s}=this,{details:r,id:n,groupId:o,track:l}=e;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${l.name}" of "${o}"`);const d=this.mainDetails;if(!d||r.endCC>d.endCC||d.expired)return this.cachedTrackLoadedData=e,void(this.state!==ms&&(this.state=Ts));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=s[n];let c=0;if(r.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;if(h.details)c=this.alignPlaylists(r,h.details,null==(u=this.levelLastLoaded)?void 0:u.details);r.alignedSliding||(hs(r,d),r.alignedSliding||cs(r,d),c=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(a.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==Ts||this.waitForCdnTuneIn(r)||(this.state=ps),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{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 nn(this.hls,u,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],g=null==(e=i.initSegment)?void 0:e.data;if(void 0!==f){const t=!1,e=s?s.index:-1,n=-1!==e,a=new Ye(i.level,i.sn,i.stats.chunkCount,r.byteLength,e,n);c.push(r,g,h,"",i,s,d.totalduration,t,a,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Ds,complete:!1};t.push(new Uint8Array(r)),this.state!==ms&&(this.state=Is)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===c&&G(e.frag)&&(this.mainFragLoading=e,this.state===ps&&this.tick())}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type===u)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(G(i)){this.fragPrevious=i;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(a.AUDIO_TRACK_SWITCHED,E({},t)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==c||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var i;if(e.fatal)this.state=Ls;else switch(e.details){case n.FRAG_GAP:case n.FRAG_PARSING_ERROR:case n.FRAG_DECRYPT_ERROR:case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(u,e);break;case n.AUDIO_TRACK_LOAD_ERROR:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ts||(null==(i=e.context)?void 0:i.type)!==d||(this.state=ps);break;case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case n.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case n.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==B&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==B){this.flushing=!1,this.bufferFlushed=!0,this.state===As&&(this.state=ps);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,u),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,o=this.getCurrentContext(n);if(!o)return void this.resetWhenMissingContext(n);const{frag:l,part:d,level:h}=o,{details:c}=h,{audio:u,text:f,id3:g,initSegment:m}=r;if(!this.fragContextChanged(l)&&c){if(this.state=Ss,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){const t=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(h,m.tracks,t,n),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:m.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=u;d&&(d.elementaryStreams[N]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(N,t,e,i,s),this.bufferFragmentData(u,l,d,n)}if(null!=g&&null!=(e=g.samples)&&e.length){const t=v({id:i,frag:l,details:c},g);s.trigger(a.FRAG_PARSING_METADATA,t)}if(f){const t=v({id:i,frag:l,details:c},f);s.trigger(a.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(l)}_bufferInitSegment(t,e,i,s){if(this.state!==Ss)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=u;const n=t.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(a.BUFFER_CODECS,e);const o=r.initSegment;if(null!=o&&o.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(a.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||s===ke||s===De)if(G(t))if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Is;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&cs(e.details,i)}else super.loadFragment(t,e,i);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;ee({name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},t,ie)||(re(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(a.AUDIO_TRACK_SWITCHED,E({},t))}},audioTrackController:class extends an{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.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(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,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=e.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,s=this.groupIds;let o=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!i||-1!==i.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!o&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!o&&e){const i=te(e,t,ie);if(i>-1)o=t[i];else{const t=te(e,this.tracks);o=this.tracks[t]}}let s=this.findTrackId(o);-1===s&&o&&(s=this.findTrackId(null));const d={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(a.AUDIO_TRACKS_UPDATED,d);const h=this.trackId;if(-1!==s&&-1===h)this.setAudioTrack(s);else if(t.length&&-1===h){var l;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(l=this.groupIds)?void 0:l.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==d||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&ee(t,s,ie))return s;const r=te(t,this.tracksInGroup,ie);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(s){let s=e.loadLevel;-1===s&&(s=e.firstAutoLevel);const r=function(t,e,i,s,r){const n=e[s],a=e.reduce((t,e,i)=>{const s=e.uri;return(t[s]||(t[s]=[])).push(i),t},{})[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=se(e,s,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==d)return!1;const s=e.audioGroups,n=i.filter(t=>!s||-1!==s.indexOf(t.groupId));return te(t,n,r)>-1});return h>-1?h:se(e,s,e=>{const s=e.audioGroups,n=i.filter(t=>!s||-1!==s.indexOf(t.groupId));return te(t,n,r)>-1})}(t,e.levels,i,s,ie);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=te(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t],r=s.details&&!s.details.live;if(t===this.trackId&&s===i&&r)return;if(this.log(`Switching to audio-track ${t} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=t,this.currentTrack=s,this.hls.trigger(a.AUDIO_TRACK_SWITCHING,E({},s)),r)return;const n=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if((!this.selectDefaultTrack||s.default)&&(!t||ee(t,s,ie)))return i}if(t){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(ee({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],ie))return t}for(let i=0;i<e.length;i++){const s=e[i];if(ln(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(ln(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&re(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,o=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(a.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}},emeController:ua,cmcdController:class{constructor(t){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=t=>{try{this.apply(t,{ot:vn.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:e,part:i}=t,s=this.hls.levels[e.level],r=this.getObjectType(e),n={d:1e3*(i||e).duration,ot:r};r!==vn.VIDEO&&r!==vn.AUDIO&&r!=vn.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(e);null!=a&&a.url&&a.url!==e.url&&(n.nor=a.url),this.apply(t,n)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;null!=i&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||t.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHED,this.onMediaDetached,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHED,this.onMediaDetached,this),t.off(a.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(t,e){this.media=e.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(t,e){var i,s;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=e.tracks.video)?void 0:s.buffer}createData(){var t;return{v:1,sf:yn.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){v(e,this.createData());const i=e.ot===vn.INIT||e.ot===vn.VIDEO||e.ot===vn.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:s}=this;s&&(e=Object.keys(e).reduce((t,i)=>(s.includes(i)&&(t[i]=e[i]),t),{}));const r={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),aa(t.headers,e,r)):t.url=da(t.url,e,r)}getNextFrag(t){var e;const i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){const e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;const{index:i,fragment:s}=t,r=null==(e=this.hls.levels[s.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=s;for(let e=r.length-1;e>=0;e--){const s=r[e];if(s.index===i&&s.fragment.sn===t)return r[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?vn.TIMED_TEXT:"initSegment"===t.sn?vn.INIT:"audio"===e?vn.AUDIO:"main"===e?this.hls.audioTracks.length?vn.VIDEO:vn.MUXED:void 0}getTopBandwidth(t){let e,i=0;const s=this.hls;if(t===vn.AUDIO)e=s.audioTracks;else{const t=s.maxAutoLevel,i=t>-1?t+1:s.levels.length;e=s.levels.slice(0,i)}return e.forEach(t=>{t.bitrate>i&&(i=t.bitrate)}),i>0?i:NaN}getBufferLength(t){const e=this.media,i=t===vn.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!e)return NaN;return 1e3*ze.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}},contentSteeringController:class extends T{constructor(t){super("content-steering",t.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=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}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(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}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(t,e){const{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===Ee&&i.flags===Ae){const t=this.levels;let s=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:i,pathwayId:s,type:n}=e.context;i&&t?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&t&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r),e.details!==n.BUFFER_APPEND_ERROR||e.fatal?i.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${Xt(s)} penalized: ${Xt(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(t=>{s-i[t]>3e5&&delete i[t]});for(let s=0;s<t.length;s++){const r=t[s];if(r in i)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,o=this.hls.levels[n];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,rs(e),this.hls.trigger(a.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];o&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(e===d&&s[i].hasAudioGroup(t)||e===h&&s[i].hasSubtitleGroup(t))return s[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new si(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(i[e.AUDIO]=n,e.AUDIO=n),o&&(s[e.SUBTITLES]=o,e.SUBTITLES=o);const l=ca(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Yt({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${r}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${r}`);return d});e.push(...o),ha(this.audioTracks,i,a,r),ha(this.subtitleTracks,s,a,r)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let s;this.loader&&this.loader.destroy(),this.loader=new i(e);try{s=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==s.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+t)}const r={responseType:"json",url:s.href},n=e.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(t,e,i,r)=>{this.log(`Loaded steering manifest: "${s}"`);const n=t.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":o,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":d}=n;if(o)try{this.uri=new self.URL(o,s).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`)}this.scheduleRefresh(this.uri||i.url),l&&this.clonePathways(l);const h={steeringManifest:n,url:s.toString()};this.hls.trigger(a.STEERING_MANIFEST_LOADED,h),d&&this.updatePathwayPriority(d)},onError:(t,e,i,s)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,d)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}},interstitialsController:class extends T{constructor(t,e){super("interstitials",t.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 t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const i=e<=-.01;this.timelinePos=t,this.bufferedPos=t;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&t<s.start||t>=s.end){var r;const e=this.findItemIndex(s);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(s)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(s)){const e=s.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(i&&t<a||t>=a+o)&&(null!=(l=s.event)&&l.appendInPlace&&(this.clearAssetPlayers(s.event,s),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const i=this.playingAsset;if(!i)return;t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{const i=this.schedule;if(!i)return;const s=this.playingItem,r=i.events||[],n=i.items||[],o=i.durations,l=t.map(t=>t.identifier),d=!(!r.length&&!l.length);(d||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(t=>xa(t))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let h=null,c=null;s&&(h=this.updateItem(s,this.timelinePos),this.itemsMatch(s,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const u=this.bufferingItem;if(u&&(c=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,c)?this.bufferingItem=c:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(s){Math.abs(i)>Aa&&this.warn(`${s} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}}),d||e){if(this.hls.trigger(a.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:o,removedIds:l}),this.isInterstitial(s)&&l.includes(s.event.identifier))return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);s&&this.trimInPlace(h,s),u&&c!==h&&this.trimInPlace(c,u),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new Ma(t),this.schedule=new Ca(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(a.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(a.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(a.MEDIA_ENDED,this.onMediaEnded,this),t.on(a.ERROR,this.onError,this),t.on(a.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(a.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(a.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(a.MEDIA_ENDED,this.onMediaEnded,this),t.off(a.ERROR,this.onError,this),t.off(a.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.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 t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){fs(t,"play",this.onPlay),fs(t,"pause",this.onPause),fs(t,"seeking",this.onSeeking),fs(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;us(i,"seeking",this.onSeeking),us(i,"timeupdate",this.onTimeupdate),us(i,"play",this.onPlay),us(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,s=(e,s,n,a,o)=>{if(e){let l=e[s].start;const d=e.event;if(d){if("playout"===s||d.timelineOccupancy!==La.Point){const t=i(n);(null==t?void 0:t.interstitial)===d&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?r():t[a])-e.start}return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var i,s;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(s=t.schedule)?void 0:s.durations[e])||0},a=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,d=t.schedule.findItemIndexAtTime(e,r),h=null==(a=t.schedule.items)?void 0:a[d],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,h);if(l&&(f||g)){const n=i(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const i="primary"===r?a.currentTime:s(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-i,d=(f?i:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(h){let i=e;if("primary"!==r){const t=e-h[r].start;i=h.start+t}const s=!t.isInterstitial(h);if(t.isInterstitial(l)&&!l.event.appendInPlace||!s&&!h.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(d>n){const e=t.schedule.findJumpRestrictedIndex(n+1,d);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(s)t.timelinePos=i,t.checkBuffer();else{const t=h.event.assetList,i=e-(h[r]||h).start;for(let e=t.length;e--;){const s=t[e];if(s.duration&&i>=s.startOffset&&i<s.startOffset+s.duration){a=e;break}}}t.setSchedulePosition(d,a)}}else{const e=t.media||(f?null==c?void 0:c.media:null);e&&(e.currentTime=i)}}},o=()=>{const i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;const s=e();return t.isInterstitial(s)?s:null},l={get bufferedEnd(){const i=e(),r=t.bufferingItem;var n;return r&&r===i&&(s(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),i=t.effectivePlayingItem;return i&&i===e?s(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){const i=o(),s=t.effectivePlayingItem;s&&s===i&&a(e+s.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const i=null==(e=o())?void 0:e.event.assetList;return i?i.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const i=null==(e=o())?void 0:e.event;return i&&t.effectivePlayingAsset?i.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){var e;return((e,i)=>{var s;if(0!==e&&"primary"!==i&&null!=(s=t.schedule)&&s.length){var r;const s=t.schedule.findItemIndexAtTime(e),n=null==(r=t.schedule.items)?void 0:r[s];if(n)return e+(n[i].start-n.start)}return e})((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){const s=t.findItemIndex(e);if(i.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(i,s,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,i;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let r=this.media;!r&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(r=this.primaryMedia);const n=null==(i=r)?void 0:i.currentTime;return void 0!==n&&e(n)?n:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,s=t.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&s)return void(this.detachedData={media:s});const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Xt(i)}`),this.detachedData=i}else e&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(t,e){var i,s;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.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 t=this.getBufferingPlayer();t?(r=t.transferMedia(),d=`${t}`):d="detached MediaSource"}else d="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Xt(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const h=r&&"mediaSource"in r&&"closed"!==(null==(s=r.mediaSource)?void 0:s.readyState),c=h&&r?r:e;this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`);const u=this.schedule;if(c===r&&u){const e=a&&t.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events;if(!e||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(Fa("checkStart",i)),this.timelinePos=i,e.length&&e[0].cue.pre){const i=t.findEventIndex(e[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){const e=this.timelinePos=i>0?i:0,s=t.findItemIndexAtTime(e);this.setSchedulePosition(s)}}else if(s&&!this.playingItem){const e=t.findItemIndex(s);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,s=i.findAssetIndex(e),r=Da(i,s);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const e=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(t)+1];e&&this.bufferedToItem(e)}}else this.bufferedToEvent(t,r)}advanceAfterAssetEnded(t,e,i){const s=Da(t,i);if(t.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=e+1;if(s>=i.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos<r&&(this.log(Fa("advanceAfterAssetEnded",r)),this.timelinePos=r,t.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(s)}}}else{if(t.appendInPlace){const e=t.assetList[s];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,s)}}setScheduleToAssetAtTime(t,e){const i=this.schedule;if(!i)return;const s=e.parentIdentifier,r=i.getEvent(s);if(r){const e=i.findEventIndex(s),n=i.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,n-1)}}setSchedulePosition(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const r=t>=0?s[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?xa(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,h=this.playingAsset,c=null==h?void 0:h.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(n,r)||void 0!==e&&c!==i.assetList[e].identifier)){var l;const e=i.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${i.assetList.length} ${wa(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(a.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:e,event:i,schedule:s.slice(0),scheduleIndex:t,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(c,r),!u.media||null!=(l=this.detachedData)&&l.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${xa(n)}`),i.hasPlayed=!0,this.hls.trigger(a.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:t}),i.cue.once)){var d;this.updateSchedule();const t=null==(d=this.schedule)?void 0:d.items;if(r&&t){const i=this.findItemIndex(r);this.advanceSchedule(i,t,e,n,o)}return}}this.advanceSchedule(t,s,e,n,o)}advanceSchedule(t,e,i,s,r){const n=this.schedule;if(!n)return;const o=e[t]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(e=>{const i=e.interstitial,s=n.findEventIndex(i.identifier);(s<t||s>t+1)&&this.clearInterstitial(i,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const r=o.event;if(void 0===i){const e=Da(r,(i=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(r,t,i);i=e}const d=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(r,i);if(this.eventItemsMatch(o,d||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${xa(o)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(a.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!l)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=o;const c=r.assetList[i];if(!c)return void this.advanceAfterAssetEnded(r,t,i||0);if(h||(h=this.getAssetPlayer(c.identifier)),null===h||h.destroyed){const t=r.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${r}`),h=this.createAssetPlayer(r,c,i),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(h,i,e,t,l),this.shouldPlay&&Oa(h.media)}else o?(this.resumePrimary(o,t,s),this.shouldPlay&&Oa(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 t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,i){var s,r;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${xa(t)}`),null==(s=this.detachedData)||!s.mediaSource){let i=this.timelinePos;(i<t.start||i>=t.end)&&(i=this.getPrimaryResumption(t,e),this.log(Fa("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,t)}if(!i)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${xa(t)}`),this.hls.trigger(a.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const i=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(i<t.fragmentStart||i>t.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return ze.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):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(t,i)),i||(this.log(Fa("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs(((null==(i=s.mainForwardBufferInfo)?void 0:i.start)||s.media.currentTime)-t)>.5?s.startLoad(t,e):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.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(a.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(a.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const i=this.hls.levels[e.level];if(!i.details)return;const s=E(E({},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(t,e){const i=this.hls.audioTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=E(E({},this.altSelection),{},{audio:i}));const r=E(E({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=E(E({},this.altSelection),{},{subtitles:i}));const r=E(E({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(t,e){const i=Jt(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i)))}onSubtitleTrackSwitch(t,e){const i=Jt(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(i)))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const s=e[t];if(s.cue.post){var i;const t=this.schedule.findEventIndex(s.identifier),e=null==(i=this.schedule.items)?void 0:i[t];this.isInterstitial(e)&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(t&&s){return s[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)});const i=t.end+.25,s=ze.bufferInfo(this.primaryMedia,i,0);if(s.end>i||(s.nextStart||0)>i){this.log(`trim buffered interstitial ${xa(t)} (was ${xa(e)})`);const s=!0;this.attachPrimary(i,null,s),this.flushFrontBuffer(i)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e;const i=this.mediaSelection;i&&(null==(e=this.schedule)||e.updateSchedule(i,[],t))}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const s=ze.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=s.len<1),this.updateBufferedPos(s.end,i,t)}updateBufferedPos(t,e,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!s)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(r),s=Math.min(i+1,e.length-1),n=e[s];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=s),this.isInterstitial(r)){const t=r.event;if(s-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>i&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.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(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){const{items:s,events:r}=i;if(!s||!r)return e;const n=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const l=o?o.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${xa(t)}`+(e?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,i)=>{const s=this.getAssetPlayer(t.identifier);s&&(i===e&&s.loadSource(),s.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger(a.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;const e=this.detachedData;if(e)if(e.mediaSource){const e=!0;this.attachPrimary(t.start,t,e)}else this.preloadPrimary(t);else this.preloadPrimary(t)}}preloadPrimary(t){const e=this.findItemIndex(t),i=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(i)}bufferedToEvent(t,e){const i=t.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){const t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const i=t.assetUrl,s=t.assetList.length,r=0===s&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart;if(t.appendInPlace){var a;const e=this.playingItem;this.isInterstitial(e)||(null==e||null==(a=e.nextEvent)?void 0:a.identifier)!==t.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&&!t.cue.pre&&!t.cue.post){const t=o-r;t>0&&(n=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:s} ${t}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(t,0,0,r,t.duration,i);const l=this.assetListLoader.loadAssetList(t,n);l&&(t.assetListLoader=l)}else if(!n&&s){for(let i=e;i<s;i++){const e=t.assetList[i],s=this.getAssetPlayerQueueIndex(e.identifier);-1!==s&&!this.playerQueue[s].destroyed||e.error||this.createAssetPlayer(t,e,i)}const i=t.assetList[e];if(i){const t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach(e=>{this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null}createAsset(t,e,i,s,r,n){const a={parentIdentifier:t.identifier,identifier:Ia(t,n,e),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,i){const s=this.hls,o=s.userConfig;let l=o.videoPreference;const d=s.loadLevelObj||s.levels[s.currentLevel];(l||d)&&(l=v({},l),d.videoCodec&&(l.videoCodec=d.videoCodec),d.videoRange&&(l.allowedVideoRanges=[d.videoRange]));const h=s.audioTracks[s.audioTrack],c=s.subtitleTracks[s.subtitleTrack];let u=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>1){const i=e.duration;i&&t<i&&(u=t)}}const f=e.identifier,g=E(E({},o),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:f,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:l,audioPreference:h||o.audioPreference,subtitlePreference:c||o.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(g.timelineOffset=e.timelineStart));const m=g.cmcd;null!=m&&m.sessionId&&m.contentId&&(g.cmcd=v({},m,{contentId:ba(e.uri)})),this.getAssetPlayer(f)&&this.warn(`Duplicate date range identifier ${t} and asset ${f}`);const p=new Pa(this.HlsPlayerClass,g,t,e);this.playerQueue.push(p),t.assetList[i]=e;let y=!0;const T=s=>{if(s.live){var a;const e=new Error(`Interstitials MUST be VOD assets ${t}`),s={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},o=(null==(a=this.schedule)?void 0:a.findEventIndex(t.identifier))||-1;return void this.handleAssetItemError(s,t,o,i,e.message)}const o=s.edge-s.fragmentStart,l=e.duration;(y||null===l||o>l)&&(y=!1,this.log(`Interstitial asset "${f}" duration change ${l} > ${o}`),e.duration=o,this.updateSchedule())};p.on(a.LEVEL_UPDATED,(t,{details:e})=>T(e)),p.on(a.LEVEL_PTS_UPDATED,(t,{details:e})=>T(e)),p.on(a.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const S=(t,e)=>{const i=this.getAssetPlayer(f);if(i&&e.tracks){i.off(a.BUFFER_CODECS,S),i.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};p.on(a.BUFFER_CODECS,S);p.on(a.BUFFERED_TO_END,()=>{var i;const s=this.getAssetPlayer(f);if(this.log(`buffered to end of asset ${s}`),!s||!this.schedule)return;const r=this.schedule.findEventIndex(t.identifier),n=null==(i=this.schedule.items)?void 0:i[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,e)});const b=e=>()=>{if(!this.getAssetPlayer(f)||!this.schedule)return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return p.once(a.MEDIA_ENDED,b(i)),p.once(a.PLAYOUT_LIMIT_REACHED,b(1/0)),p.on(a.ERROR,(e,s)=>{if(!this.schedule)return;const r=this.getAssetPlayer(f);if(s.details===n.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(s,t,this.schedule.findEventIndex(t.identifier),i,`Asset player error ${s.error} ${t}`)}),p.on(a.DESTROYING,()=>{if(!this.getAssetPlayer(f)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${f}`),s={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(s,t,this.schedule.findEventIndex(t.identifier),i,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${wa(e)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:p}),p}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){const t=this.playerQueue[i];this.log(`clear ${t} toSegment: ${e?xa(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(i,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,s,r){const{interstitial:n,assetItem:o,assetId:l}=t,d=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,h&&h.identifier===l||(h&&(this.clearAssetPlayer(h.identifier,i[s]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${d} ${wa(o)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:e,event:n,schedule:i.slice(0),scheduleIndex:s,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var i,s;if(!this.schedule)return;const{interstitial:a,assetItem:o}=t,l=this.schedule.findEventIndex(a.identifier),d=null==(i=this.schedule.items)?void 0:i[l];if(!d)return;t.loadSource(),this.setBufferingItem(d),this.bufferingAsset=o;const h=this.getBufferingPlayer();if(h===t)return;const c=a.appendInPlace;if(c&&!1===(null==h?void 0:h.interstitial.appendInPlace))return;const u=(null==h?void 0:h.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(c&&o!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(u&&!_(u,t.tracks)){const e=new Error(`Asset ${wa(o)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),i={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},s=a.findAssetIndex(o);return void this.handleAssetItemError(i,a,l,s,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,i=this.primaryMedia;if(!e||!i)return;const s=i.currentTime,r=e.findAssetIndex(t,s),n=t.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} ${t} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,r)}}}}advanceInPlace(t){const e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)}handleAssetItemError(t,e,i,s,r){if(t.details===n.BUFFER_STALLED_ERROR)return;const o=e.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o?wa(o):o} ${t.error}`),!this.schedule)return;const l=(null==o?void 0:o.identifier)||"",d=this.getAssetPlayerQueueIndex(l),h=this.playerQueue[d]||null,c=this.schedule.items,u=v({},t,{fatal:!1,errorAction:Re(!0),asset:o,assetListIndex:s,event:e,schedule:c,scheduleIndex:i,player:h});if(this.hls.trigger(a.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;const f=this.playingAsset,g=this.bufferingAsset,m=new Error(r);if(o&&(this.clearAssetPlayer(l,null),o.error=m),e.assetList.some(t=>!t.error))for(let t=s;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=m;this.updateSchedule(!0),e.error?this.primaryFallback(e):f&&f.identifier===l?this.advanceAfterAssetEnded(e,i,s):g&&g.identifier===l&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem;let s=this.timelinePos;if(i){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${s} playing: ${xa(i)} error: ${t.error}`),-1===s&&(s=this.hls.startPosition);const r=this.updateItem(i,s);this.itemsMatch(i,r)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===s)return void this.checkStart();if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(r)}onAssetListLoaded(t,e){var i,s;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(r,e,d,o+d,i,t.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 t=this.schedule.findEventIndex(n),e=null==(f=this.schedule.items)?void 0:f[t];if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===n){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(u.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case n.ASSET_LIST_PARSING_ERROR:case n.ASSET_LIST_LOAD_ERROR:case n.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case n.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function Ko(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Ko):Object.keys(t).reduce((e,i)=>(e[i]=Ko(t[i]),e),{}):t}function Ho(t,e){const i=t.loader;if(i!==Fo&&i!==$o)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=Fo,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Vo extends qe{constructor(t,e){super("gap-controller",t.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 t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const i=this.media=e.media;us(i,"playing",this.onMediaPlaying),us(i,"waiting",this.onMediaWaiting),us(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(fs(i,"playing",this.onMediaPlaying),fs(i,"waiting",this.onMediaWaiting),fs(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){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:o}=n,l=this.seeking&&!o,d=!this.seeking&&o,h=n.paused&&!o||n.ended||0===n.playbackRate;if(this.seeking=o,t!==e)return e&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(d||l)return void(l&&this.stallResolved(t));if(h)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1})));if(!ze.getBuffered(n).length)return void(this.nudgeRetry=0);const c=ze.bufferInfo(n,t,0),u=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const e=jo(this.hls.inFlightFragments,t),i=c.len>2,s=!u||e||u-t>2&&!f.getPartialFragment(t);if(i||s)return;this.moved=!1}const g=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(c.len>0)&&!u)return;const e=Math.max(u,c.start||0)-t,i=!(null==g||!g.live)?2*g.targetduration:2,s=Yo(t,f);if(e>0&&(e<=i||s))return void(n.paused||this._trySkipBufferHole(s))}const m=r.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting;let y=this.stalled;if(null===y){if(!(v>0&&p-v<m))return void(this.stalled=p);y=this.stalled=v}const E=p-y;if(!o&&(E>=m||v)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==g||!g.live)&&Math.abs(t-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(a.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}const S=ze.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(S,E,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(a.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){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&&t>s.end(0)){const i=ze.bufferedInfo(ze.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=ze.timeRangesToArray(s),o=ze.bufferedInfo(i,e,0).bufferedIndex;if(o>-1&&o<i.length-1){const e=ze.bufferedInfo(i,t,0).bufferedIndex,s=i[o].end,l=i[o+1].start;if((-1===e||e>o)&&l-s<1&&t-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${s} -> ${l} buffered index: ${e}`);this.warn(i.message),this.media.currentTime+=1e-6;let o=Yo(t,this.fragmentTracker);o&&"fragment"in o?o=o.fragment:o||(o=void 0);const d=ze.bufferInfo(this.media,t,0);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:o,buffer:d.len,bufferInfo:d})}}}}}_tryFixBufferStall(t,e,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=Yo(i,n);if(d||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=t.buffered,c=this.adjacentTraversal(t,i);(h&&h.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||c))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,s=t.nextStart;if(i&&s){const t=i.getFragAtPos(e,c),r=i.getFragAtPos(s,c);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:s,stalled:o}=this;if(!s&&null!==o&&i&&e){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Xt(t)})`);this.warn(s.message),e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:t.len,bufferInfo:t,stalled:{start:o}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:i,media:s}=this,o=null==(e=this.hls)?void 0:e.config;if(!s||!i||!o)return 0;const l=s.currentTime,d=ze.bufferInfo(s,l,0),h=l<d.start?d.start:d.nextStart;if(h&&this.hls){const e=d.len<=o.maxBufferHole,f=d.len>0&&d.len<1&&s.readyState<3,g=h-l;if(g>0&&(e||f)){if(g>o.maxBufferHole){let e=!1;if(0===l){const t=i.getAppendedFrag(0,c);t&&h<t.end&&(e=!0)}if(!e&&t){var u;if(null==(u=this.hls.loadLevelObj)||!u.details)return 0;if(jo(this.hls.inFlightFragments,h))return 0;let e=!1,s=t.end;for(;s<h;){const t=Yo(s,i);if(!t){e=!0;break}s+=t.duration}if(e)return 0}}const e=Math.max(h+.05,l+.1);if(this.warn(`skipping hole, adjusting currentTime from ${l} to ${e}`),this.moved=!0,s.currentTime=e,null==t||!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${l} to ${e}`),s={type:r.MEDIA_ERROR,details:n.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:d.len,bufferInfo:d};t&&("fragment"in t?s.part=t:s.frag=t),this.hls.trigger(a.ERROR,s)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:s}=this,o=null==e?void 0:e.config;if(!i||!o)return 0;const l=i.currentTime;if(this.nudgeRetry++,s<o.nudgeMaxRetry){const d=l+(s+1)*o.nudgeOffset,h=new Error(`Nudging 'currentTime' from ${l} to ${d}`);this.warn(h.message),i.currentTime=d,e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_NUDGE_ON_STALL,error:h,fatal:!1,buffer:t.len,bufferInfo:t})}else{const i=new Error(`Playhead still not moving while enough data buffered @${l} after ${o.nudgeMaxRetry} nudges`);this.error(i.message),e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}}function jo(t,e){const i=qo(t.main);if(i&&i.start<=e)return i;const s=qo(t.audio);return s&&s.start<=e?s:null}function qo(t){if(!t)return null;switch(t.state){case ps:case ms:case As:case Ls:return null}return t.frag}function Yo(t,e){return e.getAppendedFrag(t,c)||e.getPartialFragment(t)}function Wo(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function zo(t,e,i,s,r){let n=new t(e,i,"");try{n.value=s,r&&(n.type=r)}catch(a){n=new t(e,i,Xt(r?E({type:r},s):s))}return n}const Xo=(()=>{const t=Wo();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Qo{constructor(t){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(a.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var i;this.media=e.media,!1===(null==(i=e.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.removeCues&&Ea(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const i=t[e];if("metadata"===i.kind&&"id3"===i.label)return va(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Wo();if(n)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===sr.emsg&&!i||!s)continue;const a=Js(r[t].data),o=r[t].pts;let l=o+r[t].duration;l>Xo&&(l=Xo);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!tr(i)){this.updateId3CueEnds(o,e);const t=zo(n,o,l,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(t,e){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===e&&r.startTime<t&&r.endTime===Xo&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,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 t;t="audio"===s?t=>t.type===sr.audioId3&&o:"video"===s?t=>t.type===sr.emsg&&a:t=>t.type===sr.audioId3&&o||t.type===sr.emsg&&a,Ta(r,e,i,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,i){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Wo();if(s&&r&&!a){const{fragmentStart:e,fragmentEnd:i}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=i):o&&(r=this.assetCue=zo(o,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:d}=t,h=Object.keys(d);let c=this.dateRangeCuesAppended;var u;if(l&&i)if(null!=(u=l.cues)&&u.length){const t=Object.keys(c).filter(t=>!h.includes(t));for(let e=t.length;e--;){var f;const i=t[e],s=null==(f=c[i])?void 0:f.cues;delete c[i],s&&Object.keys(s).forEach(t=>{const e=s[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(e)}catch(t){}}})}}else c=this.dateRangeCuesAppended={};const g=t.fragments[t.fragments.length-1];if(0!==h.length&&e(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<h.length;t++){const e=h[t],i=d[e],s=i.startTime,r=c[e],n=(null==r?void 0:r.cues)||{};let l=(null==r?void 0:r.durationKnown)||!1,u=Xo;const{duration:f,endDate:g}=i;if(g&&null!==f)u=s+f,l=!0;else if(i.endOnNext&&!l){const t=h.reduce((t,e)=>{if(e!==i.id){const s=d[e];if(s.class===i.class&&s.startDate>i.startDate&&(!t||i.startDate<t.startDate))return s}return t},null);t&&(u=t.startTime,l=!0)}const m=Object.keys(i.attr);for(let t=0;t<m.length;t++){const d=m[t];if(!ri(d))continue;const h=n[d];if(h)!l||null!=r&&r.durationKnown?Math.abs(h.startTime-s)>.01&&(h.startTime=s,h.endTime=u):h.endTime=u;else if(o){let t=i.attr[d];ni(d)&&(t=P(t));const r=zo(o,s,u,{key:d,data:t},sr.dateRange);r&&(r.id=e,this.id3Track.addCue(r),n[d]=r,a&&("X-ASSET-LIST"!==d&&"X-ASSET-URL"!==d||r.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:n,dateRange:i,durationKnown:l}}}}}class Zo{constructor(t){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:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,s=Math.min(e,Math.max(1,i));this.changeMediaPlaybackRate(t,s)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(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(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,r=t-e-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 t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.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(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var i;e.details===n.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(t,e){var i,s;t.playbackRate!==e&&(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 ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}class Jo extends an{constructor(t,e){super(t,"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=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{const e=t.attrs;let{audioCodec:d,videoCodec:h}=t;d&&(t.audioCodec=d=kt(d,i)||void 0),h&&(h=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}(h));const{width:c,height:u,unknownCodecs:f}=t,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 "${e.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=e,S=`${`${y||"."}-`}${t.bitrate}-${E}-${p}-${m}-${T}-${v}`;if(r[S])if(r[S].uri===t.url||t.attrs["PATHWAY-ID"])r[S].addGroupId("audio",e.AUDIO),r[S].addGroupId("text",e.SUBTITLES);else{const e=n[S]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);r[S]=i,s.push(i)}else{const e=this.createLevel(t);r[S]=e,n[S]=1,s.push(e)}}),this.filterAndSortMediaOptions(s,e,a,o,l)}createLevel(t){const e=new Yt(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(t.message),e.supportedResult=Ot(t,[])}return e}isAudioSupported(t){return Tt(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Tt(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,s,o){var l;let d=[],h=[],c=t;const u=(null==(l=e.stats)?void 0:l.parsing)||{};if((i||s)&&o&&(c=c.filter(({videoCodec:t,videoRange:e,width:i,height:s})=>{return(!!t||!(!i||!s))&&(!!(r=e)&&Gt.indexOf(r)>-1);var r})),0===c.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i=`one or more CODECS in variant not supported: ${Xt(e.levels.map(t=>t.attrs.CODECS).filter((t,e,i)=>i.indexOf(t)===e))}`,this.warn(i),t+=` (${i})`);const s=new Error(t);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:s,reason:i})}}),void(u.end=performance.now());e.audioTracks&&(d=e.audioTracks.filter(t=>!t.audioCodec||this.isAudioSupported(t.audioCodec)),tl(d)),e.subtitles&&(h=e.subtitles,tl(h));const f=c.slice(0);c.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Gt.indexOf(t.videoRange)-Gt.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=At(t.videoCodec),s=At(e.videoCodec);if(i!==s)return s-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=Lt(t.codecSet),s=Lt(e.codecSet);if(i!==s)return s-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let g=f[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==f.length))for(let t=0;t<f.length;t++)if(f[t].pathwayId===c[0].pathwayId){g=f[t];break}this._levels=c;for(let t=0;t<c.length;t++)if(c[t]===g){var m;this._firstLevel=t;const e=g.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${e}`),void 0===(null==(m=this.hls.userConfig)?void 0:m.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const p=o&&!s,v=this.hls.config,y=!(!v.audioStreamController||!v.audioTrackController),E={levels:c,audioTracks:d,subtitleTracks:h,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:s,altAudio:y&&!p&&d.some(t=>!!t.url)};u.end=performance.now(),this.hls.trigger(a.MANIFEST_PARSED,E)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const i=new Error("invalid level idx"),s=t<0;if(this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.LEVEL_SWITCH_ERROR,level:t,fatal:s,error:i,reason:i.message}),s)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,o=s?s.attrs["PATHWAY-ID"]:void 0,l=e[t],d=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,i===t&&s&&o===d)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${d?" with Pathway "+d:""} from level ${i}${o?" with Pathway "+o:""}`);const h={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(a.LEVEL_SWITCHING,h);const c=l.details;if(!c||c.live){const t=this.switchParams(l.uri,null==s?void 0:s.details,c);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),i=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===l&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===c){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(s,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),s=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,o=null==n?void 0:n.age;this.log(`Loading level index ${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(a.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const i=this._levels.filter((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));rs(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.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(a.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(a.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function tl(t){const e={};t.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function el(){return self.SourceBuffer||self.WebKitSourceBuffer}function il(){if(!k())return!1;const t=el();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class sl extends ks{constructor(t,i,s){super(t,i,s,"stream-controller",c),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 t=this.media,i=t?t.currentTime:null;if(null===i||!e(i))return;if(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i))return;const s=this.getFwdBufferInfoAtPos(t,i,c,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${i} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=ps,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=ms}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Rs:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=ps;break}if(this.hls.nextLoadLevel!==this.level){this.state=ps;break}break}case Es:this.checkRetryDate()}this.state===ps&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(null===e||!s&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[r])return;const n=i[r],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger(a.BUFFER_EOS,t),void(this.state=As)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const d=n.details;if(!d||this.state===Rs||this.waitForLive(n))return this.level=r,this.state=Rs,void(this.startFragRequested=!1);const h=o.len,u=this.getMaxBufferLength(n.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&G(g)&&this.fragmentTracker.getState(g)!==we){var m;const t=(null!=(m=this.backtrackFragment)?m:g).sn-d.startSN,e=d.fragments[t-1];e&&g.cc===e.cc&&(g=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){const t=this.audioOnly&&!this.altAudio?N:B,e=(t===B?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,c)}g=this.getNextFragmentLoopLoading(g,d,o,c,u)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),this.loadFragment(g,n,f))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===ke||s===De?G(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,i):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,c)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let i;const s=this.getAppendedFrag(e.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*s)+1:0}else i=0;const n=this.getBufferedFrag(e.currentTime+i);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,s=Math.max(n.end,e+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 t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case vs:case ys:case Es:case Ss:case bs:this.state=ps}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;us(i,"playing",this.onMediaPlaying),us(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(fs(i,"playing",this.onMediaPlaying),fs(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(a.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,s=!1;for(let t=0;t<e.levels.length;t++){const r=e.levels[t].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),s=s||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&s&&!function(){var t;const e=el();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==ps)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=Rs)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:r}=this,n=e.level,o=e.details,l=o.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const d=e.levelInfo,h=this.fragCurrent;!h||this.state!==ys&&this.state!==Es||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let c=0;if(o.live||null!=(i=d.details)&&i.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(d.details=o,this.levelLastLoaded=d,r||this.setStartPosition(o,c),this.hls.trigger(a.LEVEL_UPDATED,{details:o,level:n}),this.state===Rs){if(this.waitForCdnTuneIn(o))return;this.state=ps}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r<s||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.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 t=ze.bufferInfo(i,s,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=s);if(t.start<=r)return void(i.currentTime=s);const{nextStart:e}=ze.bufferedInfo(t.buffered,r,0);e&&(i.currentTime=e)}else i.currentTime=s}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{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==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),f=this.transmuxer=this.transmuxer||new nn(this.hls,c,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,m=-1!==g,p=new Ye(i.level,i.sn,i.stats.chunkCount,r.byteLength,g,m),v=this.initPTS[i.cc];f.push(r,h,u,l,i,s,o.totalduration,d,p,v)}onAudioTrackSwitching(t,e){const i=this.hls,s=0!==this.altAudio;if(re(e.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 t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(a.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(a.AUDIO_TRACK_SWITCHED,e)}),void i.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(a.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=re(e.url,this.hls);if(i){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i?2:0,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,r,n=!1;for(const t in i){const e=i[t];if("main"===e.id){if(r=t,s=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.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(t,e){const{frag:i,part:s}=e,r=i.type===c;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===bs&&(this.state=ps));const t=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),G(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const n=this.media;n&&(!this._hasEnoughToStart&&ze.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=Ls;else switch(e.details){case n.FRAG_GAP:case n.FRAG_PARSING_ERROR:case n.FRAG_DECRYPT_ERROR:case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(c,e);break;case n.LEVEL_LOAD_ERROR:case n.LEVEL_LOAD_TIMEOUT:case n.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Rs||(null==(i=e.context)?void 0:i.type)!==l||(this.state=ps);break;case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case n.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case n.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=ps,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==N||!this.altAudio){const t=(e===B?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,c),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log(`could not seek to ${i}, already seeking at ${e}`);const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=ze.getBuffered(t),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),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),t.currentTime=i)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{const{hls:i}=this,s=null==t?void 0:t.frag;if(!s||this.fragContextChanged(s))return;e.fragmentError=0,this.state=ps,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(a.FRAG_LOADED,t),s.bitrateTest=!1}).catch(e=>{this.state!==ms&&this.state!==Ls&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const i=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,o=this.getCurrentContext(n);if(!o)return void this.resetWhenMissingContext(n);const{frag:l,part:d,level:h}=o,{video:c,text:u,id3:f,initSegment:g}=r,{details:m}=h,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l))this.fragmentTracker.removeFragment(l);else{if(this.state=Ss,g){const t=g.tracks;if(t){const e=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(h,t,e,n),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:t})}const r=g.initPTS,o=g.timescale,d=this.initPTS[l.cc];if(e(r)&&(!d||d.baseTime!==r||d.timescale!==o)){const t=g.trackId;this.initPTS[l.cc]={baseTime:r,timescale:o,trackId:t},s.trigger(a.INIT_PTS_FOUND,{frag:l,id:i,initPTS:r,timescale:o,trackId:t})}}if(c&&m){p&&"audiovideo"===c.type&&this.logMuxedErr(l);const t=m.fragments[l.sn-1-m.startSN],e=l.sn===m.startSN,i=!t||l.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:s,startDTS:r,endDTS:a}=c;if(d)d.elementaryStreams[c.type]={startPTS:t,endPTS:s,startDTS:r,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=c.firstKeyFramePTS?c.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!i)return void this.backtrack(l);i&&(l.gap=!0),l.setElementaryStreamInfo(c.type,l.start,s,l.start,a,!0)}else e&&t-(m.appliedTimelineOffset||0)>2&&(l.gap=!0);l.setElementaryStreamInfo(c.type,t,s,r,a),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,d,n,e||i)}else{if(!e&&!i)return void this.backtrack(l);l.gap=!0}}if(p){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=p;d&&(d.elementaryStreams[N]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(N,t,e,i,s),this.bufferFragmentData(p,l,d,n)}if(m&&null!=f&&f.samples.length){const t={id:i,frag:l,details:m,samples:f.samples};s.trigger(a.FRAG_PARSING_METADATA,t)}if(m&&u){const t={id:i,frag:l,details:m,samples:u.samples};s.trigger(a.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${G(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,s){if(this.state!==Ss)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:o}=e;if(r){const i=t.audioCodec;let s=_t(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 t=r.metadata;t&&"channelCount"in t&&1!==(t.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=c,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=c;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]=[${t.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete e.video,delete e.audio);const l=Object.keys(e);if(l.length){if(this.hls.trigger(a.BUFFER_CODECS,e),!this.hls)return;l.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(a.BUFFER_APPENDING,{type:t,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,c)}get maxBufferLength(){const{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=ps}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(ze.isBuffered(t,i)?e=this.getAppendedFrag(i):ze.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,i=e.level;t&&e.sn===t.sn&&t.level===i||(this.fragPlaying=e,this.hls.trigger(a.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(a.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return e(i)?this.getAppendedFrag(i):null}get currentProgramDateTime(){var t;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(e(i)){const t=this.getLevelDetails(),e=this.currentFrag||(t?ae(null,t.fragments,i):null);if(e){const t=e.programDateTime;if(null!==t){const s=t+1e3*(i-e.start);return new Date(s)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class rl extends T{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var e;if(t&&t!==(null==(e=s.context)?void 0:e.frag.type))return;s.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=n.KEY_LOAD_ERROR,i,s,a){return new je({type:r.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:a,error:i,networkDetails:s})}loadClear(t,e,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(let s=0,r=e.length;s<r;s++){const n=e[s];if(t.cc<=n.cc&&(!G(t)||!G(n)||t.sn<n.sn)||!i&&s==r-1)return this.emeController.selectKeySystemFormat(n).then(t=>{if(!this.emeController)return;n.setKeyFormat(t);const e=bi(t);return e?this.emeController.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=Li(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var i,s;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const i=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,n.KEY_LOAD_ERROR,i))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(t,n.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=nl(r);let l=this.keyIdToKeyInfo[o];if(null!=(i=l)&&i.decryptdata.key)return r.key=l.decryptdata.key,Promise.resolve({frag:t,keyInfo:l});if(this.emeController&&null!=(s=l)&&s.keyLoadPromise){switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(e=>{const{keyInfo:i}=e;return r.key=i.decryptdata.key,{frag:t,keyInfo:i}})}}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+w(r.keyId):""} URI: ${r.uri} from ${t.type} ${t.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(l,t):this.loadKeyEME(l,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,t);default:return Promise.reject(this.createKeyLoadError(t,n.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var s;if(!t.decryptdata.keyId&&null!=(s=e.initSegment)&&s.data){const i=function(t){const e=[];return ot(t,t=>e.push(t.subarray(8,24))),e}(e.initSegment.data);if(i.length){let e=i[0];e.some(t=>0!==t)?(this.log(`Using keyId found in init segment ${w(e)}`),Di.setKeyIdForUri(t.decryptdata.uri,e)):(e=Di.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${w(e)}`)),t.decryptdata.keyId=e}}if(!t.decryptdata.keyId&&!G(e))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(t.keyLoadPromise=r.then(e=>(t.mediaKeySessionContext=e,i))).catch(i=>{throw t.keyLoadPromise=null,"data"in i&&(i.data.frag=e),i})}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,s=new(0,i.loader)(i);return e.keyLoader=t.loader=s,t.keyLoadPromise=new Promise((r,a)=>{const o={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=i.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,s)=>{const{frag:o,keyInfo:l}=i,d=nl(l.decryptdata);if(!o.decryptdata||l!==this.keyIdToKeyInfo[d])return a(this.createKeyLoadError(o,n.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(t.data),o.keyLoader=null,l.loader=null,r({frag:o,keyInfo:l})},onError:(t,i,s,r)=>{this.resetLoader(i),a(this.createKeyLoadError(e,n.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),s,E({url:o.url,data:void 0},t)))},onTimeout:(t,i,s)=>{this.resetLoader(i),a(this.createKeyLoadError(e,n.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(t,i,s)=>{this.resetLoader(i),a(this.createKeyLoadError(e,n.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(o,d,h)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=null,i.loader=null);const n=nl(i.decryptdata)||s;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function nl(t){if(t.keyFormat!==Ei){const e=t.keyId;if(e)return w(e)}return t.uri}function al(t){const{type:e}=t;switch(e){case d:return u;case h:return f;default:return c}}function ol(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class ll{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,r=new(i||s)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:o,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:l,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:d,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:h,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const i=this.loaders[l];if(i){const t=i.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(i.abort(),delete this.loaders[l])}}load(t){var i;const s=this.hls.config;let r,n=this.getInternalLoader(t);if(n){const e=this.hls.logger,i=n.context;if(i&&i.levelOrTrack===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives))return void(i.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${i.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(r=t.type===o?s.manifestLoadPolicy.default:v({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),e(null==(i=t.deliveryDirectives)?void 0:i.part)){let e;if(t.type===l&&null!==t.level?e=this.hls.levels[t.level].details:t.type===d&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===h&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);r=v({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},c={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},u={onSuccess:(t,e,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=t.data;e.parsing.start=performance.now(),Fi.isMediaPlaylist(n)||i.type!==o?this.handleTrackOrLevelPlaylist(t,e,i,s||null,r):this.handleMasterPlaylist(t,e,i,s)},onError:(t,e,i,s)=>{this.handleNetworkError(e,i,!1,t,s)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};n.load(t,c,u)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,s){const r=this.hls,n=t.data,o=ol(t,i),l=Fi.parseMasterPlaylist(n,o);if(l.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);const{contentSteering:d,levels:h,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g}=l;this.variableList=g,h.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:r}=t;for(let n=e.length;n--;){const a=e[n];Tt(a,"audio",i)?(t.audioCodec=s=s?`${s},${a}`:a,yt.audio[s.substring(0,4)]=2,e.splice(n,1)):Tt(a,"video",i)&&(t.videoCodec=r=r?`${r},${a}`:a,yt.video[r.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=Fi.parseMasterPlaylistMedia(n,o,l);if(m.length){m.some(t=>!t.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new si({}),bitrate:0,url:""}))}r.trigger(a.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,captions:v,contentSteering:d,url:o,stats:e,networkDetails:s,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,i,s,r,n){const l=this.hls,{id:d,level:h,type:c}=s,u=ol(t,s),f=e(h)?h:e(d)?d:0,g=al(s),m=Fi.parseLevelPlaylist(t.data,u,f,g,0,this.variableList);if(c===o){const t={attrs:new si({}),bitrate:0,details:m,name:"",url:u};m.requestScheduled=i.loading.start+ts(m,0),l.trigger(a.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:u,stats:i,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}i.parsing.end=performance.now(),s.levelDetails=m,this.handlePlaylistLoaded(m,t,i,s,r,n)}handleManifestParsingError(t,e,i,s,l){this.hls.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.MANIFEST_PARSING_ERROR,fatal:e.type===o,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:l})}handleNetworkError(t,e,i=!1,s,c){let u=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===l?u+=`: ${t.level} id: ${t.id}`:t.type!==d&&t.type!==h||(u+=` id: ${t.id} group-id: "${t.groupId}"`);const f=new Error(u);this.hls.logger.warn(`[playlist-loader]: ${u}`);let g=n.UNKNOWN,m=!1;const p=this.getInternalLoader(t);switch(t.type){case o:g=i?n.MANIFEST_LOAD_TIMEOUT:n.MANIFEST_LOAD_ERROR,m=!0;break;case l:g=i?n.LEVEL_LOAD_TIMEOUT:n.LEVEL_LOAD_ERROR,m=!1;break;case d:g=i?n.AUDIO_TRACK_LOAD_TIMEOUT:n.AUDIO_TRACK_LOAD_ERROR,m=!1;break;case h:g=i?n.SUBTITLE_TRACK_LOAD_TIMEOUT:n.SUBTITLE_LOAD_ERROR,m=!1}p&&this.resetInternalLoader(t.type);const v={type:r.NETWORK_ERROR,details:g,fatal:m,url:t.url,loader:p,context:t,error:f,networkDetails:e,stats:c};if(s){const i=(null==e?void 0:e.url)||t.url;v.response=E({url:i,data:void 0},s)}this.hls.trigger(a.ERROR,v)}handlePlaylistLoaded(t,e,i,s,u,f){const g=this.hls,{type:m,level:p,levelOrTrack:v,id:y,groupId:E,deliveryDirectives:T}=s,S=ol(e,s),b=al(s);let A="number"==typeof s.level&&b===c?p:void 0;const L=t.playlistParsingError;if(L){if(this.hls.logger.warn(`${L} ${t.url}`),!g.config.ignorePlaylistParsingErrors)return void g.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_PARSING_ERROR,fatal:!1,url:S,error:L,reason:L.message,response:e,context:s,level:A,parent:b,networkDetails:u,stats:i});t.playlistParsingError=null}if(!t.fragments.length){const o=t.playlistParsingError=new Error("No Segments found in Playlist");return void g.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_EMPTY_ERROR,fatal:!1,url:S,error:o,reason:o.message,response:e,context:s,level:A,parent:b,networkDetails:u,stats:i})}switch(t.live&&f&&(f.getCacheAge&&(t.ageHeader=f.getCacheAge()||0),f.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),m){case o:case l:if(A)if(v){if(v!==g.levels[A]){const t=g.levels.indexOf(v);t>-1&&(A=t)}}else A=0;g.trigger(a.LEVEL_LOADED,{details:t,levelInfo:v||g.levels[0],level:A||0,id:y||0,stats:i,networkDetails:u,deliveryDirectives:T,withoutMultiVariant:m===o});break;case d:g.trigger(a.AUDIO_TRACK_LOADED,{details:t,track:v,id:y||0,groupId:E||"",stats:i,networkDetails:u,deliveryDirectives:T});break;case h:g.trigger(a.SUBTITLE_TRACK_LOADED,{details:t,track:v,id:y||0,groupId:E||"",stats:i,networkDetails:u,deliveryDirectives:T})}}}class dl{static get version(){return Ms}static isMSESupported(){return il()}static isSupported(){return function(){if(!il())return!1;const t=k();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(bt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(bt(e,"audio"))))}()}static getMediaSource(){return k()}static get Events(){return a}static get MetadataSchema(){return sr}static get ErrorTypes(){return r}static get ErrorDetails(){return n}static get DefaultConfig(){return dl.defaultConfig?dl.defaultConfig:Go}static set DefaultConfig(t){dl.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new xs,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 e=this.logger=function(t,e,i){const s=A();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach(e=>{s[e]=L(e,t,i)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch(t){return A()}r.forEach(e=>{I[e]=L(e,t)})}else v(I,s);return s}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(t,e,i){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Ko(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];r.forEach(i=>{const r=`${t}Loading${i}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=s[n].default;switch(e[n]={default:t},i){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Xt(e[n])}`)}),E(E({},s),e)}(dl.DefaultConfig,t,e);this.userConfig=t,i.progressive&&Ho(i,e);const{abrController:s,bufferController:r,capLevelController:n,errorController:o,fpsController:l}=i,d=new o(this),h=this.abrController=new s(this),c=new Pe(this),u=i.interstitialsController,f=u?this.interstitialsController=new u(this,dl):null,g=this.bufferController=new r(this,c),m=this.capLevelController=new n(this),p=new l(this),y=new ll(this),T=i.contentSteeringController,S=T?new T(this):null,b=this.levelController=new Jo(this,S),R=new Qo(this),k=new rl(this.config,this.logger),_=this.streamController=new sl(this,c,k),D=this.gapController=new Vo(this,c);m.setStreamController(_),p.setStreamController(_);const w=[y,b,_];f&&w.splice(1,0,f),S&&w.splice(1,0,S),this.networkControllers=w;const P=[h,g,D,m,p,R,c];this.audioTrackController=this.createController(i.audioTrackController,w);const C=i.audioStreamController;C&&w.push(this.audioStreamController=new C(this,c,k)),this.subtitleTrackController=this.createController(i.subtitleTrackController,w);const x=i.subtitleStreamController;x&&w.push(this.subtititleStreamController=new x(this,c,k)),this.createController(i.timelineController,P),k.emeController=this.emeController=this.createController(i.emeController,P),this.cmcdController=this.createController(i.cmcdController,P),this.latencyController=this.createController(Zo,P),this.coreComponents=P,w.push(d);const M=d.onErrorOut;"function"==typeof M&&this.on(a.ERROR,M,d),this.on(a.MANIFEST_LOADED,y.onManifestLoaded,y)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===a.ERROR;this.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(a.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,s=e?t:{media:i};this._media=i,this.trigger(a.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(a.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(a.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,i=this._url,s=this._url=O.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),e&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(a.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[c]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[u]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[f]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)})}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return $t.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(s=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=s;e--;){const s=t[e].attrs["HDCP-LEVEL"];if(s&&s<=i)return e}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}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(t){this.latencyController.targetLatency=t}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(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return Nt(t,Zt(e),navigator.mediaCapabilities)}}function hl(t){const{baseUrl:e,apiKey:i,clientId:s,fetch:r}=t,n=r??globalThis.fetch;if(!n)throw new Error("No fetch implementation found. Provide one in SDKConfig.fetch for Node or custom environments.");const a={"Content-Type":"application/json","x-api-key":i},o=t=>function(t,e,i){if(/^https?:\/\//i.test(i))return i;const s=t.replace(/\/+$/,""),r=i.replace(/^\/+/,"");return`${s}/b2b/v1/subscription/${encodeURIComponent(e)}${r.startsWith("/")?r:`/${r}`}`}(e,s,t),l=async(t,e,i,s)=>{const r={method:t,headers:{...a,...i?.headers},...i};void 0!==s&&(r.body=JSON.stringify(s));return async function(t){if(!t.ok){const e=await t.text().catch(()=>"");throw new Error(`HTTP ${t.status}: ${e||t.statusText}`)}if(204!==t.status)return t.json()}(await n(o(e),r))};return{get:(t,e)=>l("GET",t,e),post:(t,e,i)=>l("POST",t,i,e),put:(t,e,i)=>l("PUT",t,i,e),patch:(t,e,i)=>l("PATCH",t,i,e),delete:(t,e)=>l("DELETE",t,e)}}dl.defaultConfig=void 0;const cl="https://api.jaaq.app";class ul{constructor(t){this.videos=function(t){return{async getById(e){const i=`/videos/${encodeURIComponent(e)}`;return(await t.get(i)).video}}}(t),this.collections=function(t){return{list:async()=>(await t.get("/collections")).collections,async getById(e){const i=`/collections/${encodeURIComponent(e)}`;return(await t.get(i)).collection}}}(t)}static fromHttp(t){return new ul(t)}static init(t){return fl(t)}}function fl(t){const{baseUrl:e=cl,apiKey:i,clientId:s,fetch:r}=t,n=hl({baseUrl:e,apiKey:i,clientId:s,fetch:r??globalThis.fetch});return ul.fromHttp(n)}function gl(t,e,i){return Math.max(e,Math.min(i,t))}var ml=".jaaq-video-player {\n position: relative;\n width: 100%;\n max-width: none;\n margin: 0;\n background: #000;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n aspect-ratio: 9 / 16;\n}\n\n.jaaq-video-player video {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n display: block;\n background: #000;\n object-fit: cover;\n}\n\n.jaaq-video-player.fullscreen {\n max-width: 100%;\n border-radius: 0;\n aspect-ratio: auto;\n}\n\n.jaaq-controls {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);\n padding: 40px 16px 16px;\n opacity: 1;\n z-index: 5;\n}\n\n.jaaq-progress-bar {\n width: 100%;\n flex: 1 1 0;\n min-width: 80px;\n height: 4px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 2px;\n cursor: pointer;\n position: relative;\n}\n\n.jaaq-progress-filled {\n height: 100%;\n background: #007bff;\n border-radius: 2px;\n width: 0%;\n transition: width 0.1s linear;\n}\n\n.jaaq-progress-bar:hover .jaaq-progress-filled {\n background: #0056b3;\n}\n\n.jaaq-controls-bottom {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n color: white;\n}\n\n.jaaq-control-btn {\n background: transparent;\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 20px;\n line-height: 1;\n}\n\n.jaaq-control-btn:hover {\n transform: scale(1.1);\n}\n\n.jaaq-control-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n}\n\n.jaaq-loading {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 50px;\n height: 50px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-spin 1s linear infinite;\n}\n\n@keyframes jaaq-spin {\n to {\n transform: translate(-50%, -50%) rotate(360deg);\n }\n}\n\n.jaaq-error {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n max-width: 80%;\n text-align: center;\n font-size: 14px;\n}\n\n.jaaq-video-info {\n padding: 16px;\n background: #f8f9fa;\n border-radius: 0 0 12px 12px;\n margin-top: -12px;\n}\n\n.jaaq-video-info h3 {\n margin: 0 0 8px 0;\n color: #333;\n font-size: 18px;\n font-weight: 600;\n}\n\n.jaaq-video-info p {\n margin: 4px 0;\n color: #666;\n font-size: 14px;\n}\n\n.jaaq-video-info strong {\n color: #333;\n}\n\n.jaaq-logo {\n position: absolute;\n top: 20px;\n left: 22px;\n color: white;\n font-size: 16px;\n font-weight: 600;\n z-index: 10;\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n letter-spacing: 0.5px;\n pointer-events: none;\n}\n\n.jaaq-center-play-btn {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 84px;\n height: 84px;\n background: transparent;\n border: none;\n cursor: pointer;\n z-index: 15;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n padding: 0;\n}\n\n.jaaq-center-play-btn:hover {\n transform: translate(-50%, -50%) scale(1.1);\n}\n\n.jaaq-center-play-btn svg {\n width: 100%;\n height: 100%;\n filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3));\n}\n\n.jaaq-video-player.is-playing .jaaq-center-play-btn {\n display: none;\n}\n\n.jaaq-gradient-overlay {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(180deg, transparent 0%, #0f0f0f 100%);\n padding: 80px 22px 85px;\n pointer-events: none;\n z-index: 5;\n}\n\n.jaaq-caption-display {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 400;\n font-size: 16px;\n line-height: 20px;\n color: white;\n background: rgba(0, 0, 0, 0.8);\n padding: 8px 16px;\n margin-bottom: 12px;\n border-radius: 4px;\n text-align: center;\n max-width: 90%;\n margin-left: auto;\n margin-right: auto;\n}\n\n.jaaq-video-title {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 600;\n font-size: 18.695px;\n line-height: 21.5px;\n color: white;\n margin-bottom: 8px;\n letter-spacing: 0.37px;\n}\n\n.jaaq-video-author {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 500;\n font-size: 14.021px;\n line-height: 16.825px;\n color: white;\n opacity: 0.7;\n margin-bottom: 8px;\n letter-spacing: -0.14px;\n}\n\n.jaaq-video-description {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 400;\n font-size: 11px;\n line-height: 16px;\n color: #aaa8aa;\n letter-spacing: -0.11px;\n}\n\n.jaaq-description-text {\n color: #aaa8aa;\n}\n\n.jaaq-read-more {\n color: white;\n cursor: pointer;\n pointer-events: auto;\n}\n\n.jaaq-read-more:hover {\n text-decoration: underline;\n}\n\n.jaaq-progress-bar {\n background: rgba(255, 255, 255, 0.2);\n}\n\n.jaaq-progress-filled {\n background: white;\n}\n\n.jaaq-captions-btn {\n font-size: 14px;\n font-weight: 600;\n border: 1.5px solid white;\n border-radius: 3px;\n padding: 4px 6px;\n line-height: 1;\n}\n\n.jaaq-captions-btn.active {\n background: white;\n color: #000;\n}\n";class pl{constructor(t,e){if(this.client=null,this.hls=null,this.videoElement=null,this.listeners=new Map,this.captionCues=[],this.elements={},this.container="string"==typeof t?document.querySelector(t):t,!this.container)throw new Error("Container element not found");if(this.config=e,this.state={isPlaying:!1,currentTime:0,duration:0,volume:1,isMuted:!0===e.startMuted,isFullscreen:!1,isLoading:!0,error:null,videoData:null,captionsEnabled:!1},e.client)this.client=e.client;else{if(!e.apiKey||!e.clientId)throw new Error("Please provide either a client instance or apiKey and clientId");this.client=function(t){return fl(t)}({apiKey:e.apiKey,clientId:e.clientId,baseUrl:e.baseUrl})}this.init()}async init(){this.createDOM(),await this.loadVideo(),this.attachEventListeners(),!0===this.config.startMuted&&this.updateVolumeUI()}createDOM(){this.container.innerHTML="";const t=document.createElement("div");t.style.width=this.config.width||"100%",t.style.height=this.config.height||"auto";const e=document.createElement("div");e.className=`jaaq-video-player jaaq-vanilla-player ${this.config.className||""}`,this.elements.player=e;const i=document.createElement("video");this.videoElement=i,!0===this.config.startMuted&&(i.muted=!0,i.setAttribute("muted","")),e.appendChild(i);const s=document.createElement("div");s.className="jaaq-logo",s.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" width="50" height="15" viewBox="0 0 50 15" fill="none">\n <path d="M48.0329 10.7826C48.7578 9.6622 49.1402 8.37108 49.1402 7.02322C49.1402 3.19784 46.0283 0.0859375 42.2029 0.0859375C38.3775 0.0859375 35.2656 3.19784 35.2656 7.02322C35.2656 10.8486 38.3753 13.9578 42.1985 13.9605C42.1991 13.9605 42.2002 13.9605 42.2007 13.9605H42.2029C43.8475 13.9605 45.4305 13.3687 46.6698 12.3285L49.9971 14.56V12.0999L48.0334 10.7826H48.0329ZM37.309 7.02322C37.309 4.32479 39.5045 2.12927 42.2035 2.12927C44.9024 2.12927 47.0974 4.32479 47.0974 7.02322C47.0974 7.96252 46.8345 8.862 46.3359 9.64475L43.9817 8.06561C43.4531 7.71378 42.8373 7.52778 42.2002 7.52778C40.4394 7.52778 39.0054 8.95036 38.9846 10.7062C37.9586 9.80839 37.3084 8.49053 37.3084 7.02322H37.309ZM42.2035 11.9172C42.2035 11.9172 42.2002 11.9172 42.1985 11.9172C41.5527 11.9161 41.0274 11.3903 41.0274 10.7439C41.0274 10.0975 41.5538 9.57056 42.2007 9.57056C42.4331 9.57056 42.6578 9.6382 42.8493 9.76584L44.8714 11.1224C44.0853 11.633 43.1586 11.9172 42.2029 11.9172H42.2035Z" fill="white"/>\n <path d="M31.0751 0.686201C30.9856 0.579834 30.8858 0.483286 30.7767 0.39983C30.4374 0.138004 30.0283 0 29.5946 0C29.161 0 28.7524 0.138549 28.4126 0.39983C28.2304 0.540561 28.0755 0.711838 27.9533 0.909844C27.8835 1.02276 27.8257 1.14003 27.7815 1.25785L23.1172 13.7317H25.4551L29.5946 2.66135L33.7342 13.7317H36.0721L31.4078 1.25785C31.3303 1.05003 31.218 0.858024 31.0745 0.686746L31.0751 0.686201Z" fill="white"/>\n <path d="M17.4969 0.686201C17.4075 0.579834 17.3076 0.483286 17.1986 0.39983C16.8593 0.138004 16.4502 0 16.0165 0C15.5829 0 15.1743 0.138549 14.8345 0.39983C14.6523 0.540561 14.4974 0.711838 14.3752 0.909844C14.3054 1.02276 14.2476 1.14003 14.2034 1.25785L9.53906 13.7317H11.8769L16.0165 2.66135L20.1561 13.7317H22.494L17.8302 1.25731C17.7527 1.04948 17.6404 0.857478 17.4969 0.686201Z" fill="white"/>\n <path d="M9.86046 0.511825V0.371094H7.82204V9.02333C7.82204 10.6248 6.51891 11.928 4.91741 11.928C3.47028 11.928 2.23261 10.849 2.03897 9.41771L2.01988 9.27807L1.88024 9.29716L0.13964 9.5328L0 9.5519L0.0190914 9.69154C0.348555 12.1292 2.45462 13.9669 4.91741 13.9669C7.64313 13.9669 9.86046 11.7496 9.86046 9.02388V0.511825Z" fill="white"/>\n </svg>\n ',this.elements.logo=s,e.appendChild(s);const r=document.createElement("button");r.className="jaaq-center-play-btn",r.innerHTML='\n <svg viewBox="0 0 84 84" fill="none">\n <circle cx="42" cy="42" r="42" fill="white" fill-opacity="0.9"/>\n <path d="M33 28L56 42L33 56V28Z" fill="#000"/>\n </svg>\n ',r.setAttribute("aria-label","Play video"),this.elements.centerPlayBtn=r,e.appendChild(r);const n=document.createElement("div");n.className="jaaq-gradient-overlay",this.elements.gradientOverlay=n;const a=document.createElement("div");a.className="jaaq-caption-display",a.style.display="none",this.elements.captionDisplay=a,n.appendChild(a);const o=document.createElement("div");o.className="jaaq-video-title",this.elements.videoTitle=o,n.appendChild(o);const l=document.createElement("div");l.className="jaaq-video-author",this.elements.videoAuthor=l,n.appendChild(l);const d=document.createElement("div");d.className="jaaq-video-description",this.elements.videoDescription=d,n.appendChild(d),e.appendChild(n);const h=document.createElement("div");h.className="jaaq-loading",this.elements.loading=h,e.appendChild(h);const c=document.createElement("div");c.className="jaaq-error",c.style.display="none",this.elements.error=c,e.appendChild(c);const u=document.createElement("div");u.className="jaaq-controls",this.elements.controls=u;const f=document.createElement("div");f.className="jaaq-controls-bottom";const g=document.createElement("button");g.className="jaaq-control-btn",g.textContent="▶",g.setAttribute("aria-label","Play"),this.elements.playPauseBtn=g,f.appendChild(g);const m=document.createElement("button");m.className="jaaq-control-btn",m.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287ZM14.0215 0.150391C16.2405 0.150468 18.1409 1.39074 19.4385 3.17676C20.7365 4.9634 21.499 7.36811 21.499 9.96484C21.499 12.5613 20.7363 14.9654 19.4385 16.752C18.1409 18.538 16.2405 19.7792 14.0215 19.7793V17.1025C15.2032 17.1025 16.3824 16.4464 17.3135 15.165C18.2442 13.8839 18.8593 12.0493 18.8594 9.96484C18.8594 7.88034 18.2442 6.04581 17.3135 4.76465C16.3824 3.4832 15.2033 2.82723 14.0215 2.82715V0.150391ZM14.0215 5.75879C15.5701 5.75896 16.8252 7.64189 16.8252 9.96484C16.8251 12.2877 15.57 14.1707 14.0215 14.1709V5.75879Z" fill="white"/>\n </svg>\n ',m.setAttribute("aria-label","Mute"),this.elements.volumeBtn=m,f.appendChild(m);const p=document.createElement("div");p.className="jaaq-progress-bar",this.elements.progressBar=p;const v=document.createElement("div");v.className="jaaq-progress-filled",this.elements.progressFilled=v,p.appendChild(v),f.appendChild(p);const y=document.createElement("button");y.className="jaaq-control-btn jaaq-captions-btn",y.innerHTML="CC",y.setAttribute("aria-label","Captions"),this.elements.captionsBtn=y,f.appendChild(y);const E=document.createElement("button");E.className="jaaq-control-btn",E.textContent="⛶",E.setAttribute("aria-label","Fullscreen"),this.elements.fullscreenBtn=E,f.appendChild(E),u.appendChild(f),e.appendChild(u),t.appendChild(e),this.container.appendChild(t),this.updateControlsVisibility()}updateControlsVisibility(){const t=!1!==this.config.controls;this.elements.controls&&(this.elements.controls.style.display=t?"":"none")}async loadVideo(){if(this.client&&this.videoElement)try{this.setState({isLoading:!0,error:null});const t=await this.client.videos.getById(this.config.videoId);this.setState({videoData:t}),t.subtitle&&(this.captionCues=this.parseWebVTT(t.subtitle)),this.updateOverlayContent(t),this.emit("loaded",t);const e=t.videoUrl;if(e.includes(".m3u8"))if(dl.isSupported()){this.hls&&this.hls.destroy();const t=new dl({enableWorker:!0,lowLatencyMode:!0});!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted","")),t.loadSource(e),t.attachMedia(this.videoElement),!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted","")),t.on(dl.Events.MANIFEST_PARSED,()=>{this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}),t.on(dl.Events.ERROR,(t,e)=>{if(e.fatal){const t=`HLS Error: ${e.type} - ${e.details}`;this.showError(t),this.emit("error",new Error(t))}}),this.hls=t}else{if(!this.videoElement.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS is not supported in this browser");this.videoElement.src=e,!0===this.config.startMuted&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}else this.videoElement.src=e,!0===this.config.startMuted&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}catch(t){const e=t instanceof Error?t.message:"Failed to load video";this.showError(e),this.setState({isLoading:!1}),this.emit("error",t instanceof Error?t:new Error(e))}}parseWebVTT(t){const e=[],i=t.split("\n");let s=0;for(;s<i.length;){const t=i[s].trim();if(t.includes("--\x3e")){const[r,n]=t.split("--\x3e").map(t=>t.trim()),a=t=>{const e=t.split(":");if(3===e.length){return 3600*parseFloat(e[0])+60*parseFloat(e[1])+parseFloat(e[2])}if(2===e.length){return 60*parseFloat(e[0])+parseFloat(e[1])}return 0},o=a(r),l=a(n);s++;const d=[];for(;s<i.length&&""!==i[s].trim();)d.push(i[s].trim()),s++;d.length>0&&e.push({start:o,end:l,text:d.join(" ")})}s++}return e}updateOverlayContent(t){const e=!1!==this.config.showLogo,i=!1!==this.config.showTitle,s=!1!==this.config.showAuthor,r=!1!==this.config.showDescription,n=!1!==this.config.showCaptions;if(this.elements.logo&&(this.elements.logo.style.display=e?"block":"none"),this.elements.videoTitle){const e=t.question||"",s=t.creator||"",r=s?`${e} - ${s}`:e;this.elements.videoTitle.textContent=r,this.elements.videoTitle.style.display=i&&e?"block":"none"}if(this.elements.videoAuthor){const e=t.author||t.creator||t.userName||"";this.elements.videoAuthor.textContent=e,this.elements.videoAuthor.style.display=s&&e?"block":"none"}if(this.elements.videoDescription){const e=t.creatorBiography||t.description||"";if(e){const t=150,i=e.length>t?e.substring(0,t)+"...":e;this.elements.videoDescription.innerHTML=`\n <span class="jaaq-description-text">${i}</span>\n ${e.length>t?'<span class="jaaq-read-more"> Read more</span>':""}\n `}this.elements.videoDescription.style.display=r&&e?"block":"none"}this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=n?"flex":"none")}attachEventListeners(){this.videoElement&&(this.videoElement.addEventListener("play",()=>{this.setState({isPlaying:!0}),this.updatePlayPauseButton(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="none"),this.emit("play",void 0)}),this.videoElement.addEventListener("pause",()=>{this.setState({isPlaying:!1}),this.updatePlayPauseButton(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="flex"),this.emit("pause",void 0)}),this.videoElement.addEventListener("timeupdate",()=>{this.setState({currentTime:this.videoElement.currentTime}),this.updateProgress(),this.updateCaptions(),this.emit("timeupdate",this.videoElement.currentTime)}),this.videoElement.addEventListener("durationchange",()=>{this.setState({duration:this.videoElement.duration})}),this.videoElement.addEventListener("volumechange",()=>{this.setState({volume:this.videoElement.volume,isMuted:this.videoElement.muted}),this.updateVolumeUI(),this.emit("volumechange",this.videoElement.volume)}),this.videoElement.addEventListener("ended",()=>{this.emit("ended",void 0)}),this.elements.playPauseBtn?.addEventListener("click",()=>{this.togglePlayPause()}),this.elements.centerPlayBtn?.addEventListener("click",()=>{this.play(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="none")}),this.elements.progressBar?.addEventListener("click",t=>{this.handleSeek(t)}),this.elements.volumeBtn?.addEventListener("click",()=>{this.toggleMute()}),this.elements.captionsBtn?.addEventListener("click",()=>{this.toggleCaptions()}),this.elements.fullscreenBtn?.addEventListener("click",()=>{this.toggleFullscreen()}),document.addEventListener("fullscreenchange",()=>{const t=!!document.fullscreenElement;this.setState({isFullscreen:t}),this.elements.player?.classList.toggle("fullscreen",t),this.emit("fullscreenchange",t)}),this.elements.player?.addEventListener("mousemove",()=>{this.elements.player?.classList.remove("is-paused")}),this.videoElement.addEventListener("pause",()=>{this.elements.player?.classList.add("is-paused")}),this.videoElement.addEventListener("play",()=>{this.elements.player?.classList.remove("is-paused")}))}setState(t){this.state={...this.state,...t}}updatePlayPauseButton(){this.elements.playPauseBtn&&(this.elements.playPauseBtn.textContent=this.state.isPlaying?"⏸":"▶",this.elements.playPauseBtn.setAttribute("aria-label",this.state.isPlaying?"Pause":"Play"))}updateProgress(){if(this.elements.progressFilled&&this.state.duration>0){const t=this.state.currentTime/this.state.duration*100;this.elements.progressFilled.style.width=`${t}%`}}updateVolumeUI(){if(this.elements.volumeBtn){const{isMuted:t,volume:e}=this.state;this.elements.volumeBtn.innerHTML=t||0===e?'\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287Z" fill="white"/>\n </svg>\n ':'\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287ZM14.0215 0.150391C16.2405 0.150468 18.1409 1.39074 19.4385 3.17676C20.7365 4.9634 21.499 7.36811 21.499 9.96484C21.499 12.5613 20.7363 14.9654 19.4385 16.752C18.1409 18.538 16.2405 19.7792 14.0215 19.7793V17.1025C15.2032 17.1025 16.3824 16.4464 17.3135 15.165C18.2442 13.8839 18.8593 12.0493 18.8594 9.96484C18.8594 7.88034 18.2442 6.04581 17.3135 4.76465C16.3824 3.4832 15.2033 2.82723 14.0215 2.82715V0.150391ZM14.0215 5.75879C15.5701 5.75896 16.8252 7.64189 16.8252 9.96484C16.8251 12.2877 15.57 14.1707 14.0215 14.1709V5.75879Z" fill="white"/>\n </svg>\n '}}updateCaptions(){if(!this.elements.captionDisplay||!this.state.captionsEnabled)return void(this.elements.captionDisplay&&(this.elements.captionDisplay.style.display="none"));const t=this.state.currentTime,e=this.captionCues.find(e=>t>=e.start&&t<=e.end);e?(this.elements.captionDisplay.textContent=e.text,this.elements.captionDisplay.style.display="block"):this.elements.captionDisplay.style.display="none"}handleSeek(t){if(!this.videoElement||!this.state.duration||!this.elements.progressBar)return;const e=this.elements.progressBar.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.videoElement.currentTime=this.state.duration*gl(i,0,1)}showError(t){this.setState({error:t,isLoading:!1}),this.elements.error&&(this.elements.error.textContent=t,this.elements.error.style.display="block"),this.elements.loading&&(this.elements.loading.style.display="none")}togglePlayPause(){this.state.isPlaying?this.pause():this.play()}toggleCaptions(){this.setState({captionsEnabled:!this.state.captionsEnabled}),this.updateCaptionsButton(),this.updateCaptions()}updateCaptionsButton(){this.elements.captionsBtn&&(this.state.captionsEnabled?this.elements.captionsBtn.classList.add("active"):this.elements.captionsBtn.classList.remove("active"))}toggleFullscreen(){var t;this.elements.player&&(t=this.elements.player,document.fullscreenElement?document.exitFullscreen():t.requestFullscreen())}play(){this.videoElement&&(!0!==this.config.startMuted||this.videoElement.muted||(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0})),this.videoElement.play())}pause(){this.videoElement?.pause()}setVolume(t){this.videoElement&&(this.videoElement.volume=gl(t,0,1),this.videoElement.muted=0===t)}toggleMute(){this.videoElement&&(this.videoElement.muted=!this.videoElement.muted)}seek(t){this.videoElement&&(this.videoElement.currentTime=gl(t,0,this.state.duration))}setFeatures(t){this.config={...this.config,...t},void 0!==t.controls&&this.updateControlsVisibility(),void 0!==t.startMuted&&this.videoElement&&(this.videoElement.muted=!0===t.startMuted,!0===t.startMuted?this.videoElement.setAttribute("muted",""):this.videoElement.removeAttribute("muted"),this.setState({isMuted:!0===t.startMuted}),this.updateVolumeUI()),this.state.videoData?this.updateOverlayContent(this.state.videoData):(void 0!==t.showLogo&&this.elements.logo&&(this.elements.logo.style.display=t.showLogo?"block":"none"),void 0!==t.showCaptions&&this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=t.showCaptions?"flex":"none"))}getState(){return{...this.state}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e)}off(t,e){const i=this.listeners.get(t);i&&i.delete(e)}emit(t,e){const i=this.listeners.get(t);i&&i.forEach(t=>t(e))}destroy(){this.hls&&(this.hls.destroy(),this.hls=null),this.videoElement&&(this.videoElement.pause(),this.videoElement.src="",this.videoElement=null),this.listeners.clear(),this.container.innerHTML=""}}class vl extends HTMLElement{static get observedAttributes(){return["video-id","api-key","client-id","autoplay","base-url","width","height","controls","show-logo","show-title","show-author","show-description","show-captions","start-muted"]}constructor(){super(),this.player=null,this.container=null,this.clientInstance=null,this.connected=!1,this.attachShadow({mode:"open"})}connectedCallback(){this.connected=!0,this.render(),this.initPlayer()}disconnectedCallback(){this.connected=!1,this.destroyPlayer()}attributeChangedCallback(t,e,i){if(this.connected&&e!==i)if("video-id"===t&&this.player)this.destroyPlayer(),this.initPlayer();else if("width"===t||"height"===t)this.updateContainerStyles();else if(("controls"===t||"show-logo"===t||"show-title"===t||"show-author"===t||"show-description"===t||"show-captions"===t||"start-muted"===t)&&this.player){const e={};"controls"===t?e.controls=!this.hasAttribute("controls")||"false"!==this.getAttribute("controls"):"show-logo"===t?e.showLogo=!this.hasAttribute("show-logo")||"false"!==this.getAttribute("show-logo"):"show-title"===t?e.showTitle=!this.hasAttribute("show-title")||"false"!==this.getAttribute("show-title"):"show-author"===t?e.showAuthor=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"):"show-description"===t?e.showDescription=!this.hasAttribute("show-description")||"false"!==this.getAttribute("show-description"):"show-captions"===t?e.showCaptions=!this.hasAttribute("show-captions")||"false"!==this.getAttribute("show-captions"):"start-muted"===t&&(e.startMuted=this.hasAttribute("start-muted")&&"false"!==this.getAttribute("start-muted")),this.player.setFeatures(e)}}render(){if(!this.shadowRoot)return;const t=document.createElement("style");t.textContent=`\n ${ml}\n .jaaq-vanilla-player {\n user-select: none;\n}\n\n.jaaq-vanilla-player video {\n outline: none;\n}\n\n.jaaq-collection-player {\n width: 100%;\n max-width: 1400px;\n margin: 0 auto;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n}\n\n.jaaq-collection-loading {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 400px;\n}\n\n.jaaq-collection-spinner {\n width: 50px;\n height: 50px;\n border: 4px solid rgba(0, 123, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-collection-spin 1s linear infinite;\n}\n\n@keyframes jaaq-collection-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n.jaaq-collection-error {\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n text-align: center;\n font-size: 14px;\n margin: 20px;\n}\n\n.jaaq-collection-carousel .splide__track {\n padding: 40px 0;\n}\n\n.jaaq-collection-carousel .splide__slide {\n opacity: 0.7;\n transition: all 0.3s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active {\n opacity: 1;\n}\n\n.jaaq-collection-carousel .splide__slide jaaq-video-player {\n width: 100%;\n max-width: 600px;\n transition: all 0.3s ease;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 800px;\n}\n\n.jaaq-collection-carousel .splide__arrow {\n background: rgba(0, 0, 0, 0.5);\n border: none;\n width: 48px;\n height: 48px;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n transition: all 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 20px;\n}\n\n.jaaq-collection-carousel .splide__arrow:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n}\n\n.jaaq-collection-carousel .splide__arrow:disabled {\n opacity: 0.3;\n cursor: not-allowed;\n}\n\n.jaaq-collection-carousel .splide__arrow svg {\n fill: white;\n width: 20px;\n height: 20px;\n}\n\n.jaaq-collection-carousel .splide__pagination {\n bottom: -30px;\n}\n\n.jaaq-collection-carousel .splide__pagination__page {\n background: #ccc;\n border: none;\n width: 10px;\n height: 10px;\n margin: 0 4px;\n border-radius: 50%;\n transition: all 0.2s;\n cursor: pointer;\n}\n\n.jaaq-collection-carousel .splide__pagination__page.is-active {\n background: #007bff;\n transform: scale(1.3);\n}\n\n@media (max-width: 1024px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 650px;\n }\n}\n\n@media (max-width: 768px) {\n .jaaq-collection-carousel .splide__track {\n padding: 20px 0;\n }\n\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 400px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__arrow {\n width: 40px;\n height: 40px;\n }\n}\n\n@media (max-width: 480px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 100%;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 100%;\n }\n}\n\n \n:host {\n display: block;\n width: 100%;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n `,this.container=document.createElement("div"),this.container.className="jaaq-webcomponent-container",this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(this.container),this.updateContainerStyles()}updateContainerStyles(){if(!this.container)return;const t=this.getAttribute("width")||"100%",e=this.getAttribute("height")||"auto";this.container.style.width=t,this.container.style.height=e}async initPlayer(){if(!this.container||this.player)return;const t=this.getAttribute("video-id");if(!t)return void this.emitError(new Error("video-id attribute is required"));const e=this.getAttribute("api-key"),i=this.getAttribute("client-id"),s=this.getAttribute("base-url")||void 0,r=this.hasAttribute("autoplay")&&"false"!==this.getAttribute("autoplay"),n=!this.hasAttribute("controls")||"false"!==this.getAttribute("controls"),a=!this.hasAttribute("show-logo")||"false"!==this.getAttribute("show-logo"),o=!this.hasAttribute("show-title")||"false"!==this.getAttribute("show-title"),l=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"),d=!this.hasAttribute("show-description")||"false"!==this.getAttribute("show-description"),h=!this.hasAttribute("show-captions")||"false"!==this.getAttribute("show-captions"),c=this.hasAttribute("start-muted")&&"false"!==this.getAttribute("start-muted");if(this.clientInstance||e||i)try{this.player=new pl(this.container,{videoId:t??void 0,apiKey:e??void 0,clientId:i??void 0,client:this.clientInstance||void 0,baseUrl:s,autoplay:r,controls:n,showLogo:a,showTitle:o,showAuthor:l,showDescription:d,showCaptions:h,startMuted:c}),this.attachPlayerEvents()}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to initialize player"))}else this.emitError(new Error("Either client property or api-key and client-id attributes are required"))}attachPlayerEvents(){this.player&&(this.player.on("loaded",t=>{this.dispatchEvent(new CustomEvent("jaaq:loaded",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("play",()=>{this.dispatchEvent(new CustomEvent("jaaq:play",{bubbles:!0,composed:!0}))}),this.player.on("pause",()=>{this.dispatchEvent(new CustomEvent("jaaq:pause",{bubbles:!0,composed:!0}))}),this.player.on("timeupdate",t=>{this.dispatchEvent(new CustomEvent("jaaq:timeupdate",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("volumechange",t=>{this.dispatchEvent(new CustomEvent("jaaq:volumechange",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("ended",()=>{this.dispatchEvent(new CustomEvent("jaaq:ended",{bubbles:!0,composed:!0}))}),this.player.on("error",t=>{this.emitError(t)}),this.player.on("fullscreenchange",t=>{this.dispatchEvent(new CustomEvent("jaaq:fullscreenchange",{detail:t,bubbles:!0,composed:!0}))}))}emitError(t){this.dispatchEvent(new CustomEvent("jaaq:error",{detail:t,bubbles:!0,composed:!0}))}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null)}get client(){return this.clientInstance}set client(t){this.clientInstance=t,this.connected&&(this.destroyPlayer(),this.initPlayer())}get videoId(){return this.getAttribute("video-id")}set videoId(t){t?this.setAttribute("video-id",t):this.removeAttribute("video-id")}play(){this.player?.play()}pause(){this.player?.pause()}setVolume(t){this.player?.setVolume(t)}toggleMute(){this.player?.toggleMute()}seek(t){this.player?.seek(t)}getState(){return this.player?.getState()||null}destroy(){this.destroyPlayer()}}function yl(t,e,i){return e&&function(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).JaaqWebComponents={})}(this,function(t){"use strict";const e=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},i=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=s},s=Number.MAX_SAFE_INTEGER||9007199254740991;let r=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),n=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),a=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var o="manifest",l="level",d="audioTrack",h="subtitleTrack",c="main",u="audio",f="subtitle";class g{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class m{constructor(t,e,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 g(t),this.fast_=new g(e),this.defaultTTFB_=s,this.ttfb_=new g(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new g(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new g(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new g(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const i=(t=Math.max(t,this.minDelayMs_))/1e3,s=8*e/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,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 p(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var s=i.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function v(){return v=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)({}).hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},v.apply(null,arguments)}function y(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,s)}return i}function E(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?y(Object(i),!0).forEach(function(e){p(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):y(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}class T{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${t}]:`;this.trace=S,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const S=function(){},b={trace:S,debug:S,log:S,warn:S,info:S,error:S};function A(){return v({},b)}function L(t,e,i){return e[t]?e[t].bind(e):function(t,e){const i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):S}(t,i)}const I=A();const R=I;function k(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function _(t,e){const i=Object.keys(t),s=Object.keys(e),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(t=>-1===s.indexOf(t))}function w(t,e=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(t);if(e){const t=i.indexOf("\0");return-1!==t?i.substring(0,t):i}return i.replace(/\0/g,"")}const i=t.length;let s,r,n,a="",o=0;for(;o<i;){if(s=t[o++],0===s&&e)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=t[o++],a+=String.fromCharCode((31&s)<<6|63&r);break;case 14:r=t[o++],n=t[o++],a+=String.fromCharCode((15&s)<<12|(63&r)<<6|63&n)}}return a}function D(t){let e="";for(let i=0;i<t.length;i++){let s=t[i].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function P(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function C(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var x,M={exports:{}};var O=(x||(x=1,function(t){var e,i,s,r,n;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var r=n.parseURL(t);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(e);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)):e;var o=n.parseURL(t);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(t){var i=e.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(s,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=n}(M)),M.exports);class F{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 N="audio",B="video",U="audiovideo";class ${constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const i=H(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let s;s=1===i.length?(null==e?void 0:e.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={[N]:null,[B]:null,[U]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new F),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=O.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[N]=null,t[B]=null,t[U]=null}}function G(t){return"initSegment"!==t.sn}class K extends ${constructor(t,e){super(e),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=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],i=this.byteRange[1];if(e(t)&&e(i))return i-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const i=this._decryptdata=e[t[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=e(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){e(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return G(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var i;const s=e[t];!s||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=s.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:n}}}class V extends ${constructor(t,e,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=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const n=t.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:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function H(t,e){const i=Object.getPrototypeOf(t);if(i){const t=Object.getOwnPropertyDescriptor(i,e);return t||H(i,e)}}const j=Math.pow(2,32)-1,q=[].push,Y={video:1,audio:2,id3:3,text:4};function W(t){return String.fromCharCode.apply(null,t)}function z(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function X(t,e){const i=Z(t,e);return i<0?4294967296+i:i}function Q(t,e){let i=X(t,e);return i*=Math.pow(2,32),i+=X(t,e+4),i}function Z(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function J(t,e){const i=[];if(!e.length)return i;const s=t.byteLength;for(let r=0;r<s;){const n=X(t,r),a=n>1?r+n:s;if(W(t.subarray(r+4,r+8))===e[0])if(1===e.length)i.push(t.subarray(r+8,a));else{const s=J(t.subarray(r+8,a),e.slice(1));s.length&&q.apply(i,s)}r=a}return i}function tt(t){const e=[],i=t[0];let s=8;const r=X(t,s);s+=4;let n=0,a=0;0===i?(n=X(t,s),a=X(t,s+4),s+=8):(n=Q(t,s),a=Q(t,s+8),s+=16),s+=2;let o=t.length+a;const l=z(t,s);s+=2;for(let i=0;i<l;i++){let i=s;const n=X(t,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return R.warn("SIDX has hierarchical references (not supported)"),null;const l=X(t,i);i+=4,e.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:e}}function et(t){const e=[],i=J(t,["moov","trak"]);for(let t=0;t<i.length;t++){const s=i[t],r=J(s,["tkhd"])[0];if(r){let t=r[0];const i=X(r,0===t?12:20),n=J(s,["mdia","mdhd"])[0];if(n){t=n[0];const r=X(n,0===t?12:20),a=J(s,["mdia","hdlr"])[0];if(a){const t=W(a.subarray(8,12)),n={soun:N,vide:B}[t],o=it(J(s,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:r,type:n,stsd:o},e[n]=E({timescale:r,id:i},o)):e[i]={timescale:r,type:t,stsd:o}}}}}return J(t,["moov","mvex","trex"]).forEach(t=>{const i=X(t,4),s=e[i];s&&(s.default={duration:X(t,12),flags:X(t,20)})}),e}function it(t){const e=t.subarray(8),i=e.subarray(86),s=W(e.subarray(4,8));let r,n=s;const a="enca"===s||"encv"===s;if(a){const t=J(e,[s])[0];J(t.subarray("enca"===s?28:78),["sinf"]).forEach(t=>{const e=J(t,["schm"])[0];if(e){const i=W(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=J(t,["frma"])[0];e&&(n=W(e))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=J(i,["avcC"])[0];t&&t.length>3&&(n+="."+nt(t[1])+nt(t[2])+nt(t[3]),r=st("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=J(e,[s])[0],i=J(t.subarray(28),["esds"])[0];if(i&&i.length>7){let t=4;if(3!==i[t++])break;t=rt(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=rt(i,t);const s=i[t++];if(64!==s)break;if(n+="."+nt(s),t+=12,5!==i[t++])break;t=rt(i,t);const r=i[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=J(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],s=31&e,r=X(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+i+s,n+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}n+=d}r=st("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=st(n,i)||n;break;case"vp09":{const t=J(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],s=t[6]>>4&15;n+="."+at(e)+"."+at(i)+"."+at(s)}break}case"av01":{const t=J(i,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,s=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,h=(16&t[2])>>4,c=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+at(s)+a+"."+at(d)+"."+h+"."+c+u+f+"."+at(g)+"."+at(m)+"."+at(p)+"."+v,r=st("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:r}}function st(t,e){const i=J(e,["dvvC"]),s=i.length?i[0]:J(e,["dvcC"])[0];if(s){const e=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return t+"."+at(e)+"."+at(i)}}function rt(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function nt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function at(t){return(t<10?"0":"")+t}function ot(t,e){J(t,["moov","trak"]).forEach(t=>{const i=J(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let r=J(s,["enca"]);const n=r.length>0;n||(r=J(s,["encv"])),r.forEach(t=>{J(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const i=lt(t);i&&e(i,n)})})})}function lt(t){const e=J(t,["schm"])[0];if(e){const i=W(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=J(t,["schi","tenc"])[0];if(e)return e}}}function dt(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function ht(t,e){const i=[],s=e.samples,r=e.timescale,n=e.id;let a=!1;return J(s,["moof"]).map(o=>{const l=o.byteOffset-8;J(o,["traf"]).map(o=>{const d=J(o,["tfdt"]).map(t=>{const e=t[0];let i=X(t,4);return 1===e&&(i*=Math.pow(2,32),i+=X(t,8)),i/r})[0];return void 0!==d&&(t=d),J(o,["tfhd"]).map(d=>{const h=X(d,4),c=16777215&X(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=X(d,p),p+=4),f&&(g=X(d,p),p+=4),m&&(p+=4),"video"===e.type&&(a=ct(e.codec)),J(o,["trun"]).map(n=>{const o=n[0],d=16777215&X(n,0),h=!!(1&d);let c=0;const f=!!(4&d),m=!!(256&d);let p=0;const v=!!(512&d);let y=0;const E=!!(1024&d),T=!!(2048&d);let S=0;const b=X(n,4);let A=8;h&&(c=X(n,A),A+=4),f&&(A+=4);let L=c+l;for(let l=0;l<b;l++){if(m?(p=X(n,A),A+=4):p=u,v?(y=X(n,A),A+=4):y=g,E&&(A+=4),T&&(S=0===o?X(n,A):Z(n,A),A+=4),e.type===B){let e=0;for(;e<y;){const n=X(s,L);if(L+=4,ut(a,s[L])){ft(s.subarray(L,L+n),a?2:1,t+S/r,i)}L+=n,e+=n+4}}t+=p/r}}))})})}),i}function ct(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function ut(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function ft(t,e,i,s){const r=gt(t);let n=0;n+=e;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 t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){R.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=z(r,e);if(e+=2,49===t){const t=X(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=r[e++]}s.push({type:t,payloadType:a,pts:i,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const s=r[e++].toString(16);t.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=r[e++];s.push({payloadType:a,pts:i,uuid:t.join(""),userData:w(l),userDataBytes:l})}}}function gt(t){const e=t.byteLength,i=[];let s=1;for(;s<e-2;)0===t[s]&&0===t[s+1]&&3===t[s+2]?(i.push(s+2),s+=2):s++;if(0===i.length)return t;const r=e-i.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===i[0]&&(a++,i.shift()),n[s]=t[a];return n}function mt(t,e,i){if(16!==t.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(t,...e){const i=e.length;let s=8,r=i;for(;r--;)s+=e[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(t,4),r=0,s=8;r<i;r++)n.set(e[r],s),s+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,i)}function pt(t){const e=t.getUint32(0),i=t.byteOffset,s=t.byteLength;if(s<e)return{offset:i,size:s};if(1886614376!==t.getUint32(4))return{offset:i,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:e};const n=t.buffer,a=D(new Uint8Array(n,i+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=t.getUint32(28);if(!r||s<32+16*r)return{offset:i,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(n,i+32+16*t,16));d=32+16*r}if(!d)return{offset:i,size:e};const h=t.getUint32(d);return e-32<h?{offset:i,size:e}:(l=new Uint8Array(n,i+d+4,h),{version:r,systemId:a,kids:o,data:l,offset:i,size:e})}const vt=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),yt={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 Et(t,e){const i=yt[e];return!!i&&!!i[t.slice(0,4)]}function Tt(t,e,i=!0){return!t.split(",").some(t=>!St(t,e,i))}function St(t,e,i=!0){var s;const r=k(i);return null!=(s=null==r?void 0:r.isTypeSupported(bt(t,e)))&&s}function bt(t,e){return`${e}/mp4;codecs=${t}`}function At(t){if(t){const e=t.substring(0,4);return yt.video[e]}return 2}function Lt(t){const e=vt();return t.split(",").reduce((t,i)=>{const s=e&&ct(i)?9:yt.video[i];return s?(2*s+t)/(t?3:2):(yt.audio[i]+t)/(t?2:1)},0)}const It={};const Rt=/flac|opus|mp4a\.40\.34/i;function kt(t,e=!0){return t.replace(Rt,t=>function(t,e=!0){if(It[t])return It[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<i.length;r++){var s;if(St(i[r],"audio",e))return It[t]=i[r],i[r];if("mp3"===i[r]&&null!=(s=k(e))&&s.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function _t(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(wt(t,"audio")||wt(t,"video")))return t;if(e){const i=e.split(",");if(i.length>1){if(t)for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e];return i[0]}}return e||t}function wt(t,e){return Et(t,e)&&St(t,e)}function Dt(t){if(t.startsWith("av01.")){const e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}function Pt(t){const e=k(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ct(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const xt={supported:!1,smooth:!1,powerEfficient:!1},Mt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Ot(t,e){return{supported:!1,configurations:e,decodingInfoResults:[xt],error:t}}function Ft(t,i,s,r,n,a){const o=t.videoCodec,l=t.audioCodec?t.audioGroups:null,d=null==a?void 0:a.audioCodec,h=null==a?void 0:a.channels,c=h?parseInt(h):d?1/0:2;let u=null;if(null!=l&&l.length)try{u=1===l.length&&l[0]?i.groups[l[0]].channels:l.reduce((t,e)=>{if(e){const s=i.groups[e];if(!s)throw new Error(`Audio track group ${e} not found`);Object.keys(s.channels).forEach(e=>{t[e]=(t[e]||0)+s.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==o&&(o.split(",").some(t=>ct(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(n,8e6))||!!u&&e(c)&&Object.keys(u).some(t=>parseInt(t)>c)}function Nt(t,e,i,s={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!i)return Promise.resolve(Mt);const n=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),s=Ut(t),r=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map(t=>{const e={contentType:bt(Dt(t),"video"),width:r,height:n,bitrate:s,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,i){var s;const r=null==(s=t.audioCodec)?void 0:s.split(","),n=Ut(t);if(r&&t.audioGroups)return t.audioGroups.reduce((t,s)=>{var a;const o=s?null==(a=e.groups[s])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===s){const s=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:bt(e,"audio"),bitrate:i?Bt(e,n):n};s&&(r.channels=""+s),t.push(r)})}return t},t):t},[]);return[]}(t,e,o>0),d=l.length;for(let t=o||1*d||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),d){e.audio=l[t%d];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}n.push(e)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>ct(t))&&vt())return Promise.resolve(Ot(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:i,video:s}=t;if(s){e+=`${Ct(s.contentType)}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){e+=`${s?"_":""}${Ct(i.contentType)}_c${i.channels}`}return e}(t);return s[e]||(s[e]=i.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function Bt(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function Ut(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}const $t=["NONE","TYPE-0","TYPE-1",null];const Gt=["SDR","PQ","HLG"];var Kt="",Vt="YES",Ht="v2";function jt(t){const{canSkipUntil:e,canSkipDateRanges:i,age:s}=t;return e&&s<e/2?i?Ht:Vt:Kt}class qt{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class Yt{constructor(t){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=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.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(t){return Wt(this._audioGroups,t)}hasSubtitleGroup(t){return Wt(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function Wt(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function zt(t,e){let i=!1,s=[];if(t&&(i="SDR"!==t,s=[t]),e){s=e.allowedVideoRanges||Gt.slice(0);const t="SDR"!==s.join("")&&!e.videoCodec;i=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}const Xt=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(i,s)=>{if(t&&(s=t(i,s)),"object"==typeof s&&null!==s){if(e.has(s))return;e.add(s)}return s}})(e));function Qt(t,e){R.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Zt(t){return t.reduce((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const s=e.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Jt(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}=t;return{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function te(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let s=0;s<e.length;s++){if(ee(t,e[s],i))return s}return-1}function ee(t,e,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===s||e.groupId===s)&&(void 0===r||e.name===r)&&(void 0===n||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===n||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const i=t.split(","),s=e.split(",");return i.length===s.length&&!i.some(t=>-1===s.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function ie(t,e){const{audioCodec:i,channels:s}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(e.channels||"2"))}function se(t,e,i){for(let s=e;s>-1;s--)if(i(t[s]))return s;for(let s=e+1;s<t.length;s++)if(i(t[s]))return s;return-1}function re(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}const ne=function(t,e){let i=0,s=t.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=t[r];const a=e(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function ae(t,e,i=0,s=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const s=t.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===oe(i,s,n)||function(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),i);return t.start<=s}return!1}(n,t,Math.min(r,s))))return n;const a=ne(e,oe.bind(null,i,s));return!a||a===t&&n?n:a}function oe(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const s=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=t?1:i.start-s>t&&i.start?-1:0}function le(t,e,i){const s=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>t}function de(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let s=t.fragments;const{fragmentHint:r}=t;let n;return r&&(s=s.concat(r)),ne(s,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=i?1:t.start>i?-1:0)),n||null}return null}function he(t){switch(t.details){case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_TIMEOUT:case n.LEVEL_LOAD_TIMEOUT:case n.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ce(t){return t.details.startsWith("key")}function ue(t){return ce(t)&&!!t.frag&&!t.frag.decryptdata}function fe(t,e){const i=he(e);return t.default[(i?"timeout":"error")+"Retry"]}function ge(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function me(t){return E(E({},t),{errorRetry:null,timeoutRetry:null})}function pe(t,e,i,s){if(!t)return!1;const r=null==s?void 0:s.code,n=e<t.maxNumRetry&&(function(t){return ve(t)||!!t&&(t<400||t>499)}(r)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,s,n):n}function ve(t){return 0===t&&!1===navigator.onLine}var ye=0,Ee=2,Te=3,Se=5,be=0,Ae=1,Le=2,Ie=4;function Re(t){const e={action:ye,flags:be};return t&&(e.resolved=!0),e}var ke="NOT_LOADED",_e="APPENDING",we="PARTIAL",De="OK";class Pe{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const s=i[e];if(!s)break;if(s.start<=t&&t<=s.end&&s.loaded)return s}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,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)===e&&(!i||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,s,r){this.timeRanges&&(this.timeRanges[t]=e);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[t];o&&(0!==o.time.length?o.time.some(t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(a.body),i}):this.removeFragment(a.body))})}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const i=t.frag,s=xe(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const n=!i.relurl;Object.keys(e).forEach(s=>{const a=i.elementaryStreams[s];if(!a)return;const o=e[s],l=n||!0===a.partial;r.range[s]=this.getBufferedTimes(i,t.part,l,o)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),Ce(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Me(i,e=>e.fragment.sn>=t))}fragBuffered(t,e){const i=xe(t);let s=this.fragments[i];!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,t))}getBufferedTimes(t,e,i,s){const r={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<s.length;t++){const e=s.start(t)-this.bufferPadding,i=s.end(t)+this.bufferPadding;if(l>=e&&o<=i){r.time.push({startPTS:Math.max(n,s.start(t)),endPTS:Math.min(a,s.end(t))});break}if(n<i&&a>e){const e=Math.max(n,s.start(t)),i=Math.min(a,s.end(t));i>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return r}getPartialFragment(t){let e,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&Ce(d)&&(i=d.body.start-a,s=d.body.end+a,t>=i&&t<=s&&(e=Math.min(t-i,s-t),n<=e&&(r=d.body,n=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Ce(e))}getState(t){const e=xe(t),i=this.fragments[e];return i?i.buffered?Ce(i)?we:De:_e:ke}isTimeBuffered(t,e,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,t>=s&&e<=r)return!0;if(e<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const i=e.frag,s=e.part?null:e,r=xe(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:r,type:n}=e;if("initSegment"===i.sn)return;const a=i.type;if(s){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(s)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,s)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=xe(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let s=i.length;s--;){const r=e[i[s]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,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<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=xe(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=Me(i,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function Ce(t){var e,i,s;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(s=t.range.audiovideo)&&s.partial)}function xe(t){return`${t.type}_${t.level}_${t.sn}`}function Me(t,e){return t.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Oe=0,Fe=1;class Ne{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case Oe:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case Fe:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Be{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_(t){const e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=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,t[f]=i,e[i]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[i]^16843008*i;s[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,d[i]=v<<16|v>>>16,h[i]=v<<8|v>>>24,c[i]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s<e.length&&i;)i=e[s]===this.key[s],s++;if(i)return;this.key=e;const r=this.keySize=e.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 v,y;for(a=0;a<n;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^m[h[y>>>8&255]]^p[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,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(t),v=new Int32Array(p.length);let y,E,T,S,b,A,L,I,R,k,_,w,D,P;const C=this.networkToHostOrderSwap;for(;e<p.length;){for(R=C(p[e]),k=C(p[e+1]),_=C(p[e+2]),w=C(p[e+3]),b=R^r[0],A=w^r[1],L=_^r[2],I=k^r[3],D=4,P=1;P<s;P++)y=o[b>>>24]^l[A>>16&255]^d[L>>8&255]^h[255&I]^r[D],E=o[A>>>24]^l[L>>16&255]^d[I>>8&255]^h[255&b]^r[D+1],T=o[L>>>24]^l[I>>16&255]^d[b>>8&255]^h[255&A]^r[D+2],S=o[I>>>24]^l[b>>16&255]^d[A>>8&255]^h[255&L]^r[D+3],b=y,A=E,L=T,I=S,D+=4;y=n[b>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&I]^r[D],E=n[A>>>24]<<24^n[L>>16&255]<<16^n[I>>8&255]<<8^n[255&b]^r[D+1],T=n[L>>>24]<<24^n[I>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^r[D+2],S=n[I>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^r[D+3],v[e]=C(y^u),v[e+1]=C(S^f),v[e+2]=C(T^g),v[e+3]=C(E^m),u=R,f=k,g=_,m=w,e+=4}return v.buffer}}class Ue{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=function(t){switch(t){case Oe:return"AES-CBC";case Fe:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class $e{constructor(t,{removePKCS7Padding:e=!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=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}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:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,s){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==Oe||16!==e.byteLength)return R.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=dt(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Be),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,i,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,s));this.key=e,this.fastAesKey=new Ue(this.subtle,e,s)}return this.fastAesKey.expandKey().then(e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Ne(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,e)}).catch(r=>(R.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(R.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Ge=Math.pow(2,17);class Ke{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const i=t.url;if(!i)return Promise.reject(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const s=this.config,a=s.fLoader,o=s.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void d(He(t));t.gap=!1}const h=this.loader=a?new a(s):new o(s),c=Ve(t);t.loader=h;const u=me(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Ge};t.stats=h.stats;const g={onSuccess:(e,i,s,r)=>{this.resetLoader(t,h);let n=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),l({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,s,a,o)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:E({url:i,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:a,stats:o}))},onAbort:(e,i,s)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:(e,i,s)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:s,stats:e}))}};e&&(g.onProgress=(i,s,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})),h.load(c,f,g)})}loadPart(t,e,i){this.abort();const s=this.config,a=s.fLoader,o=s.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void d(He(t,e));const h=this.loader=a?new a(s):new o(s),c=Ve(t,e);t.loader=h;const u=me(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ge};e.stats=h.stats,h.load(c,f,{onSuccess:(s,r,n,a)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:s.data,networkDetails:a};i(o),l(o)},onError:(i,s,a,o)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:E({url:c.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:a,stats:o}))},onAbort:(i,s,a)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:a,stats:i}))},onTimeout:(i,s,a)=>{this.resetLoader(t,h),d(new je({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:a,stats:i}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(t.duration/e.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(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Ve(t,i=null){const s=i||t,r={frag:t,part:i,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=s.byteRangeStartOffset,a=s.byteRangeEndOffset;if(e(n)&&e(a)){var o;let e=n,i=a;if("initSegment"===t.sn&&("AES-128"===(l=null==(o=t.decryptdata)?void 0:o.method)||"AES-256"===l)){const t=a-n;t%16&&(i=a+(16-t%16)),0!==n&&(r.resetIV=!0,e=n-16)}r.rangeStart=e,r.rangeEnd=i}var l;return r}function He(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:r.MEDIA_ERROR,details:n.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(s.part=e),(e||t).stats.aborted=!0,new je(s)}class je extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class qe extends T{constructor(t,e){super(t,e),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(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!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 Ye{constructor(t,e,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=t,this.sn=e,this.id=i,this.size=s,this.part=r,this.partial=n}}const We={length:0,start:()=>0,end:()=>0};class ze{static isBuffered(t,e){if(t){const i=ze.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=ze.getBuffered(t);return ze.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const s=ze.bufferedRanges(t);if(s.length)return ze.bufferedInfo(s,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let s=-1,r=[];if(i)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(s=n);const a=r.length;if(a){const e=r[a-1].end;t[n].start-e<i?t[n].end>e&&(r[a-1].end=t[n].end):r.push(t[n])}else r.push(t[n])}else r=t;let n,a=0,o=e,l=e;for(let t=0;t<r.length;t++){const d=r[t].start,h=r[t].end;if(-1===s&&e>=d&&e<=h&&(s=t),e+i>=d&&e<h)o=d,l=h,a=l-e;else if(e+i<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||We}catch(t){return R.log("failed to get media.buffered",t),We}}}const Xe=/\{\$([a-zA-Z0-9-_]+)\}/g;function Qe(t){return Xe.test(t)}function Ze(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(Xe,e=>{const s=e.substring(2,e.length-1),r=null==i?void 0:i[s];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),e):r})}return e}function Je(t,e,i){let s,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){s=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=t.get(s)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else s=e.NAME,r=e.VALUE;s in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function ti(t,e,i){const s=e.IMPORT;if(i&&s in i){let e=t.variableList;e||(t.variableList=e={}),e[s]=i[s]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const ei=/^(\d+)x(\d+)$/,ii=/(.+?)=(".*?"|.*?)(?:,|$)/g;class si{constructor(t,e){"string"==typeof t&&(t=si.parseAttrList(t,e)),v(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=ei.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const s={};for(ii.lastIndex=0;null!==(i=ii.exec(t));){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(e&&(a||o))n=Ze(e,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":R.warn(`${t}: attribute ${r} is missing quotes`)}s[r]=n}return s}}function ri(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function ni(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class ai{constructor(t,i,s=0){var r;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==i?void 0:i.tagAnchor)||null,this.tagOrder=null!=(r=null==i?void 0:i.tagOrder)?r:s,i){const e=i.attr;for(const i in e)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==e[i]){R.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=i;break}t=v(new si({}),e,t)}if(this.attr=t,i?(this._startDate=i._startDate,this._cue=i._cue,this._endDate=i._endDate,this._dateAtEnd=i._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==i?void 0:i.endDate)||new Date(this.attr["END-DATE"]);e(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(R.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(e(t))return t}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&&e(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 oi{constructor(t){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=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&e(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.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 t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function li(t,e){return t.length===e.length&&!t.some((t,i)=>t!==e[i])}function di(t,e){return!t&&!e||!(!t||!e)&&li(t,e)}function hi(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function ci(t){switch(t){case"AES-128":case"AES-256":return Oe;case"AES-256-CTR":return Fe;default:throw new Error(`invalid full segment method ${t}`)}}function ui(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function fi(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function gi(t){const e=function(t,e,i){const s=t[e];t[e]=t[i],t[i]=s};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function mi(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),s=t[t.length-1].split(",");if(2===s.length){const e="base64"===s[0],r=s[1];e?(t.splice(-1,1),i=ui(r)):i=function(t){const e=fi(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(r)}}return i}const pi="undefined"!=typeof self?self:void 0;var vi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},yi="org.w3.clearkey",Ei="com.apple.streamingkeydelivery",Ti="com.microsoft.playready",Si="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function bi(t){switch(t){case Ei:return vi.FAIRPLAY;case Ti:return vi.PLAYREADY;case Si:return vi.WIDEVINE;case yi:return vi.CLEARKEY}}function Ai(t){switch(t){case vi.FAIRPLAY:return Ei;case vi.PLAYREADY:return Ti;case vi.WIDEVINE:return Si;case vi.CLEARKEY:return yi}}function Li(t){const{drmSystems:e,widevineLicenseUrl:i}=t,s=e?[vi.FAIRPLAY,vi.WIDEVINE,vi.PLAYREADY,vi.CLEARKEY].filter(t=>!!e[t]):[];return!s[vi.WIDEVINE]&&i&&s.push(vi.WIDEVINE),s}const Ii=null!=pi&&null!=(Ri=pi.navigator)&&Ri.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Ri;function ki(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),i=String.fromCharCode.apply(null,Array.from(e)),s=i.substring(i.indexOf("<"),i.length),r=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const t=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(t){const e=ui(t).subarray(0,16);return gi(e),e}}return null}let _i={};class wi{static clearKeyUriToKeyIdMap(){_i={}}static setKeyIdForUri(t,e){_i[t]=e}static addKeyIdForUri(t){const e=Object.keys(_i).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),_i[t]=i,i}constructor(t,e,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=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!hi(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(P(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&li(t.keyFormatVersions,this.keyFormatVersions)&&di(t.iv,this.iv)&&di(t.keyId,this.keyId)}isSupported(){if(this.method){if(hi(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Ei:case Si:case Ti:case yi:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(hi(this.method)){let e=this.iv;e||("number"!=typeof t&&(R.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),e=function(t){const e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t));return new wi(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){const t=_i[this.uri];if(t&&!li(this.keyId,t)&&wi.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=mi(this.uri);if(i)switch(this.keyFormat){case Si:if(this.pssh=i,!this.keyId){const t=function(t){const e=[];if(t instanceof ArrayBuffer){const i=t.byteLength;let s=0;for(;s+32<i;){const i=pt(new DataView(t,s));e.push(i),s+=i.size}}return e}(i.buffer);if(t.length){var s;const e=t[0];this.keyId=null!=(s=e.kids)&&s.length?e.kids[0]:null}}this.keyId||(this.keyId=Di(e));break;case Ti:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mt(t,0,i),this.keyId=ki(i);break}default:{let t=i.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t;t=function(t){const e=null==t?void 0:t[Si];if(e)return e.keyId;return null}(e),t||(t=Di(e),t||(t=_i[this.uri])),t&&(this.keyId=t,wi.setKeyIdForUri(this.uri,t))}return this}}function Di(t){const e=null==t?void 0:t[Ti];if(e){const t=mi(e.uri);if(t)return ki(t)}return null}const Pi=/#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,Ci=/#EXT-X-MEDIA:(.*)/g,xi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Mi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Oi=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 Fi{static findGroup(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(s.id===e)return s}}static resolve(t,e){return O.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return xi.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Qe(t)},s=[];if(Pi.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=Pi.exec(t));)if(r[1]){var n;const t=new si(r[1],i),a=Ze(i,r[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Fi.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Gi(t.CODECS,o);const d=t["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},Gi(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||s.push(o),i.levels.push(o)}else if(r[3]){const t=r[3],s=r[4];switch(t){case"SESSION-DATA":{const t=new si(s,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Ui(s,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):R.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${s}"`);break}case"DEFINE":Je(i,new si(s,i),e);break;case"CONTENT-STEERING":{const t=new si(s,i);i.contentSteering={uri:Fi.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=$i(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(t,e,i){let s;const r={},n=i.levels,a={AUDIO:n.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:n.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(Ci.lastIndex=0;null!==(s=Ci.exec(t));){const t=new si(s[1],i),n=t.TYPE;if(n){const i=a[n],s=r[n]||[];r[n]=s;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],h=t.CHANNELS,c=t.CHARACTERISTICS,u=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Fi.resolve(t.URI,e):""};if(d&&(f.assocLang=d),h&&(f.channels=h),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=i&&i.length){const t=Fi.findGroup(i,f.groupId)||i[0];Ki(f,t,"audioCodec"),Ki(f,t,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(t,i,s,r,n,a){var o;const l={url:i},d=new oi(i),h=d.fragments,c=[];let u,f,g,m,p=null,y=0,E=0,T=0,S=0,b=0,A=null,L=new K(r,l),I=-1,k=!1,_=null;if(Mi.lastIndex=0,d.m3u8=t,d.hasVariableRefs=Qe(t),"#EXTM3U"!==(null==(o=Mi.exec(t))?void 0:o[0]))return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;null!==(u=Mi.exec(t));){k&&(k=!1,L=new K(r,l),L.playlistOffset=T,L.setStart(T),L.sn=y,L.cc=S,b&&(L.bitrate=b),L.level=s,p&&(L.initSegment=p,p.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),_&&(L.setByteRange(_),_=null)));const t=u[1];if(t){L.duration=parseFloat(t);const e=(" "+u[2]).slice(1);L.title=e||null,L.tagList.push(e?["INF",t,e]:["INF",t])}else if(u[3]){if(e(L.duration)){L.playlistOffset=T,L.setStart(T),g&&ji(L,g,d),L.sn=y,L.level=s,L.cc=S,h.push(L);const t=(" "+u[3]).slice(1);L.relurl=Ze(d,t),Vi(L,A,c),A=L,T+=L.duration,y++,E=0,k=!0}}else{if(u=u[0].match(Oi),!u){R.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<u.length&&void 0===u[f];f++);const t=(" "+u[f]).slice(1),n=(" "+u[f+1]).slice(1),o=u[f+2]?(" "+u[f+2]).slice(1):null;switch(t){case"BYTERANGE":A?L.setByteRange(n,A):L.setByteRange(n);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=n,L.tagList.push(["PROGRAM-DATE-TIME",n]),-1===I&&(I=h.length);break;case"PLAYLIST-TYPE":d.type&&qi(d,t,u),d.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":0!==d.startSN?qi(d,t,u):h.length>0&&Yi(d,t,u),y=d.startSN=parseInt(n);break;case"SKIP":{d.skippedSegments&&qi(d,t,u);const i=new si(n,d),s=i.decimalInteger("SKIPPED-SEGMENTS");if(e(s)){d.skippedSegments+=s;for(let t=s;t--;)h.push(null);y+=s}const r=i.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(r.split("\t")));break}case"TARGETDURATION":0!==d.targetduration&&qi(d,t,u),d.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==d.version&&qi(d,t,u),d.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||qi(d,t,u),d.live=!1;break;case"#":(n||o)&&L.tagList.push(o?[n,o]:[n]);break;case"DISCONTINUITY":S++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([t]);break;case"BITRATE":L.tagList.push([t,n]),b=1e3*parseInt(n),e(b)?L.bitrate=b:b=0;break;case"DATERANGE":{const t=new si(n,d),e=new ai(t,d.dateRanges[t.ID],d.dateRangeTagCount);d.dateRangeTagCount++,e.isValid||d.skippedSegments?d.dateRanges[e.id]=e:R.warn(`Ignoring invalid DATERANGE tag: "${n}"`),L.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new si(n,d);"IMPORT"in t?ti(d,t,a):Je(d,t,i)}break;case"DISCONTINUITY-SEQUENCE":0!==d.startCC?qi(d,t,u):h.length>0&&Yi(d,t,u),d.startCC=S=parseInt(n);break;case"KEY":{const t=Ui(n,i,d);if(t.isSupported()){if("NONE"===t.method){g=void 0;break}g||(g={});const e=g[t.keyFormat];null!=e&&e.matches(t)||(e&&(g=v({},g)),g[t.keyFormat]=t)}else R.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${n}"`);break}case"START":d.startTimeOffset=$i(n);break;case"MAP":{const t=new si(n,d);if(L.duration){const e=new K(r,l);Hi(e,t,s,g),p=e,L.initSegment=p,p.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime)}else{const e=L.byteRangeEndOffset;if(e){const t=L.byteRangeStartOffset;_=`${e-t}@${t}`}else _=null;Hi(L,t,s,g),p=L,k=!0}p.cc=S;break}case"SERVER-CONTROL":m&&qi(d,t,u),m=new si(n),d.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),d.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{d.partTarget&&qi(d,t,u);const e=new si(n);d.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=d.partList;t||(t=d.partList=[]);const e=E>0?t[t.length-1]:void 0,i=E++,s=new si(n,d),r=new V(s,L,l,i,e);t.push(r),L.duration+=r.duration;break}case"PRELOAD-HINT":{const t=new si(n,d);d.preloadHint=t;break}case"RENDITION-REPORT":{const t=new si(n,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(t);break}default:R.warn(`line parsed but not handled: ${u}`)}}}A&&!A.relurl?(h.pop(),T-=A.duration,d.partList&&(d.fragmentHint=A)):d.partList&&(Vi(L,A,c),L.cc=S,d.fragmentHint=L,g&&ji(L,g,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const w=h.length,D=h[0],P=h[w-1];if(T+=d.skippedSegments*d.targetduration,T>0&&w&&P){d.averagetargetduration=T/w;const t=P.sn;d.endSN="initSegment"!==t?t:0,d.live||(P.endList=!0),I>0&&(!function(t,e){let i=t[e];for(let s=e;s--;){const e=t[s];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(h,I),D&&c.unshift(D))}return d.fragmentHint&&(T+=d.fragmentHint.duration),d.totalduration=T,c.length&&d.dateRangeTagCount&&D&&Ni(c,d),d.endCC=S,d}}function Ni(t,e){let i=t.length;if(!i){if(!e.hasProgramDateTime)return;{const s=e.fragments[e.fragments.length-1];t.push(s),i++}}const s=t[i-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let s=i;s--;){var a;if((null==(a=t[s])?void 0:a.sn)<e.startSN)break;const i=Bi(e,d,t,s,r);if(-1!==i){l.tagAnchor=e.fragments[i].ref;break}}}}function Bi(t,e,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(e>=o||0===s){var a;if(e<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||r)-n.start)){const r=i[s].sn-t.startSN;if(r<0)return-1;const n=t.fragments;if(n.length>i.length){for(let a=(i[s+1]||n[n.length-1]).sn-t.startSN;a>r;a--){const t=n[a].programDateTime;if(e>=t&&e<t+1e3*n[a].duration)return a}}return r}}}return-1}function Ui(t,e,i){var s,r;const n=new si(t,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&&R.error(`Invalid IV: ${n.IV}`);const c=o?Fi.resolve(o,e):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new wi(a,c,h,u,l,n.KEYID)}function $i(t){const i=new si(t).decimalFloatingPoint("TIME-OFFSET");return e(i)?i:null}function Gi(t,e){let i=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const s=i.filter(e=>Et(e,t));s.length&&(e[`${t}Codec`]=s.map(t=>t.split("/")[0]).join(","),i=i.filter(t=>-1===s.indexOf(t)))}),e.unknownCodecs=i}function Ki(t,e,i){const s=e[i];s&&(t[i]=s)}function Vi(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Hi(t,e,i,s){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",s&&(t.levelkeys=s),t.initSegment=null}function ji(t,e,i){t.levelkeys=e;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||s.push(t)}function qi(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function Yi(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function Wi(t,i){const s=i.startPTS;if(e(s)){let e,r=0;i.sn>t.sn?(r=s-t.start,e=t):(r=t.start-s,e=i),e.duration!==r&&e.setDuration(r)}else if(i.sn>t.sn){t.cc===i.cc&&t.minEndPTS?i.setStart(t.start+(t.minEndPTS-t.start)):i.setStart(t.start+t.duration)}else i.setStart(Math.max(t.start-i.duration,0))}function zi(t,i,s,r,n,a,o){r-s<=0&&(o.warn("Fragment should have a positive duration",i),r=s+i.duration,a=n+i.duration);let l=s,d=r;const h=i.startPTS,c=i.endPTS;if(e(h)){const u=Math.abs(h-s);t&&u>t.totalduration?o.warn(`media timestamps and playlist times differ by ${u}s for level ${i.level} ${t.url}`):e(i.deltaPTS)?i.deltaPTS=Math.max(u,i.deltaPTS):i.deltaPTS=u,l=Math.max(s,h),s=Math.min(s,h),n=void 0!==i.startDTS?Math.min(n,i.startDTS):n,d=Math.min(r,c),r=Math.max(r,c),a=void 0!==i.endDTS?Math.max(a,i.endDTS):a}const u=s-i.start;0!==i.start&&i.setStart(s),i.setDuration(r-i.start),i.startPTS=s,i.maxStartPTS=l,i.startDTS=n,i.endPTS=r,i.minEndPTS=d,i.endDTS=a;const f=i.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let g;const m=f-t.startSN,p=t.fragments;for(p[m]=i,g=m;g>0;g--)Wi(p[g],p[g-1]);for(g=m;g<p.length-1;g++)Wi(p[g],p[g+1]);return t.fragmentHint&&Wi(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function Xi(t,i,s){if(t===i)return;let r=null;const n=t.fragments;for(let t=n.length-1;t>=0;t--){const e=n[t].initSegment;if(e){r=e;break}}let a;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){const s=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(s?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let d=r;d<=n;d++){const r=l[a+d];let n=o[d];if(s&&!n&&r&&(n=e.fragments[d]=r),r&&n){i(r,n,d,o);const s=r.relurl,a=n.relurl;if(s&&ns(s,a))return void(e.playlistParsingError=Qi(`media sequence mismatch ${n.sn}:`,t,e,r,n));if(r.cc!==n.cc)return void(e.playlistParsingError=Qi(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,t,e,r,n))}}}(t,i,(t,s,n,o)=>{if((!i.startCC||i.skippedSegments)&&s.cc!==t.cc){const e=t.cc-s.cc;for(let t=n;t<o.length;t++)o[t].cc+=e;i.endCC=o[o.length-1].cc}e(t.startPTS)&&e(t.endPTS)&&(s.setStart(s.startPTS=t.startPTS),s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.setDuration(t.endPTS-t.startPTS),s.duration&&(a=s),i.PTSKnown=i.alignedSliding=!0),t.hasStreams&&(s.elementaryStreams=t.elementaryStreams),s.loader=t.loader,t.hasStats&&(s.stats=t.stats),t.initSegment&&(s.initSegment=t.initSegment,r=t.initSegment)});const o=i.fragments,l=i.fragmentHint?o.concat(i.fragmentHint):o;if(r&&l.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=r)?void 0:e.relurl)||(t.initSegment=r)}),i.skippedSegments){if(i.deltaUpdateFailed=o.some(t=>!t),i.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=i.skippedSegments;t--;)o.shift();i.startSN=o[0].sn}else{i.canSkipDateRanges&&(i.dateRanges=function(t,e,i){const{dateRanges:s,recentlyRemovedDateranges:r}=e,n=v({},t);r&&r.forEach(t=>{delete n[t]});const a=Object.keys(n).length;if(!a)return s;return Object.keys(s).forEach(t=>{const e=n[t],r=new ai(s[t].attr,e);r.isValid?(n[t]=r,e||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Xt(s[t].attr)}"`)}),n}(t.dateRanges,i,s));const e=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!i.hasProgramDateTime)for(let t=1;t<l.length;t++)null===l[t].programDateTime&&Vi(l[t],l[t-1],e);Ni(e,i)}i.endCC=o[o.length-1].cc}if(!i.startCC){var d;const e=es(t,i.startSN-1);i.startCC=null!=(d=null==e?void 0:e.cc)?d:o[0].cc}!function(t,e,i){if(t&&e){let s=0;for(let r=0,n=t.length;r<=n;r++){const n=t[r],a=e[r+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):s--}}}(t.partList,i.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),a?zi(i,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,s):Zi(t,i),o.length&&(i.totalduration=i.edge-o[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const h=i.advancedDateTime;if(i.advanced&&h){const t=i.edge;i.driftStart||(i.driftStartTime=h,i.driftStart=t),i.driftEndTime=h,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime;-1===i.requestScheduled&&(i.requestScheduled=t.requestScheduled)}function Qi(t,e,i,s,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function Zi(t,e,i=!0){const s=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&i)a=t.fragmentStart+s*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}Ji(e,a)}function Ji(t,e){if(e){const i=t.fragments;for(let s=t.skippedSegments;s<i.length;s++)i[s].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function ts(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const s=t.fragments,r=4;if(s.length&&i*r>e){const t=1e3*s[s.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}function es(t,e,i){if(!t)return null;let s=t.fragments[e-t.startSN];return s||(s=t.fragmentHint,s&&s.sn===e?s:e<t.startSN&&i&&i.sn===e?i:null)}function is(t,e,i){return t?ss(t.partList,e,i):null}function ss(t,e,i){if(t)for(let s=t.length;s--;){const r=t[s];if(r.index===i&&r.fragment.sn===e)return r}return null}function rs(t){t.forEach((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function ns(t,e){return!(t===e||!e)&&as(t)!==as(e)}function as(t){return t.replace(/\?[^?]*$/,"")}function os(t,e){for(let s=0,r=t.length;s<r;s++){var i;if((null==(i=t[s])?void 0:i.cc)===e)return t[s]}return null}function ls(t,e){const i=t.start+e;t.startPTS=i,t.setStart(i),t.endPTS=i+t.duration}function ds(t,e){const i=e.fragments;for(let e=0,s=i.length;e<s;e++)ls(i[e],t);e.fragmentHint&&ls(e.fragmentHint,t),e.alignedSliding=!0}function hs(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const i=Math.min(e.endCC,t.endCC),s=os(e.fragments,i),r=os(t.fragments,i);if(!s||!r)return;R.log(`Aligning playlist at start of dicontinuity sequence ${i}`);ds(s.start-r.start,t)}function cs(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,s=e.fragments;if(!i.length||!s.length)return;let r,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(r=os(s,a),n=os(i,a)),r&&n||(r=s[Math.floor(s.length/2)],n=os(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;ds((l-o)/1e3-(n.start-r.start),t)}function us(t,e,i){fs(t,e,i),t.addEventListener(e,i)}function fs(t,e,i){t.removeEventListener(e,i)}const gs=function(t){let e="";const i=t.length;for(let s=0;s<i;s++)e+=`[${t.start(s).toFixed(3)}-${t.end(s).toFixed(3)}]`;return e},ms="STOPPED",ps="IDLE",vs="KEY_LOADING",ys="FRAG_LOADING",Es="FRAG_LOADING_WAITING_RETRY",Ts="WAITING_TRACK",Ss="PARSING",bs="PARSED",As="ENDED",Ls="ERROR",Is="WAITING_INIT_PTS",Rs="WAITING_LEVEL";class ks extends qe{constructor(t,i,s,r,n){super(r,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ms,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:t,fragCurrent:i,media:s,mediaBuffer:r,state:n}=this,a=s?s.currentTime:0,o=ze.bufferInfo(r||s,a,t.maxBufferHole),l=!o.len;if(this.log(`Media seeking to ${e(a)?a.toFixed(3):a}, state: ${n}, ${l?"out of":"in"} buffer`),this.state===As)this.resetLoadingState();else if(i){const e=t.maxFragLookUpTolerance,s=i.start-e,r=i.start+i.duration+e;if(l||r<o.start||s>o.end){const t=a>r;(a<s||t)&&(t&&i.loader&&(this.log(`Cancelling fragment load for seek (sn: ${i.sn})`),i.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s){this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0);if(a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts){const t=Math.max(o.end,a),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}}this.hls.hasEnoughToStart||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${a} for seek without enough to start`),this.nextLoadPosition=a,l&&(this.startPosition=a)),l&&this.state===ps&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=t,this.fragmentLoader=new Ke(t.config),this.keyLoader=s,this.fragmentTracker=i,this.config=t.config,this.decrypter=new $e(t.config)}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===ms)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ms}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const i=t.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=ze.bufferedInfo(r,t.start,0));const n=t.nextStart;if(n&&n>s&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return ze.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;us(i,"seeking",this.onMediaSeeking),us(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===ms&&this.startLoad(s.startPosition)}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(null!==s){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),fs(s,"seeking",this.onMediaSeeking),fs(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(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ms,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(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,i=t.frag;this.fragContextChanged(i)?(e===ys||!this.fragCurrent&&e===Ss)&&(this.fragmentTracker.removeFragment(i),this.state=ps):("payload"in t&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(a.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==ms&&this.state!==Ls&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===_e){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,s?s.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===we&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(a.BUFFER_FLUSHING,s)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t}).then(t=>{const{hls:e}=this,{frag:i,payload:s}=t,o=i.decryptdata;if(s&&s.byteLength>0&&null!=o&&o.key&&o.iv&&hi(o.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),o.key.buffer,o.iv.buffer,ci(o.method)).catch(t=>{throw e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t}).then(s=>{const r=self.performance.now();return e.trigger(a.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:l,tdecrypt:r}}),t.payload=s,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)}).catch(e=>{this.state!==ms&&this.state!==Ls&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state!==ms&&(this.state=ps),t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var i,s;const o=t.tracks;if(o&&!e.encrypted&&(null!=(i=o.audio)&&i.encrypted||null!=(s=o.video)&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(i.message),!t||t.mediaKeys?!1:(this.hls.trigger(a.ERROR,{type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?gs(ze.getBuffered(i)):"(detached)"})`),G(t)){var s;if(t.type!==f){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=ps)}const e=null==(s=this.levels)?void 0:s[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=ps}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:r}=t,n=!r||0===r.length||r.some(t=>!t),a=new Ye(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,i,s=null,r){var n;this.fragCurrent=t;const o=i.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let l=null;if(!t.encrypted||null!=(n=t.decryptdata)&&n.key)t.encrypted||(l=this.keyLoader.loadClear(t,o.encryptedFragments,this.startFragRequested),l&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${t.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=vs,this.fragCurrent=t,l=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(a.KEY_LOADED,t),this.state===vs&&(this.state=ps),t}),this.hls.trigger(a.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const d=this.fragPrevious;if(G(t)&&(!d||t.sn!==d.sn)){const e=this.shouldLoadParts(i.details,t.end);e!==this.loadingParts&&(this.log(`LL-Part loading ${e?"ON":"OFF"} loading sn ${null==d?void 0:d.sn}->${t.sn}`),this.loadingParts=e)}if(s=Math.max(t.start,s||0),this.loadingParts&&G(t)){const e=o.partList;if(e&&r){s>o.fragmentEnd&&o.fragmentHint&&(t=o.fragmentHint);const n=this.getNextPart(e,t,s);if(n>-1){const d=e[n];let h;return t=this.fragCurrent=d.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${d.index} (${n}/${e.length-1}) of ${this.fragInfo(t,!1,d)}) cc: ${t.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=ys,h=l?l.then(e=>!e||this.fragContextChanged(e.frag)?null:this.doFragPartsLoad(t,d,i,r)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,d,i,r).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,part:d,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(e,s))return Promise.resolve(null)}}var h;if(G(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(h=o.partList)?void 0:h.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),e(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ys;const c=this.config.progressive&&t.type!==f;let u;return u=c&&l?l.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,r)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,c?r:void 0),l]).then(([t])=>(!c&&r&&r(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(t,e,i,s){return new Promise((r,n)=>{var o;const l=[],d=null==(o=i.details)?void 0:o.partList,h=e=>{this.fragmentLoader.loadPart(t,e,s).then(s=>{l[e.index]=s;const n=s.part;this.hls.trigger(a.FRAG_LOADED,s);const o=is(i.details,t.sn,e.index+1)||ss(d,t.sn,e.index+1);if(!o)return r({frag:t,part:n,partsLoaded:l});h(o)}).catch(n)};h(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===n.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===r.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger(a.ERROR,e)}else this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Ss)return void(this.fragCurrent||this.state===ms||this.state===Ls||(this.state=ps));const{frag:i,part:s,level:r}=e,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,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var i;const r=t.partList[0];if(r.fragment.type===f)return!1;if(e>=r.end+((null==(i=t.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(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:n}=t;if(null==e||!e[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=e[s],o=a.details,l=n>-1?is(o,r,n):null,d=l?l.fragment:es(o,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,i,s,r){if(this.state!==Ss)return;const{data1:n,data2:o}=t;let l=n;if(o&&(l=dt(n,o)),!l.length)return;const d=this.initPTS[e.cc],h=d?-d.baseTime/d.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:s,offset:h,parent:e.type,data:l};if(this.hls.trigger(a.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!ze.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,s=ze.bufferInfo(e,i,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,s.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,i){var s;const r=this.getLoadPosition();if(!e(r))return null;const n=this.lastCurrentTime>r||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,r,i,n)}getFwdBufferInfoAtPos(t,e,i,s){const r=ze.bufferInfo(t,e,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&(r.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(r.nextStart,n.end)-e,s);return ze.bufferInfo(t,e,i)}}return r}getMaxBufferLength(t){const{config:e}=this;let i;return i=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}exceedsMaxBuffer(t,e,i){const s=t.nextStart;if(s&&i.start>s){const s=t.buffered;if(s){let r=t.len;const n=t.bufferedIndex;for(let t=s.length-1;t>n;t--)s[t].start<i.start&&(r+=s[t].end-s[t].start);return r>=e}}return!1}reduceMaxBufferLength(t,e){const i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e),r=Math.max(t-3*e,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=c){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=e.fragmentStart,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=r.initialLiveManifestSize;if(s<i)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${i})`),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);const i=this.config.startPosition,s=this.hls.startPosition,r=this.hls.liveSyncPosition,d=(null==(l=o)?void 0:l.start)||0;let h,c;-1!==s&&s>=n?(h=s,c=s===i?"config":"next load start"):null!==r?(h=r,c="live edge"):(h=t,c="buffer pos"),h<d&&(h=d,c="live frag start"),h<n&&(h=n,c="playlist start"),this.startPosition==h&&this.nextLoadPosition==h||(this.log(`Setting startPosition to ${h.toFixed(3)} ${-1===s?"":`(from ${i}) `}based on ${c}. live edge: ${r} live frag start: ${d.toFixed(3)} playlist start: ${n.toFixed(3)} buffer pos: ${t}`),this.startPosition=this.nextLoadPosition=h)}}else t<=n&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let d=this.filterReplacedPrimary(o,e);if(!d&&o){const t=o.sn-e.startSN;d=this.filterReplacedPrimary(i[t+1]||null,e)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const i=this.fragmentTracker.getState(t);return i===De||i===we&&!!t.gap}getNextFragmentLoopLoading(t,e,i,s,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==t&&i.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(_s(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(_s(this.config)&&t.type!==f){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(t.start-s.start)>1||0===s.start)return null}else{if(t.end<=s.start&&!1===(null==e?void 0:e.live))return null;if(t.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||t.start-s.end>1))return null}}const r=null==i?void 0:i.playerQueue;if(r)for(let e=r.length;e--;){const i=r[e].interstitial;if(i.appendInPlace&&t.start>=i.startTime&&t.end<=i.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let s=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[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===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${o.start}`),s=a),r=l}return s}loadedEndOfParts(t,e){let i;for(let s=t.length;s--;){if(i=t[s],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const i=t.fragments,s=this.fragPrevious;let r=null;if(s){if(t.hasProgramDateTime&&(r=function(t,i,s){if(null===i||!Array.isArray(t)||!t.length||!e(i))return null;if(i<(t[0].programDateTime||0))return null;if(i>=(t[t.length-1].endProgramDateTime||0))return null;for(let e=0;e<t.length;++e){const r=t[e];if(le(i,s,r))return r}return null}(i,s.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!r){const e=s.sn+1;if(e>=t.startSN&&e<=t.endSN){const n=i[e-t.startSN];s.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=de(t,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,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),t<e){var u;c=ae(r,n,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const t=c.sn-i.startSN,e=this.fragmentTracker.getState(c);if((e===De||e===we&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!h||d[0].fragment.sn>c.sn||!i.live)){if(c.level===r.level){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==De?e:null}}}return c}alignPlaylists(t,i,s){const r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=t.fragmentStart,a=!i,o=t.alignedSliding&&e(n);if(a||!o&&!n){!function(t,e){t&&(hs(e,t),e.alignedSliding||cs(e,t),e.alignedSliding||e.skippedSegments||Zi(t,e,!1))}(s,t);const e=t.fragmentStart;return this.log(`Live playlist sliding: ${e.toFixed(2)} start-sn: ${i?i.startSN:"na"}->${t.startSN} fragments: ${r}`),e}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,i){let s=this.startPosition;s<i&&(s=-1);const r=this.timelineOffset;if(-1===s){const n=null!==this.startTimeOffset,a=n?this.startTimeOffset:t.startTimeOffset;null!==a&&e(a)?(s=i+a,a<0&&(s+=t.edge),s=Math.min(Math.max(i,s),i+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):t.live?(s=this.hls.liveSyncPosition||i,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var t;const{media:e}=this;let i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&G(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===Es)||(this.state=ps)}onFragmentOrKeyLoadError(t,e){var i;if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const s=e.frag;if(!s||s.type!==t||!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 a=e.details===n.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);const o=e.errorAction;if(!o)return void(this.state=Ls);const{action:l,flags:d,retryCount:h=0,retryConfig:c}=o,u=!!c,f=u&&l===Se,g=u&&!o.resolved&&d===Ae,m=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!f&&g&&G(s)&&!s.endList&&m&&!ue(e))this.resetFragmentErrors(t),this.treatAsGap(s),o.resolved=!0;else if((f||g)&&h<c.maxNumRetry){var p;const i=ve(null==(p=e.response)?void 0:p.code),r=ge(c,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=Es,o.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${h+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(t),!(h<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${h})`);a||l===Te||(o.resolved=!0)}else this.state=l===Ee?Rs:Ls;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,i=e===1/0;(!e||t>=e||i&&!ve(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ps)}reduceLengthAndFlushBuffer(t){if(this.state===Ss||this.state===bs){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===u&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ms&&(this.state=ps)}afterBufferFlushed(t,e,i){if(!t)return;const s=ze.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===As&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ms&&(this.state=ps)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){const o=i.details;if(!o)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce((e,r)=>{const n=t.elementaryStreams[r];if(n){const l=n.endPTS-n.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${l})`),e||!1;const d=s?0:zi(o,t,n.startPTS,n.endPTS,n.startDTS,n.endDTS,this);return this.hls.trigger(a.LEVEL_PTS_UPDATED,{details:o,level:i,drift:d,type:r,frag:t,start:n.startPTS,end:n.endPTS}),!0}return e},!1)){var l;const e=null===(null==(l=this.transmuxer)?void 0:l.error);if((0===i.fragmentError||e&&(i.fragmentError<2||t.endList))&&this.treatAsGap(t,i),e){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=bs,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(a.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===c?"level":"track"}fragInfo(t,e=!0,i){var s,r;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${(null!=(s=e&&!i?t.startPTS:(i||t).start)?s:NaN).toFixed(3)}-${(null!=(r=e&&!i?t.endPTS:(i||t).end)?r:NaN).toFixed(3)}]${i&&"main"===t.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function _s(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class ws{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let s=0;for(let e=0;e<t.length;e++){const r=t[e];i.set(r,s),s+=r.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Ds,Ps={exports:{}};var Cs=(Ds||(Ds=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0===--t._eventsCount?t._events=new s:delete t._events[e]}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 t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];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(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},o.prototype.emit=function(t,e,s,r,n,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,s),!0;case 4:return h.fn.call(h.context,e,s,r),!0;case 5:return h.fn.call(h.context,e,s,r,n),!0;case 6:return h.fn.call(h.context,e,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(t,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,e);break;case 3:h[d].fn.call(h[d].context,e,s);break;case 4:h[d].fn.call(h[d].context,e,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(t,e,i){return n(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||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!==e||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(t){var e;return t?(e=i?i+t:t,this._events[e]&&a(this,e)):(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,t.exports=o}(Ps)),Ps.exports),xs=C(Cs);const Ms="1.6.16",Os={};function Fs(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Ns(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Bs(t,e){let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i}function Us(t,e){const i=e;let s=0;for(;Ns(t,e);){s+=10;s+=Bs(t,e+6),Fs(t,e+10)&&(s+=10),e+=s}if(s>0)return t.subarray(i,i+s)}function $s(t,e){return 255===t[e]&&240==(246&t[e+1])}function Gs(t,e){return 1&t[e+1]?7:9}function Ks(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Vs(t,e){return e+1<t.length&&$s(t,e)}function Hs(t,e){if(Vs(t,e)){const i=Gs(t,e);if(e+i>=t.length)return!1;const s=Ks(t,e);if(s<=i)return!1;const r=e+s;return r===t.length||Vs(t,r)}return!1}function js(t,e,i,s,o){if(!t.samplerate){const l=function(t,e,i,s){const o=e[i+2],l=o>>2&15;if(l>12){const e=new Error(`invalid ADTS sampling index:${l}`);return void t.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const d=1+(o>>6&3),h=e[i+3]>>6&3|(1&o)<<2,c="mp4a.40."+d,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][l];let f=l;5!==d&&29!==d||(f-=3);const g=[d<<3|(14&f)>>1,(1&f)<<7|h<<3];return R.log(`manifest codec:${s}, parsed codec:${c}, channels:${h}, rate:${u} (ADTS object type:${d} sampling index:${l})`),{config:g,samplerate:u,channelCount:h,codec:c,parsedCodec:c,manifestCodec:s}}(e,i,s,o);if(!l)return;v(t,l)}}function qs(t){return 9216e4/t}function Ys(t,e,i,s,r){const n=s+r*qs(t.samplerate),a=function(t,e){const i=Gs(t,e);if(e+i<=t.length){const s=Ks(t,e)-i;if(s>0)return{headerLength:i,frameLength:s}}}(e,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,d=Math.max(0,i+l-e.length);d?(o=new Uint8Array(l-r),o.set(e.subarray(i+r,e.length),0)):o=e.subarray(i+r,i+l);const h={unit:o,pts:n};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Ws(t,e){return Ns(t,e)&&Bs(t,e+6)+10<=t.length-e}function zs(t,e=0,i=1/0){return function(t,e,i,s){const r=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=(c=t,c&&c.buffer instanceof ArrayBuffer&&void 0!==c.byteLength&&void 0!==c.byteOffset?t.byteOffset:0),o=(a+t.byteLength)/n,l=(a+e)/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)}(t,e,i,Uint8Array)}function Xs(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=t.data.subarray(1).indexOf(0);if(-1===i)return;const s=w(zs(t.data,1,i)),r=t.data[2+i],n=t.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=w(zs(t.data,3+i,n));let o;return o="--\x3e"===s?w(zs(t.data,4+i+n)):function(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}(t.data.subarray(4+i+n)),e.mimeType=s,e.pictureType=r,e.description=a,e.data=o,e}function Qs(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=w(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=w(t.data.subarray(e),!0);e+=i.length+1;const s=w(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=w(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?Xs(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const i=w(t.data.subarray(e),!0);e+=i.length+1;const s=w(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=w(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function Zs(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=Bs(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}function Js(t){let e=0;const i=[];for(;Ns(t,e);){const s=Bs(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+s;for(;e+10<r;){const s=Zs(t.subarray(e)),r=Qs(s);r&&i.push(r),e+=s.size+10}Fs(t,e)&&(e+=10)}return i}function tr(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function er(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}function ir(t){const e=Js(t);for(let t=0;t<e.length;t++){const i=e[t];if(tr(i))return er(i)}}let sr=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function rr(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class nr{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(t,e,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,i){this.cachedData&&(t=dt(this.cachedData,t),this.cachedData=null);let s,r=Us(t,0),n=r?r.length:0;const a=this._audioTrack,o=this._id3Track,l=r?ir(r):void 0,d=t.length;for((null===this.basePTS||0===this.frameIndex&&e(l))&&(this.basePTS=ar(l,i,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:sr.audioId3,duration:Number.POSITIVE_INFINITY});n<d;){if(this.canParse(t,n)){const e=this.appendFrame(a,t,n);e?(this.frameIndex++,this.lastPTS=e.sample.pts,n+=e.length,s=n):n=d}else Ws(t,n)?(r=Us(t,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:sr.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,s=n):n++;if(n===d&&s!==d){const e=t.slice(s);this.cachedData?this.cachedData=dt(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:rr(),id3Track:o,textTrack:rr()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:rr(),id3Track:this._id3Track,textTrack:rr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const ar=(t,i,s)=>{if(e(t))return 90*t;return 9e4*i+(s?9e4*s.baseTime/s.timescale:0)};let or=null;const lr=[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],dr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],hr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],cr=[0,1,1,4];function ur(t,e,i,s,r){if(i+24>e.length)return;const n=fr(e,i);if(n&&i+n.frameLength<=e.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function fr(t,e){const i=t[e+1]>>3&3,s=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*lr[14*(3===i?3-s:3===s?3:4)+r-1],d=dr[3*(3===i?0:2===i?1:2)+n],h=3===o?1:2,c=hr[i][s],u=cr[s],f=8*c*u,g=Math.floor(c*l/d+a)*u;if(null===or){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);or=t?parseInt(t[1]):0}return!!or&&or<=87&&2===s&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function gr(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function mr(t,e){return e+1<t.length&&gr(t,e)}function pr(t,e){if(e+1<t.length&&gr(t,e)){const i=4,s=fr(t,e);let r=i;null!=s&&s.frameLength&&(r=s.frameLength);const n=e+r;return n===t.length||mr(t,n)}return!1}const vr=(t,e)=>{let i=0,s=5;e+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=t[e];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],e+=1,s-=o}return i};class yr extends nr{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const s=Er(t,e,i,this.basePTS,this.frameIndex);if(-1!==s){return{sample:t.samples[t.samples.length-1],length:s,missing:0}}}static probe(t){if(!t)return!1;const e=Us(t,0);if(!e)return!1;const i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==ir(e)&&vr(t,i)<16}}function Er(t,e,i,s,r){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const n=e[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[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>e.length)return-1;const d=e[i+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(e[i+6]<<8|e[i+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=e[i+5]>>3,g=7&e[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),v=e.subarray(i,i+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}const Tr=/\/emsg[-/]ID3/i;function Sr(t,i){return e(t.presentationTime)?t.presentationTime/t.timeScale:i+t.presentationTimeDelta/t.timeScale}class br{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new $e(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,Oe)}decryptAacSample(t,e,i){const s=t[e].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(t,e+1,i)}).catch(i)}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)i.set(t.subarray(e,e+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)t.set(i.subarray(s,s+16),e);return t}decryptAvcSample(t,e,i,s,r){const n=gt(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)}).catch(s)}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void s();const r=t[e].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,s,n),this.decrypter.isSync())))return}}}}class Ar{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i,s=this.VideoSample;if(s&&0!==s.units.length||(s=t[t.length-1]),null!=(e=s)&&e.units){const t=s.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,s=i.length;if(!s)return void e.dropped++;{const e=i[s-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,i){const s=e.byteLength;let r=t.naluState||0;const n=r,a=[];let o,l,d,h=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(e,0),r=0,h=1);h<s;)if(o=e[h++],r)if(1!==r)if(o)if(1===o){if(l=h-r-1,c>=0){const t={data:e.subarray(c,l),type:u};a.push(t)}else{const i=this.getLastNalUnit(t.samples);i&&(n&&h<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=dt(i.data,e.subarray(0,l)),i.state=0))}h<s?(d=this.getNALuType(e,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 t={data:e.subarray(c,s),type:u,state:r};a.push(t)}if(0===a.length){const i=this.getLastNalUnit(t.samples);i&&(i.data=dt(i.data,e))}return t.naluState=r,a}}class Lr{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");s.set(t.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&R.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Ir extends Ar{parsePES(t,e,i,s){const r=this.parseNALu(t,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 1:{let e=!1;n=!0;const r=s.data;if(o&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;if(e)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),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,ft(s.data,1,i.pts,e.samples);break;case 7:{var h,c;n=!0,o=!0;const e=s.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(h=t.pixelRatio)?void 0:h[0])!==i.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e];const s=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=s[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:n=!0,t.pps=[s.data];break;case 9:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),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,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new Lr(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,s=8,r=8;for(let n=0;n<t;n++)0!==r&&(i=e.readEG(),r=(s+i+256)%256),s=0===r?s:r}readSPS(t){const e=new Lr(t);let i,s,r,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),h=e.readBits.bind(e),c=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=c();if(3===t&&f(1),m(),m(),f(1),u())for(s=3!==t?8:12,r=0;r<s;r++)u()&&p(r<6?16:64,e)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),i=c(),r=0;r<i;r++)g();m(),f(1);const E=c(),T=c(),S=h(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let b=[1,1];if(u()&&u()){switch(d()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}class Rr extends Ar{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,s){const r=this.parseNALu(t,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),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,t),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,t),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,ft(s.data,2,i.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=v(t.params,this.readVPS(s.data)),this.initVPS=s.data),t.vps=[s.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],s.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(s.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const i in e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,s.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(s.data);for(const i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,s.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),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,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let s=0;s<t.byteLength;s++)s>=2&&3===t[s]&&0===t[s-1]&&0===t[s-2]||(e[i]=t[s],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new Lr(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new Lr(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const s=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),d=e.readUByte(),h=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let t=0;t<i;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),S=e.readUEG(),b=e.readBoolean();let A=0,L=0,I=0,R=0;b&&(A+=e.readUEG(),L+=e.readUEG(),I+=e.readUEG(),R+=e.readUEG());const k=e.readUEG(),_=e.readUEG(),w=e.readUEG();for(let t=e.readBoolean()?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBoolean()){const i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const D=e.readUEG();let P=0;for(let t=0;t<D;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===D&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=P;t++){const t=e.readBoolean();let s=!1;t||(s=e.readBoolean()),(t||s)&&i++}P=i}else{const t=e.readUEG(),i=e.readUEG();P=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<w+4;t++)e.readBits(1);e.readBits(1)}}let C=0,x=1,M=1,O=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let B=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(x=e.readBits(16),M=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),B=e.readBoolean(),B&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),s=e.readBoolean();let r=!1;(t||s)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){O=e.readBoolean();let i=!1;O||e.readBoolean()?e.readEG():i=e.readBoolean();const n=i?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(s)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),C=e.readUEG())}let U=T,$=S;if(b){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),U=T-t*L-t*A,$=S-e*R-e*I}const G=s?["A","B","C"][s]:"",K=a<<24|o<<16|l<<8|d;let V=0;for(let t=0;t<32;t++)V=(V|(K>>t&1)<<31-t)>>>0;let H=V.toString(16);1===n&&"2"===H&&(H="6");return{codecString:`hvc1.${G}${n}.${H}.${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:_,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:O,fps:N/F}},width:U,height:$,pixelRatio:[x,M]}}readPPS(t){const e=new Lr(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const i=e.readBoolean(),s=e.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}}const kr=188;class _r{constructor(t,e,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=t,this.config=e,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(t,e){const i=_r.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let i=Math.min(940,e-kr)+1,s=0;for(;s<i;){let r=!1,n=-1,a=0;for(let o=s;o<e;o+=kr){if(71!==t[o]||e-o!==kr&&71!==t[o+kr]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,t.length-kr)+1)),r||(r=0===wr(t,o)),r&&a>1&&(0===n&&a>2||o+kr>i))return n}s++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Y[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=_r.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=_r.createTrack("audio",s),this._id3Track=_r.createTrack("id3"),this._txtTrack=_r.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,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,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=dt(this.remainderData,t)).length,this.remainderData=null),y<kr&&!s)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,_r.syncOffset(t));y-=(y-E)%kr,y<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let e=E;e<y;e+=kr)if(71===t[e]){const s=!!(64&t[e+1]),y=wr(t,e);let T;if((48&t[e+3])>>4>1){if(T=e+5+t[e+4],T===e+kr)continue}else T=e+4;switch(y){case d:s&&(h&&(r=Mr(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(t.subarray(T,e+kr)),h.size+=e+kr-T);break;case c:if(s){if(f&&(r=Mr(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(t.subarray(T,e+kr)),f.size+=e+kr-T);break;case u:s&&(g&&(r=Mr(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+kr)),g.size+=e+kr-T);break;case 0:s&&(T+=t[T]+1),v=this._pmtId=Dr(t,T);break;case v:{s&&(T+=t[T]+1);const r=Pr(t,T,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 ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&Cr(this.observer,new Error(`Found ${T} 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:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:s,textTrack:r}=t,n=i.pesData,a=e.pesData,o=s.pesData;let l;if(n&&(l=Mr(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=Mr(a,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=Mr(o,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=o}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),r=this.sampleAes=new br(this.observer,this.config,e);return this.decrypt(s,r)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new Ir:"hevc"===t&&(this.videoParser=new Rr))}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=t;s.samples&&"aac"===s.segmentCodec?e.decryptAacSamples(s.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{i(t)}):i(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{i(t)})})}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(t,e){let i=0;const s=this.aacOverFlow;let r,n,a,o=e.data;if(s){this.aacOverFlow=null;const e=s.missing,r=s.sample.unit.byteLength;if(-1===e)o=dt(s.sample.unit,o);else{const n=r-e;s.sample.unit.set(o.subarray(0,e),n),t.samples.push(s.sample),i=s.missing}}for(r=i,n=o.length;r<n-1&&!Vs(o,r);r++);if(r!==i){let t;const e=r<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",Cr(this.observer,new Error(t),e,this.logger),!e)return}if(js(t,this.observer,o,r,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=qs(t.samplerate);a=s.sample.pts+e}}let l,d=0;for(;r<n;){if(l=Ys(t,o,r,a,d),r+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;r<n-1&&!Vs(o,r);r++);}}parseMPEGPES(t,e){const i=e.data,s=i.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<s;)if(mr(i,n)){const e=ur(t,i,n,a,r);if(!e)break;n+=e.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,s=e.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=Er(t,i,o,s,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=v({},e,{type:this._videoTrack?sr.emsg:sr.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function wr(t,e){return((31&t[e+1])<<8)+t[e+2]}function Dr(t,e){return(31&t[e+10])<<8|t[e+11]}function Pr(t,e,i,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<o;){const o=wr(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!s){xr("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){xr("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){xr("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=e+5,r=l;for(;r>2;){if(106===t[s])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const e=t[s+1]+2;s+=e,r-=e}}break;case 194:case 135:return Cr(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"))}e+=l+5}return a}function Cr(t,e,i,s){s.warn(`parsing error: ${e.message}`),t.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function xr(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Mr(t,e){let i,s,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=dt(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>t.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&&(e.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(t.size<=h)return null;t.size-=h;const c=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(h){if(h>e){h-=e;continue}i=i.subarray(h),e-=h,h=0}c.set(i,o),o+=e}return s&&(s-=r+3),{data:c,pts:n,dts:a,len:s}}return null}class Or{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)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===e)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===e)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===e)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===e)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 Fr=Math.pow(2,32)-1;class Nr{static init(){let t;for(t in Nr.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:[]},Nr.types)Nr.types.hasOwnProperty(t)&&(Nr.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=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]);Nr.HDLR_TYPES={video:e,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]);Nr.STTS=Nr.STSC=Nr.STCO=r,Nr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Nr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Nr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Nr.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]);Nr.FTYP=Nr.box(Nr.types.ftyp,n,o,n,a),Nr.DINF=Nr.box(Nr.types.dinf,Nr.box(Nr.types.dref,s))}static box(t,...e){let i=8,s=e.length;const r=s;for(;s--;)i+=e[s].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),s=0,i=8;s<r;s++)n.set(e[s],i),i+=e[s].byteLength;return n}static hdlr(t){return Nr.box(Nr.types.hdlr,Nr.HDLR_TYPES[t])}static mdat(t){return Nr.box(Nr.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Fr+1)),s=Math.floor(e%(Fr+1));return Nr.box(Nr.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,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(t){return Nr.box(Nr.types.mdia,Nr.mdhd(t.timescale||0,t.duration||0),Nr.hdlr(t.type),Nr.minf(t))}static mfhd(t){return Nr.box(Nr.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Nr.box(Nr.types.minf,Nr.box(Nr.types.smhd,Nr.SMHD),Nr.DINF,Nr.stbl(t)):Nr.box(Nr.types.minf,Nr.box(Nr.types.vmhd,Nr.VMHD),Nr.DINF,Nr.stbl(t))}static moof(t,e,i){return Nr.box(Nr.types.moof,Nr.mfhd(t),Nr.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Nr.trak(t[e]);return Nr.box.apply(null,[Nr.types.moov,Nr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Nr.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Nr.trex(t[e]);return Nr.box.apply(null,[Nr.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Fr+1)),s=Math.floor(e%(Fr+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,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 Nr.box(Nr.types.mvhd,r)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,r;for(s=0;s<e.length;s++)r=e[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Nr.box(Nr.types.sdtp,i)}static stbl(t){return Nr.box(Nr.types.stbl,Nr.stsd(t),Nr.box(Nr.types.stts,Nr.STTS),Nr.box(Nr.types.stsc,Nr.STSC),Nr.box(Nr.types.stsz,Nr.STSZ),Nr.box(Nr.types.stco,Nr.STCO))}static avc1(t){let e,i,s,r=[],n=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=Nr.box(Nr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return Nr.box(Nr.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,Nr.box(Nr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Nr.box(Nr.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(t){const e=t.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,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Nr.box(Nr.types.mp4a,Nr.audioStsd(t),Nr.box(Nr.types.esds,Nr.esds(t)))}static mp3(t){return Nr.box(Nr.types[".mp3"],Nr.audioStsd(t))}static ac3(t){return Nr.box(Nr.types["ac-3"],Nr.audioStsd(t),Nr.box(Nr.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.mp4a(t));if("ac3"===e&&t.config)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.avc1(t));if("hevc"===e&&t.vps)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),s=t.width||0,r=t.height||0,n=Math.floor(i/(Fr+1)),a=Math.floor(i%(Fr+1));return Nr.box(Nr.types.tkhd,new Uint8Array([1,0,0,7,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,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(t,e){const i=Nr.sdtp(t),s=t.id,r=Math.floor(e/(Fr+1)),n=Math.floor(e%(Fr+1));return Nr.box(Nr.types.traf,Nr.box(Nr.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Nr.box(Nr.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])),Nr.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Nr.box(Nr.types.trak,Nr.tkhd(t),Nr.mdia(t))}static trex(t){const e=t.id;return Nr.box(Nr.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r);let a,o,l,d,h,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,e>>>24&255,e>>>16&255,e>>>8&255,255&e],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 Nr.box(Nr.types.trun,n)}static initSegment(t){Nr.types||Nr.init();const e=Nr.moov(t);return dt(Nr.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],s=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let r=s.length;for(let t=0;t<i.length;t+=1){r+=3;for(let e=0;e<i[t].length;e+=1)r+=2+i[t][e].length}const n=new Uint8Array(r);n.set(s,0),r=s.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),r),r+=3;for(let e=0;e<i[t].length;e+=1)n.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),r),r+=2,n.set(i[t][e],r),r+=i[t][e].length}const o=Nr.box(Nr.types.hvcC,n),l=t.width,d=t.height,h=t.pixelRatio[0],c=t.pixelRatio[1];return Nr.box(Nr.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,Nr.box(Nr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Nr.box(Nr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}}Nr.types=void 0,Nr.HDLR_TYPES=void 0,Nr.STTS=void 0,Nr.STSC=void 0,Nr.STCO=void 0,Nr.STSZ=void 0,Nr.VMHD=void 0,Nr.SMHD=void 0,Nr.STSD=void 0,Nr.FTYP=void 0,Nr.DINF=void 0;function Br(t,e,i=1,s=!1){const r=t*e*i;return s?Math.round(r):r}function Ur(t,e=!1){return Br(t,1e3,1/9e4,e)}function $r(t){const{baseTime:e,timescale:i,trackId:s}=t;return`${e/i} (${e}/${i}) trackId: ${s}`}let Gr,Kr=null,Vr=null;function Hr(t,e,i,s){return{duration:e,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class jr extends T{constructor(t,e,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=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===Kr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Kr=t?parseInt(t[1]):0}if(null===Vr){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Vr=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?$r(e):e} > ${t?$r(t):t}`),this._initPTS=this._initDTS=t}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(t){let e=!1;const i=t[0].pts,s=t.reduce((t,s)=>{let r=s.pts,n=r-t;return n<-4294967296&&(e=!0,r=qr(r,i),n=r-t),n>0?t:r},i);return e&&this.debug("PTS rollover detected"),s}remux(t,e,i,s,r,n,a,o){let l,d,h,c,f,g,m=r,p=r;const v=t.pid>-1,y=e.pid>-1,E=e.samples.length,T=t.samples.length>0,S=a&&E>0||E>1;if((!v||T)&&(!y||S)||this.ISGenerated||a){if(this.ISGenerated){var b,A,L,I;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(b=e.pixelRatio)?void 0:b[0])!==(null==(A=t.pixelRatio)?void 0:A[0])||(null==(L=e.pixelRatio)?void 0:L[1])!==(null==(I=t.pixelRatio)?void 0:I[1]))||!t&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,e,r,n));const i=this.isVideoContiguous;let s,a=-1;if(S&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,a>0){this.warn(`Dropped ${a} out of ${E} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,p+=(e.samples[0].pts-t)/e.inputTimeScale,s=p}else-1===a&&(this.warn(`No keyframe found out of ${E} video samples`),g=!1);if(this.ISGenerated){if(T&&S){const i=this.getVideoStartPts(e.samples),s=(qr(t.samples[0].pts,i)-i)/e.inputTimeScale;m+=Math.max(0,s),p+=Math.max(0,-s)}if(T){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,e,r,n)),d=this.remuxAudio(t,m,this.isAudioContiguous,n,y||S||o===u?p:void 0),S){const s=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,p,i,s)}}else S&&(l=this.remuxVideo(e,p,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Yr(i,r,this._initPTS,this._initDTS)),s.samples.length&&(c=Wr(s,r,this._initPTS))),{audio:d,video:l,initSegment:h,independent:g,text:c,id3:f}}computeInitPts(t,e,i,s){const r=Math.round(i*e);let n=qr(t,r);if(n<r+e)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${s}`);n<r+e;)n+=8589934592;return n-r}generateIS(t,e,i,s){const r=t.samples,n=e.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),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Nr.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(g=t.id,c=t.inputTimeScale,l&&c===l.timescale?u=!1:d=h=this.computeInitPts(r[0].pts,c,i,"audio"))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Nr.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(g=e.id,c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=qr(n[0].dts,t),s=this.computeInitPts(e,c,i,"video"),r=this.computeInitPts(t,c,i,"video");h=Math.min(h,s),d=Math.min(d,r)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.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(t,e,i,s){const o=t.inputTimeScale,l=t.samples,d=[],h=l.length,c=this._initPTS,u=c.baseTime*o/c.timescale;let f,g,m=this.nextVideoTs,p=8,y=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!i||null===m){const t=u+e*o,s=l[0].pts-qr(l[0].dts,l[0].pts);Kr&&null!==m&&Math.abs(t-s-(m+u))<15e3?i=!0:m=t-s-u}const b=m+u;for(let t=0;t<h;t++){const e=l[t];e.pts=qr(e.pts,b),e.dts=qr(e.dts,b),e.dts<l[t>0?t-1:t].dts&&(S=!0)}S&&l.sort(function(t,e){const i=t.dts-e.dts,s=t.pts-e.pts;return i||s}),f=l[0].dts,g=l[l.length-1].dts;const A=g-f,L=A?Math.round(A/(h-1)):y||t.inputTimeScale/30;if(i){const i=f-b,s=i>L,r=i<-1;if((s||r)&&(s?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ur(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ur(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||b>=l[0].pts||Kr)){f=b;const t=l[0].pts-i;if(s)l[0].dts=f,l[0].pts=t;else{let e=!0;for(let s=0;s<l.length&&!(l[s].dts>t&&e);s++){const t=l[s].pts;if(l[s].dts-=i,l[s].pts-=i,s<l.length-1){const i=l[s+1].pts;e=i<=l[s].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ur(t,!0)}/${Ur(f,!0)}, delta: ${Ur(i,!0)} ms`)}}f=Math.max(0,f);let I=0,R=0,k=f;for(let t=0;t<h;t++){const e=l[t],i=e.units,s=i.length;let r=0;for(let t=0;t<s;t++)r+=i[t].data.length;R+=r,I+=s,e.length=r,e.dts<k?(e.dts=k,k+=L/4|0||1):k=e.dts,E=Math.min(e.pts,E),T=Math.max(e.pts,T)}g=l[h-1].dts;const _=R+4*I+8;let w;try{w=new Uint8Array(_)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:r.MUX_ERROR,details:n.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:_,reason:`fail allocating video mdat ${_}`})}const D=new DataView(w.buffer);D.setUint32(0,_),w.set(Nr.types.mdat,4);let P=!1,C=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<h;t++){const e=l[t],i=e.units;let r,n=0;for(let t=0,e=i.length;t<e;t++){const e=i[t],s=e.data,r=e.data.byteLength;D.setUint32(p,r),p+=4,w.set(s,p),p+=r,n+=4+r}if(t<h-1)y=l[t+1].dts-e.dts,r=l[t+1].pts-e.pts;else{const i=this.config,n=t>0?e.dts-l[t-1].dts:L;if(r=t>0?e.pts-l[t-1].pts:L,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*o),r=(s?E+s*o:this.nextAudioTs+u)-e.pts;r>t?(y=r-n,y<0?y=n:P=!0,this.log(`It is approximately ${r/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=n}else y=n}const a=Math.round(e.pts-e.dts);C=Math.min(C,y),M=Math.max(M,y),x=Math.min(x,r),O=Math.max(O,r),d.push(Hr(e.key,y,n,a))}if(d.length)if(Kr){if(Kr<70){const t=d[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Vr&&O-x<M-C&&L/M<.025&&0===d[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=f;for(let e=0,i=d.length;e<i;e++){const s=t+d[e].duration,r=t+d[e].cts;if(e<i-1){const t=s+d[e+1].cts;d[e].duration=t-r}else d[e].duration=e?d[e-1].duration:L;d[e].cts=0,t=s}}y=P||!y?L:y;const F=g+y;this.nextVideoTs=m=F-u,this.videoSampleDuration=y,this.isVideoContiguous=!0;const N={data1:Nr.moof(t.sequenceNumber++,f,v(t,{samples:d})),data2:w,startPTS:(E-u)/o,endPTS:(T+y-u)/o,startDTS:(f-u)/o,endDTS:m/o,type:"video",hasAudio:!1,hasVideo:!0,nb:d.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,s,o){const l=t.inputTimeScale,d=l/(t.samplerate?t.samplerate:l),h=this.getSamplesPerFrame(t),c=h*d,u=this._initPTS,f="mp3"===t.segmentCodec&&this.typeSupported.mpeg,g=[],m=void 0!==o;let p=t.samples,y=f?0:8,E=this.nextAudioTs||-1;const T=u.baseTime*l/u.timescale,S=T+e*l;if(this.isAudioContiguous=i=i||p.length&&E>0&&(s&&Math.abs(S-(E+T))<9e3||Math.abs(qr(p[0].pts,S)-(E+T))<20*c),p.forEach(function(t){t.pts=qr(t.pts,S)}),!i||E<0){const t=p.length;if(p=p.filter(t=>t.pts>=0),t!==p.length&&this.warn(`Removed ${p.length-t} of ${t} samples (initPTS ${T} / ${l})`),!p.length)return;E=0===o?0:s&&!m?Math.max(0,S-T):p[0].pts-T}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,s=E+T;i<p.length;i++){const r=p[i],n=r.pts,a=n-s,o=Math.abs(1e3*a/l);if(a<=-e*c&&m)0===i&&(this.warn(`Audio frame @ ${(n/l).toFixed(3)}s overlaps marker by ${Math.round(1e3*a/l)} ms.`),this.nextAudioTs=E=n-T,s=n);else if(a>=e*c&&o<1e4&&m){let e=Math.round(a/c);for(s=n-e*c;s<0&&e&&c;)e--,s+=c;0===i&&(this.nextAudioTs=E=s-T),this.warn(`Injecting ${e} audio frames @ ${((s-T)/l).toFixed(3)}s due to ${Math.round(1e3*a/l)} ms gap.`);for(let n=0;n<e;n++){let e=Or.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),p.splice(i,0,{unit:e,pts:s}),s+=c,i++}}r.pts=s,s+=c}}let b,A=null,L=null,I=0,R=p.length;for(;R--;)I+=p[R].unit.byteLength;for(let e=0,s=p.length;e<s;e++){const s=p[e],o=s.unit;let l=s.pts;if(null!==L){g[e-1].duration=Math.round((l-L)/d)}else{if(i&&"aac"===t.segmentCodec&&(l=E+T),A=l,!(I>0))return;I+=y;try{b=new Uint8Array(I)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:r.MUX_ERROR,details:n.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:I,reason:`fail allocating audio mdat ${I}`})}if(!f){new DataView(b.buffer).setUint32(0,I),b.set(Nr.types.mdat,4)}}b.set(o,y);const c=o.byteLength;y+=c,g.push(Hr(!0,h,c,0)),L=l}const k=g.length;if(!k)return;const _=g[g.length-1];E=L-T,this.nextAudioTs=E+d*_.duration;const w=f?new Uint8Array(0):Nr.moof(t.sequenceNumber++,A/d,v({},t,{samples:g}));t.samples=[];const D=(A-T)/l,P=this.nextAudioTs/l,C={data1:w,data2:b,startPTS:D,endPTS:P,startDTS:D,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,C}}function qr(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=i;return t}function Yr(t,e,i,s){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=qr(r.pts-i.baseTime*n/i.timescale,e*n)/n,r.dts=qr(r.dts-s.baseTime*n/s.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Wr(t,e,i){const s=t.samples.length;if(!s)return;const r=t.inputTimeScale;for(let n=0;n<s;n++){const s=t.samples[n];s.pts=qr(s.pts-i.baseTime*r/i.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function zr(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Xr(t,e,i){const s=t.codec;if(s&&s.length>4)return s;if(e===N){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return kt(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{Gr=self.performance.now.bind(self.performance)}catch(t){Gr=Date.now}const Qr=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,i,s){const r=this.videoTrack=rr("video",1),n=this.audioTrack=rr("audio",1),a=this.txtTrack=rr("text",1);if(this.id3Track=rr("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=et(t);if(o.video){const{id:t,timescale:e,codec:i,supplemental:s}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=i,r.supplemental=s}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;n.id=t,n.timescale=e,n.codec=i}a.id=Y.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let i=0;i<e;){const s=X(t,i);if(s>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=s>1?i+s:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=dt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=J(t,["moof"]);if(i.length<2)return e.remainder=t,e;const s=i[i.length-1];return e.valid=t.slice(0,s.byteOffset-8),e.remainder=t.slice(s.byteOffset-8),e}(i);this.remainderData=e.remainder,s.samples=e.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,e);return r.samples=ht(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return i.samples=ht(t,e),{videoTrack:e,audioTrack:rr(),id3Track:s,textTrack:rr()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const r=J(t.samples,["emsg"]);r&&r.forEach(t=>{const r=function(t){const e=t[0];let s="",r="",n=0,a=0,o=0,l=0,d=0,h=0;if(0===e){for(;"\0"!==W(t.subarray(h,h+1));)s+=W(t.subarray(h,h+1)),h+=1;for(s+=W(t.subarray(h,h+1)),h+=1;"\0"!==W(t.subarray(h,h+1));)r+=W(t.subarray(h,h+1)),h+=1;r+=W(t.subarray(h,h+1)),h+=1,n=X(t,12),a=X(t,16),l=X(t,20),d=X(t,24),h=28}else if(1===e){h+=4,n=X(t,h),h+=4;const e=X(t,h);h+=4;const a=X(t,h);for(h+=4,o=2**32*e+a,i(o)||(o=Number.MAX_SAFE_INTEGER,R.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=X(t,h),h+=4,d=X(t,h),h+=4;"\0"!==W(t.subarray(h,h+1));)s+=W(t.subarray(h,h+1)),h+=1;for(s+=W(t.subarray(h,h+1)),h+=1;"\0"!==W(t.subarray(h,h+1));)r+=W(t.subarray(h,h+1)),h+=1;r+=W(t.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:r,timeScale:n,presentationTime:o,presentationTimeDelta:a,eventDuration:l,id:d,payload:t.subarray(h,t.byteLength)}}(t);if(Tr.test(r.schemeIdUri)){const t=Sr(r,e);let i=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=r.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:sr.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=Sr(r,e);s.samples.push({data:r.payload,len:r.payload.byteLength,dts:t,pts:t,type:sr.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(t,e,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 T{constructor(t,e,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(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(t,s),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:i,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=et(t);if(e)!function(t,e){if(!t||!e)return;const i=e.keyId;i&&e.isCommonEncryption&&ot(t,(t,e)=>{const s=t.subarray(8,24);s.some(t=>0!==t)||(R.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${D(s)} -> ${D(i)}`),t.set(i,8))})}(t,e);else{const t=r||n;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}r&&(i=Xr(r,N,this)),n&&(s=Xr(n,B,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:r?a.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:t,id:"audio"}:n?a.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(t,i,s,r,n,a){var o,l;let{initPTS:d,lastEndTime:h}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};e(h)||(h=this.lastEndTime=n||0);const u=i.samples;if(!u.length)return c;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if(null!=(o=g)&&o.length||(this.generateInitSegment(u),g=this.initData),null==(l=g)||!l.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,i,s){const r={},n=J(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=J(a,["tfhd"])[0],l=X(o,4),d=i[l];if(!d)continue;r[l]||(r[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});const h=r[l],c=J(a,["tfdt"])[0];if(c){const t=c[0];let i=X(c,4);1===t&&(i===j?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(i*=j+1,i+=X(c,8))),e(i)&&(!e(h.start)||i<h.start)&&(h.start=i)}const u=d.default,f=X(o,0)|(null==u?void 0:u.flags);let g=(null==u?void 0:u.duration)||0;8&f&&(g=X(o,2&f?12:8));const m=J(a,["trun"]);let p=h.start||0,v=0,y=g;for(let t=0;t<m.length;t++){const e=m[t],i=X(e,4),s=h.sampleCount;h.sampleCount+=i;const r=1&e[3],n=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],d=8&e[2];let c=8,u=i;for(r&&(c+=4),n&&i&&(1&e[c+1]||void 0!==h.keyFrameIndex||(h.keyFrameIndex=s),c+=4,a?(y=X(e,c),c+=4):y=g,o&&(c+=4),d&&(c+=4),p+=y,v+=y,u--);u--;)a?(y=X(e,c),c+=4):y=g,o&&(c+=4),l&&(1&e[c+1]||void 0===h.keyFrameIndex&&(h.keyFrameIndex=h.sampleCount-(u+1),h.keyFrameStart=p),c+=4),d&&(c+=4),p+=y,v+=y;!v&&g&&(v+=g*i)}h.duration+=v}if(!Object.keys(r).some(t=>r[t].duration)){let i=1/0,s=0;const n=J(t,["sidx"]);for(let t=0;t<n.length;t++){const e=tt(n[t]);if(null!=e&&e.references){i=Math.min(i,e.earliestPresentationTime/e.timescale);const t=e.references.reduce((t,e)=>t+e.info.duration||0,0);s=Math.max(s,t+e.earliestPresentationTime/e.timescale)}}s&&e(s)&&Object.keys(r).forEach(t=>{r[t].duration||(r[t].duration=s*r[t].timescale-r[t].start)})}return r}(u,g,this),p=g.audio?m[g.audio.id]:null,v=g.video?m[g.video.id]:null,y=zr(v,1/0),E=zr(p,1/0),T=zr(v,0,!0),S=zr(p,0,!0);let b=n,A=0;const L=p&&(!v||!d&&E<y||d&&d.trackId===g.audio.id),I=L?p:v;if(I){const t=I.timescale,e=I.start-n*t,i=L?g.audio.id:g.video.id;b=I.start/t,A=L?S-E:T-y,!a&&d||!function(t,e,i,s){if(null===t)return!0;const r=Math.max(s,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>r}(d,b,n,A)&&t===d.timescale||(d&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${e/t} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${b-n} (${e}/${t}) trackId: ${i}`),d=null,f.initPTS=e,f.timescale=t,f.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):(f.timescale&&void 0!==f.trackId&&void 0!==f.initPTS||(this.warn("Could not set initPTS"),f.initPTS=b,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const R=b-d.baseTime/d.timescale,k=R+A;A>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const _=!!g.audio,w=!!g.video;let D="";_&&(D+="audio"),w&&(D+="video");const P={data1:u,startPTS:R,startDTS:R,endPTS:k,endDTS:k,type:D,hasAudio:_,hasVideo:w,nb:1,dropped:0,encrypted:!!g.audio&&g.audio.encrypted||!!g.video&&g.video.encrypted};c.audio=_&&!w?P:void 0,c.video=w?P:void 0;const C=null==v?void 0:v.sampleCount;if(C){const t=v.keyFrameIndex,e=-1!==t;P.nb=C,P.dropped=0===t||this.isVideoContiguous?0:e?t:C,P.independent=e,P.firstKeyFrame=t,e&&v.keyFrameStart&&(P.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(c.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),P.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${C} dropped: ${P.dropped} start: ${P.firstKeyFramePTS||"NA"}`)}return c.initSegment=f,c.id3=Yr(s,n,d,d),r.samples.length&&(c.text=Wr(r,n,d)),c}}},{demux:_r,remux:jr},{demux:class extends nr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=Us(t,0);let s=(null==i?void 0:i.length)||0;if(pr(t,s))return!1;for(let i=t.length;s<i;s++)if(Hs(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&$s(t,e)&&Ks(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){js(t,this.observer,e,i,t.manifestCodec);const s=Ys(t,e,i,this.basePTS,this.frameIndex);if(s&&0===s.missing)return s}},remux:jr},{demux:class extends nr{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Us(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==ir(e)&&vr(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(pr(t,i))return R.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return gr(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return ur(t,e,i,this.basePTS,this.frameIndex)}},remux:jr}];Qr.splice(2,0,{demux:yr,remux:jr});class Zr{constructor(t,e,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=t,this.typeSupported=e,this.config=i,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){const o=i.transmuxing;o.executeStart=Gr();let l=new Uint8Array(t);const{currentTransmuxState:d,transmuxConfig:h}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:u,trackSwitch:f,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=s||d,{audioCodec:v,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=h,b=function(t,e){let i=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(l,e);if(b&&hi(b.method)){const t=this.getDecrypter(),e=ci(b.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(l,b.key.buffer,b.iv.buffer,e).then(t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e}),this.decryptionPromise;{let s=t.softwareDecrypt(l,b.key.buffer,b.iv.buffer,e);if(i.part>-1){const e=t.flush();s=e?e.buffer:e}if(!s)return o.executeEnd=Gr(),Jr(i);l=new Uint8Array(s)}}const A=this.needsProbing(u,f);if(A){const t=this.configureTransmuxer(l);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),o.executeEnd=Gr(),Jr(i)}(u||f||p||A)&&this.resetInitSegment(S,v,y,T,e),(u||p||A)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const L=this.transmux(l,b,m,g,i);this.asyncResult=tn(L);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,o.executeEnd=Gr(),L}flush(t){const e=t.transmuxing;e.executeStart=Gr();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const n=[],{timeOffset:a}=s;if(i){const e=i.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Gr();const i=[Jr(t)];return this.asyncResult?Promise.resolve(i):i}const d=o.flush(a);return tn(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=e,{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===c?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Gr()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,s,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,i,s),a.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,s,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,s,r):this.transmuxUnencrypted(t,i,s,r),n}transmuxUnencrypted(t,e,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){return this.demuxer.demuxSampleAes(t,e,i).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s}=this;let r;for(let e=0,i=Qr.length;e<i;e++){var n;if(null!=(n=Qr[e].demux)&&n.probe(t,this.logger)){r=Qr[e];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,e,s,this.logger)),a&&a instanceof d||(this.demuxer=new d(i,e,s,this.logger),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new $e(this.config)),t}}const Jr=t=>({remuxResult:{},chunkMeta:t});function tn(t){return"then"in t&&t.then instanceof Function}class en{constructor(t,e,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=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class sn{constructor(t,e,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=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}let rn=0;class nn{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=rn++,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=t=>{const e=t.data,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var s;const t=null==(s=this.workerContext)?void 0:s.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,i.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const o=t.config;this.hls=t,this.id=e,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const l=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===a.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new xs,this.observer.on(a.FRAG_DECRYPTED,l),this.observer.on(a.ERROR,l);const d=Pt(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(i.log(`loading Web Worker ${o.workerPath} for "${e}"`),this.workerContext=function(t){const e=Os[t];if(e)return e.clientCount++,e;const i=new self.URL(t,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Os[t]=s,s}(o.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Os[Ms];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(e),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return Os[Ms]=s,s}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:d,id:e,config:Xt(o)})}catch(s){i.warn(`Error setting up "${e}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new Zr(this.observer,d,o,"",e,t.logger)}return}}this.transmuxer=new Zr(this.observer,d,o,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=rn++;const e=this.hls.config,i=Pt(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:Xt(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Os[t||Ms];if(e&&1===e.clientCount--){const{worker:i,objectURL:s}=e;delete Os[t||Ms],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,s,r,n,a,o,l,d){var h,u;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,m=n?n.start:r.start,p=r.decryptdata,v=this.frag,y=!(v&&r.cc===v.cc),E=!(v&&l.level===v.level),T=v?l.sn-v.sn:-1,S=this.part?l.part-this.part.index:-1,b=0===T&&l.id>1&&l.id===(null==v?void 0:v.stats.chunkCount),A=!E&&(1===T||0===T&&(1===S||b&&S<=0)),L=self.performance.now();(E||T||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),!n||!S&&A||(n.stats.parsing.start=L);const I=!(v&&(null==(h=r.initSegment)?void 0:h.url)===(null==(u=v.initSegment)?void 0:u.url)),R=new sn(y,A,o,E,m,I);if(!A||y||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===c?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${y}\n trackSwitch: ${E}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${m}\n initSegmentChange: ${I}`);const t=new en(i,s,e,a,d);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:R},t instanceof ArrayBuffer?[t]:[]);else if(g){const e=g.push(t,p,l,R);tn(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const e=i.flush(t);tn(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class an extends T{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}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(t,e,i){const s=null==e?void 0:e.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,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=s[r],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=i&&jt(i);return new qt(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,i){const{details:s,stats:o}=e,l=self.performance.now(),d=o.loading.first?Math.max(0,l-o.loading.first):0;s.advancedDateTime=Date.now()-d;const h=this.hls.config.timelineOffset;if(h!==s.appliedTimelineOffset){const t=Math.max(h||0,0);s.appliedTimelineOffset=t,s.fragments.forEach(e=>{e.setStart(e.playlistOffset+t)})}if(s.live||null!=i&&i.live){const h="levelInfo"in e?e.levelInfo:e.track;if(s.reloaded(i),i&&s.fragments.length>0){Xi(i,s,this);const t=s.playlistParsingError;if(t){this.warn(t);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var c;const{networkDetails:l}=e;return void i.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(c=s.fragments[0])?void 0:c.type,networkDetails:l,stats:o})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=o.loading.start);const u=this.hls.mainForwardBufferInfo,f=u?u.end-u.len:0,g=ts(s,1e3*(s.edge-f));if(s.requestScheduled+g<l?s.requestScheduled=l:s.requestScheduled+=g,this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let m,p,v;if(s.canBlockReload&&s.endSN&&s.advanced){const t=this.hls.config.lowLatencyMode,r=s.lastPartSn,n=s.endSN,a=s.lastPartIndex,o=r===n;-1!==a?o?(p=n+1,v=t?0:a):(p=r,v=t?a+1:s.maxPartIndex):p=n+1;const d=s.age,c=d+s.ageHeader;let u=Math.min(c-s.partTarget,1.5*s.targetduration);if(u>0){if(c>3*s.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(null!=i&&i.tuneInGoal&&c-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${u} with playlist age: ${s.age}`),u=0;else{const t=Math.floor(u/s.targetduration);if(p+=t,void 0!==v){v+=Math.round(u%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${u} skip sn ${t} to part ${v}`)}s.tuneInGoal=u}if(m=this.getDeliveryDirectives(s,e.deliveryDirectives,p,v),t||!o)return s.requestScheduled=l,void this.loadingPlaylist(h,m)}else(s.canBlockReload||s.canSkipUntil)&&(m=this.getDeliveryDirectives(s,e.deliveryDirectives,p,v));m&&void 0!==p&&s.canBlockReload&&(s.requestScheduled=o.loading.first+Math.max(g-2*d,g/2)),this.scheduleLoading(h,m,s)}else this.clearTimer()}scheduleLoading(t,e,i){const s=i||t.details;if(!s)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=s.requestScheduled;if(r>=n)return void this.loadingPlaylist(t,e);const a=n-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,i,s){let r=jt(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,r=Kt),new qt(i,s,r)}checkRetry(t){const e=t.details,i=he(t),s=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===Se||!s.resolved&&r===Ee);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=ge(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,s.resolved=!0}return o}}function on(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!ln(t[i].attrs,e[i].attrs))return!1;return!0}function ln(t,e,i){const s=t["STABLE-RENDITION-ID"];return s&&!i?s===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>t[i]!==e[i])}function dn(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class hn{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;const s=this.queues[e];s.push(t),1!==s.length||i||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const i=null==(e=t[0])?void 0:e.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(null===this.queues)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){var i;if(s.onError(e),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[t])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=null==(e=this.tracks)?void 0:e[t],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const cn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,un="HlsJsTrackRemovedError";class fn extends Error{constructor(t){super(t),this.name=un}}function gn(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function mn(t){return"audio"===t?1:0}class pn{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,i){this.timer&&e(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.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 t=this.hls.levels;if(t.length){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter((e,i)=>this.isLevelAllowed(e)&&i<=t);return this.clientRect=null,pn.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 t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,i){if(null==t||!t.length)return-1;const s=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let r=t.length-1;const n=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=n||i.height>=n)&&s(i,t[e+1])){r=e;break}}return r}}const vn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},yn={HLS:"h"};class En{constructor(t,e){Array.isArray(t)&&(t=t.map(t=>t instanceof En?t:new En(t))),this.value=t,this.params=e}}function Tn(t,e,i,s){return new Error(`failed to ${t} "${r=e,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 Sn(t,e,i){return Tn("serialize",t,e,i)}class bn{constructor(t){this.description=t}}const An="Bare Item";function Ln(t){if(!1===ArrayBuffer.isView(t))throw Sn(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function In(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw Sn(t,"Integer");return t.toString()}function Rn(t,e){if(t<0)return-Rn(-t,e);const i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){const e=Math.floor(t*i);return(e%2==0?e:e+1)/i}return Math.round(t*i)/i}function kn(t){const e=Rn(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Sn(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}const _n=/[\x00-\x1f\x7f]+/;function wn(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Sn(e,"Token");return e}function Dn(t){switch(typeof t){case"number":if(!e(t))throw Sn(t,An);return Number.isInteger(t)?In(t):kn(t);case"string":return function(t){if(_n.test(t))throw Sn(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return wn(t);case"boolean":return function(t){if("boolean"!=typeof t)throw Sn(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${In(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return Ln(t);if(t instanceof bn)return wn(t);default:throw Sn(t,An)}}function Pn(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Sn(t,"Key");return t}function Cn(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${Pn(t)}`:`;${Pn(t)}=${Dn(e)}`).join("")}function xn(t){return t instanceof En?`${Dn(t.value)}${Cn(t.params)}`:Dn(t)}function Mn(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw Sn(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),s=(null==e?void 0:e.whitespace)?" ":"";return Array.from(i).map(([t,e])=>{e instanceof En==!1&&(e=new En(e));let i=Pn(t);var s;return!0===e.value?i+=Cn(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(s=e).value.map(xn).join(" ")})${Cn(s.params)}`:i+=xn(e)),i}).join(`,${s}`)}function On(t,e){return Mn(t,e)}const Fn="CMCD-Object",Nn="CMCD-Request",Bn="CMCD-Session",Un="CMCD-Status",$n={br:Fn,ab:Fn,d:Fn,ot:Fn,tb:Fn,tpb:Fn,lb:Fn,tab:Fn,lab:Fn,url:Fn,pb:Nn,bl:Nn,tbl:Nn,dl:Nn,ltc:Nn,mtp:Nn,nor:Nn,nrr:Nn,rc:Nn,sn:Nn,sta:Nn,su:Nn,ttfb:Nn,ttfbb:Nn,ttlb:Nn,cmsdd:Nn,cmsds:Nn,smrt:Nn,df:Nn,cs:Nn,ts:Nn,cid:Bn,pr:Bn,sf:Bn,sid:Bn,st:Bn,v:Bn,msd:Bn,bs:Un,bsd:Un,cdn:Un,rtp:Un,bg:Un,pt:Un,ec:Un,e:Un},Gn=Nn;function Kn(t,e){const i={};if(!t)return i;const s=Object.keys(t),r=e?(n=e,Object.keys(n).reduce((t,e)=>{var i;return null===(i=n[e])||void 0===i||i.forEach(i=>t[i]=e),t},{})):{};var n;return s.reduce((e,i)=>{var s;const n=$n[i]||r[i]||Gn;return(null!==(s=e[n])&&void 0!==s?s:e[n]={})[i]=t[i],e},i)}const Vn="event";const Hn=t=>Math.round(t),jn=(t,e)=>Array.isArray(t)?t.map(t=>jn(t,e)):t instanceof En&&"string"==typeof t.value?new En(jn(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){const i=new URL(t),s=new URL(e);if(i.origin!==s.origin)return t;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}(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),qn=t=>100*Hn(t/100),Yn={br:Hn,d:Hn,bl:qn,dl:qn,mtp:qn,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof En&&"string"==typeof t.value?i=new En([t]):"string"==typeof t&&(i=[t])),jn(i,e)},rtp:qn,tb:Hn},Wn="request",zn="response",Xn=["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"],Qn=["e"],Zn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Jn(t){return Zn.test(t)}const ta=["d","dl","nor","ot","rtp","su"];const ea=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const ia=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function sa(t){return ia.includes(t)||Jn(t)}const ra={[zn]:function(t){return Xn.includes(t)||ta.includes(t)||ea.includes(t)||Jn(t)},[Vn]:function(t){return Xn.includes(t)||Qn.includes(t)||Jn(t)},[Wn]:function(t){return Xn.includes(t)||ta.includes(t)||Jn(t)}};function na(t,i={}){const s={};if(null==t||"object"!=typeof t)return s;const r=i.version||t.v||1,n=i.reportingMode||Wn,a=1===r?sa:ra[n];let o=Object.keys(t).filter(a);const l=i.filter;"function"==typeof l&&(o=o.filter(l));const d=n===zn||n===Vn;d&&!o.includes("ts")&&o.push("ts"),r>1&&!o.includes("v")&&o.push("v");const h=v({},Yn,i.formatters),c={version:r,reportingMode:n,baseUrl:i.baseUrl};return o.sort().forEach(i=>{let n=t[i];const a=h[i];if("function"==typeof a&&(n=a(n,c)),"v"===i){if(1===r)return;n=r}"pr"==i&&1===n||(d&&"ts"===i&&!e(n)&&(n=Date.now()),function(t){return"number"==typeof t?e(t):null!=t&&""!==t&&!1!==t}(n)&&(function(t){return["ot","sf","st","e","sta"].includes(t)}(i)&&"string"==typeof n&&(n=new bn(n)),s[i]=n))}),s}function aa(t,e,i){return v(t,function(t,e={}){const i={};if(!t)return i;const s=Kn(na(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(s).reduce((t,[e,i])=>{const s=On(i,{whitespace:!1});return s&&(t[e]=s),t},i)}(e,i))}function oa(t,e={}){if(!t)return"";const i=function(t,e={}){return t?On(na(t,e),{whitespace:!1}):""}(t,e);return encodeURIComponent(i)}const la=/CMCD=[^&#]+/;function da(t,e,i){const s=function(t,e={}){return t?`CMCD=${oa(t,e)}`:""}(e,i);if(!s)return t;if(la.test(t))return t.replace(la,s);const r=t.includes("?")?"&":"?";return`${t}${r}${s}`}function ha(t,e,i,s){t&&Object.keys(e).forEach(r=>{const n=t.filter(t=>t.groupId===r).map(t=>{const n=v({},t);return n.details=void 0,n.attrs=new si(n.attrs),n.url=n.attrs.URI=ca(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=s,n});t.push(...n)})}function ca(t,e,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(t=>{t&&l.searchParams.set(t,n[t])}),l.href}class ua extends T{constructor(t){super("eme",t.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=ua.CDMCleanupPromise?[ua.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:e,initData:i}=t,s=`"${t.type}" event: init data type: "${e}"`;if(this.debug(s),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Li(this.config));const e=t.map(Ai).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{const n=bi(r);if("sinf"!==e||n!==vi.FAIRPLAY)return void this.log(`Ignoring "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);let a;try{const t=W(new Uint8Array(i)),e=lt(ui(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${s} Failed to parse sinf: ${t}`)}const o=D(a),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this;let h=l[o];for(let t=0;t<d.length;t++){const s=d[t],r=s.decryptdata;if(!r.keyId)continue;const n=D(r.keyId);if(li(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,e,i,"encrypted-event-key-match")),h.catch(t=>this.handleError(t));break}}h||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(a.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(a.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(a.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(a.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(a.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(a.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,s=null==e?void 0:e[t];return s?s.licenseUrl:t===vi.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(t){const e=this.getLicenseServerUrl(t);if(void 0===e)throw new Error(`no license server URL configured for key-system "${t}"`);return e}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=null==e?void 0:e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,s=e.map(t=>t.audioCodec).filter(i),a=e.map(t=>t.videoCodec).filter(i);return s.length+a.length===0&&a.push("avc1.42e01e"),new Promise((e,i)=>{const o=t=>{const l=t.shift();this.getMediaKeysPromise(l,s,a).then(t=>e({keySystem:l,mediaKeys:t})).catch(e=>{t.length?o(t):i(e instanceof ma?e:new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};o(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Ii&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){var s;const r=function(t,e,i,s){let r;switch(t){case vi.FAIRPLAY:r=["cenc","sinf"];break;case vi.WIDEVINE:case vi.PLAYREADY:r=["cenc"];break;case vi.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,s){return[{initDataTypes:t,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}(r,e,i,s)}(t,e,i,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(s=n)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Xt(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,s.then(e=>e?this.setMediaKeysServerCertificate(i,t,e):i)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${D(t.keyId||[])} keyUri: ${t.uri}`);const s=i.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),s=fa(e),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,e){const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${D(t.decryptdata.keyId||[])}\n } (data length: ${e.byteLength})`),i.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Ai(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return new Promise((e,i)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const s=Ai(t);s?e(s):i(new Error(`Unable to find format for key-system "${t}"`))}).catch(i)})}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){const e=Li(this.config),i=t.map(bi).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(i)}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let i=0;i<e.length;i++){const s=ga(t,e[i]);if(s)return s}}loadKey(t){const e=t.keyInfo.decryptdata,i=fa(e),s=this.bannedKeyIds[i];if(s||"internal-error"===this.getKeyStatus(e)){const i=pa(s||"internal-error",e);return this.handleError(i,t.frag),Promise.reject(i)}const r=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[i];if(!n){const s=this.getKeySystemForKeyPromise(e).then(({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:e}))))).then(t=>{const i=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",i,"playlist-key")});return s.catch(e=>this.handleError(e,t.frag)),this.keyIdToKeySessionPromise[i]=s,s}return n.catch(i=>{if(i instanceof ma){const s=E({},i.data);"internal-error"===this.getKeyStatus(e)&&(s.decryptdata=e);const r=new ma(s,i.message);this.handleError(r,t.frag)}}),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof ma){e&&(t.data.frag=e);const i=t.data.decryptdata;this.error(`${t.message}${i?` (${D(i.keyId||[])})`:""}`),this.hls.trigger(a.ERROR,t.data)}else this.error(t.message),this.hls.trigger(a.ERROR,{type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=fa(t),i=this.keyIdToKeySessionPromise[e];if(!i){const e=bi(t.keyFormat),i=e?[e]:Li(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=Li(this.config)),0===t.length)throw new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Xt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(i)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===i.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,i,s){var a;const o=null==(a=this.config.drmSystems)||null==(a=a[t.keySystem])?void 0:a.generateRequest;if(o)try{const s=o.call(this.hls,e,i,t);if(!s)throw new Error("Invalid response from configured generateRequest filter");e=s.initDataType,i=s.initData?s.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(t){if(this.warn(t.message),this.hls&&this.hls.config.debug)throw t}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const l=fa(t.decryptdata),d=t.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${l} URI: ${d} (init data type: ${e} length: ${i.byteLength})`);const h=new xs,c=t._onmessage=e=>{const i=t.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));const{messageType:s,message:r}=e;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(t,r).catch(t=>{h.eventNames().length?h.emit("error",t):this.handleError(t)}):"license-release"===s?t.keySystem===vi.FAIRPLAY&&this.updateKeySession(t,fi("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${s}"`)},u=(t,e)=>{let i;e.keyStatus=t,t.startsWith("usable")?h.emit("resolved"):"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=pa(t,e.decryptdata):"expired"===t?i=new Error(`key expired (keyId: ${l})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${l})`),i&&(h.eventNames().length?h.emit("error",i):this.handleError(i))},f=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));const i=this.getKeyStatuses(t);if(!Object.keys(i).some(t=>"status-pending"!==i[t]))return;if("expired"===i[l])return this.log(`Expired key ${Xt(i)} in key-session "${t.mediaKeysSession.sessionId}"`),void this.renewKeySession(t);let s=i[l];if(s)u(s,t);else{var r;const e=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(r=t.keyStatusTimeouts)[l]||(r[l]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const i=this.getKeyStatus(t.decryptdata);if(i&&"status-pending"!==i)return this.log(`No status for keyId ${l} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${i} from other session.`),u(i,t);this.log(`key status for ${l} in key-session "${t.mediaKeysSession.sessionId}" timed out after ${e}ms`),s="internal-error",u(s,t)},e)),this.log(`No status for keyId ${l} (${Xt(i)}).`)}};us(t.mediaKeysSession,"message",c),us(t.mediaKeysSession,"keystatuseschange",f);const g=new Promise((t,e)=>{h.on("error",e),h.on("resolved",t)});return t.mediaKeysSession.generateRequest(e,i).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${l} URI: ${d}`)}).catch(e=>{throw new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>g).catch(e=>(h.removeAllListeners(),this.removeSession(t).then(()=>{throw e}))).then(()=>(h.removeAllListeners(),t))}getKeyStatuses(t){const e={};return t.mediaKeysSession.keyStatuses.forEach((i,s)=>{if("string"==typeof s&&"object"==typeof i){const t=s;s=i,i=t}const r="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);if(t.keySystem===vi.PLAYREADY&&16===r.length){const t=D(r);e[t]=i,gi(r)}const n=D(r);"internal-error"===i&&(this.bannedKeyIds[n]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${n} key-session "${t.mediaKeysSession.sessionId}"`),e[n]=i}),e}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),s=this.getServerCertificateUrl(t);return s?(this.log(`Fetching server certificate for "${t}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:s},d=e.certLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,i,s)=>{a(t.data)},onError:(e,i,a,d)=>{o(new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:E({url:l.url,data:void 0},e)},`"${t}" certificate request failed (${s}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,a)=>{o(new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${s})`))},onAbort:(t,e,i)=>{o(new Error("aborted"))}};i.load(l,h,c)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((s,a)=>{t.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),s(t)}).catch(t=>{a(new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(e=>this.updateKeySession(t,new Uint8Array(e)).catch(e=>{throw new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(t,e){const i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const s=(new DOMParser).parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let i=0,s=r.length;i<s;i++){var n,a;e=r[i];const s=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;s&&o&&t.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 fi(atob(l))}setupLicenseXHR(t,e,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,t,e,i,s)}).catch(n=>{if(!i.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,i,s)}).then(i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||s}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:s}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise((s,a)=>{const o=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${o}`);const l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return a(new Error("invalid state"));if(4===l.readyState)if(200===l.status){this._requestLicenseFailureCount=0;let e=l.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,l,o,t)}catch(t){this.error(t)}s(e)}else{const d=i.errorRetry,h=d?d.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>h||l.status>=400&&l.status<500)a(new ma({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:l,response:{url:o,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${o}). Status: ${l.status} (${l.statusText})`));else{const i=h-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(t,e).then(s,a)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=l,this.setupLicenseXHR(l,o,t,e).then(({xhr:e,licenseChallenge:i})=>{t.keySystem==vi.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}).catch(a)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,us(i,"encrypted",this.onMediaEncrypted),us(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(fs(t,"encrypted",this.onMediaEncrypted),fs(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,wi.clearKeyUriToKeyIdMap();const o=s.length;ua.CDMCleanupPromise=Promise.all(s.map(t=>this.removeSession(t)).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{o&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i,decryptdata:s}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}" keyId: ${D((null==s?void 0:s.keyId)||[])}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const o=this.mediaKeySessions.indexOf(t);o>-1&&this.mediaKeySessions.splice(o,1);const{keyStatusTimeouts:l}=t;l&&Object.keys(l).forEach(t=>self.clearTimeout(l[t]));const{drmSystemOptions:d}=this.config,h=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(d)?new Promise((t,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(i)}):Promise.resolve();return h.catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function fa(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return D(t.keyId)}function ga(t,e){return t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId)?e.mediaKeysSession.keyStatuses.get(t.keyId):t.matches(e.decryptdata)?e.keyStatus:void 0}ua.CDMCleanupPromise=void 0;class ma extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}function pa(t,e){const i="output-restricted"===t,s=i?n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ma({type:r.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},i?"HDCP level output restricted":`key status changed to "${t}"`)}function va(t,e){let i;try{i=new Event("addtrack")}catch(t){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function ya(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){R.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){R.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function Ea(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)e&&t.cues[i].removeEventListener("enter",e),t.removeCue(t.cues[i]);"disabled"===i&&(t.mode=i)}function Ta(t,e,i,s){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,i){const s=[],r=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let s,r=0,n=i;for(;r<=n;)if(s=Math.floor((n+r)/2),e<t[s].startTime)n=s-1;else{if(!(e>t[s].startTime&&r<i))return s;r=s+1}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(t.cues,e,i);for(let e=0;e<r.length;e++)s&&!s(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function Sa(t){const e=[];for(let i=0;i<t.length;i++){const s=t[i];"subtitles"!==s.kind&&"captions"!==s.kind||!s.label||e.push(t[i])}return e}function ba(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}const Aa=.025;let La=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Ia(t,e,i){return`${t.identifier}-${i+1}-${ba(e)}`}class Ra{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const i=this.playoutLimit;if(t<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return ka(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-ka(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,i=e(t)?t:this.duration;return this.cumulativeDuration+i}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return ka(t,e)}return t}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)<Aa))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?La.Range:La.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`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function ka(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<Aa)?e.start:e.start+e.duration}function _a(t,e,i){const s=new self.URL(t,i);return"data:"!==s.protocol&&s.searchParams.set("_HLS_primary_id",e),s}function wa(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function Da(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class Pa{constructor(t,e,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(a.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(a.LEVEL_LOADED,n),r.once(a.AUDIO_TRACK_LOADED,n),r.once(a.SUBTITLE_TRACK_LOADED,n),r.on(a.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(a.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger(a.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=_a(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,r=ze.bufferInfo(t,s,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=ze.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const i=e-this.startOffset;if(i>0&&i<t)return i}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const i=t-e;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=t}}}getAssetTime(t){const e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,i){var s;null==(s=this.hls)||s.on(t,e)}once(t,e,i){var s;null==(s=this.hls)||s.once(t,e)}off(t,e,i){var s;null==(s=this.hls)||s.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${Da(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class Ca extends T{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((i,s)=>t<=s.startOffset&&e>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(e&&"primary"!==e&&(r=r[e]),t===r.start||t>r.start&&t<r.end)return s}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let s=t;s<=e&&i[s];s++){const t=i[s].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return s}return-1}findEventIndex(t){const e=this.items;if(e)for(let s=e.length;s--;){var i;if((null==(i=e[s].event)?void 0:i.identifier)===t)return s}return-1}findAssetIndex(t,e){const i=t.assetList,s=i.length;if(s>1)for(let t=0;t<s;t++){const r=i[t];if(!r.error){const i=r.timelineStart;if(e===i||e>i&&(e<i+(r.duration||0)||t===s-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e){const i=t.main.details,{dateRanges:s}=i,r=this.events,n=this.parseDateRanges(s,{url:i.url},e),a=Object.keys(s),o=r?r.filter(t=>!a.includes(t.identifier)):[];n.length&&n.sort((t,e)=>{const i=t.cue.pre,s=t.cue.post,r=e.cue.pre,n=e.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=t.startTime,s=e.startTime;if(i!==s)return i-s}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=n,o.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,o)}updateSchedule(t,e=[],i=!1){const s=this.events||[];if(s.length||e.length||this.length<2){const r=this.items,n=this.parseSchedule(s,t);(i||e.length||(null==r?void 0:r.length)!==n.length||n.some((t,e)=>Math.abs(t.playout.start-r[e].playout.start)>.005||Math.abs(t.playout.end-r[e].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(e,r))}}parseDateRanges(t,e,i){const s=[],r=Object.keys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new Ra(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),s.push(t)}}return s}parseSchedule(t,e){const i=[],s=e.main.details,r=s.live?1/0:s.edge;let n=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let s=0,o=0;if(t.forEach((e,a)=>{const l=e.cue.pre,d=e.cue.post,h=t[a-1]||null,c=e.appendInPlace,u=d?r:e.startOffset,f=e.duration,g=e.timelineOccupancy===La.Range?f:0,m=e.resumptionOffset,p=(null==h?void 0:h.startTime)===u,v=u+e.cumulativeDuration;let y=c?v+f:u+m;if(l||!d&&u<=0){const t=o;o+=g,e.timelineStart=v;const s=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:s,end:n},integrated:{start:t,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:t[a-1]||null,nextEvent:e,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&&(y=v),e.timelineStart=v;const r=o;o+=g;const l=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const E=e.resumeTime;s=d||E>r?r:E}),s<r){var a;const t=s,e=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:t+l,playout:{start:d,end:n},integrated:{start:e,end:o}})}this.setDurations(r,n,o)}else{const t=0;i.push({previousEvent:null,nextEvent:null,start:t,end:r,playout:{start:t,end:r},integrated:{start:t,end:r}}),this.setDurations(r,r,r)}return i}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,i){const s=i.main.details,r=s.live?1/0:s.edge;let n=0,a=-1;t.forEach((o,l)=>{const d=o.cue.pre,h=o.cue.post,c=d?0:h?r:o.startTime;this.updateAssetDurations(o);if(a===c?o.cumulativeDuration=n:(n=0,a=c),!h&&o.snapOptions.in&&(o.resumeAnchor=ae(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(o,i)||(o.appendInPlace=!1)}if(!o.appendInPlace&&l+1<t.length){t[l+1].startTime-t[l].resumeTime<.033&&(t[l+1].appendInPlace=!1,t[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`))}const u=e(o.resumeOffset)?o.resumeOffset:o.duration;n+=u})}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,s=t.startTime+t.resumptionOffset;if(Math.abs(i-s)>Aa)return this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1;return!Object.keys(e).some(s=>{const r=e[s].details,n=r.edge;if(i>=n)return this.log(`"${t.identifier}" resumption ${i} past ${s} playlist end ${n}`),!1;const a=ae(null,r.fragments,i);if(!a)return this.log(`"${t.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)<Aa+o||Math.abs(a.end-i)<Aa+o)&&(this.log(`"${t.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}t.duration=s&&!r?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function xa(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class Ma{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let s;try{s=_a(i,this.hls.sessionId,t.baseUrl)}catch(e){const s=this.assignAssetListError(t,n.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(a.ERROR,s)}e&&"data:"!==s.protocol&&s.searchParams.set("_HLS_start_offset",""+e);const r=this.hls.config,o=new(0,r.loader)(r),l={responseType:"json",url:s.href},d=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,i,s,r)=>{const o=e.data,l=null==o?void 0:o.ASSETS;if(!Array.isArray(l)){const e=this.assignAssetListError(t,n.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,r);return void this.hls.trigger(a.ERROR,e)}t.assetListResponse=o,this.hls.trigger(a.ASSET_LIST_LOADED,{event:t,assetListResponse:o,networkDetails:r})},onError:(e,i,s,r)=>{const o=this.assignAssetListError(t,n.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,r,s);this.hls.trigger(a.ERROR,o)},onTimeout:(e,i,s)=>{const r=this.assignAssetListError(t,n.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,s);this.hls.trigger(a.ERROR,r)}};return o.load(l,h,c),this.hls.trigger(a.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,e,i,s,n,a){return t.error=i,{type:r.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:s,error:i,networkDetails:a,stats:n}}}function Oa(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function Fa(t,e){return`[${t}] Advancing timeline position to ${e}`}class Na{constructor(t){this.buffered=void 0;const e=(e,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}const Ba={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},Ua=t=>String.fromCharCode(Ba[t]||t),$a=15,Ga=100,Ka={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Va={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ha={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ja={25:2,26:4,29:6,30:8,31:10,27:13,28:15},qa=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ya{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;R.log(`${this.time} [${t}] ${i}`)}}}const Wa=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class za{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(t){const e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){const s=e[i];t.hasOwnProperty(s)&&(this[s]=t[s])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Xa{constructor(){this.uchar=" ",this.penState=new za}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Qa{constructor(t){this.chars=[],this.pos=0,this.currPenState=new za,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ga;t++)this.chars.push(new Xa);this.logger=t}equals(t){for(let e=0;e<Ga;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Ga;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Ga;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ga&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ga)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Ua(t);this.pos>=Ga?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<Ga;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<Ga;i++){const s=this.chars[i].uchar;" "!==s&&(e=!1),t.push(s)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class Za{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<$a;e++)this.rows.push(new Qa(t));this.logger=t}reset(){for(let t=0;t<$a;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<$a;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<$a;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<$a;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+Xt(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<$a;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[t].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[e-this.nrRollUpRows+s+1].copy(i.rows[t+s])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,s=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[s].penState.foreground}const s={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+Xt(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}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 t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",s=-1;for(let i=0;i<$a;i++){const r=this.rows[i].getTextString();r&&(s=i+1,t?e.push("Row "+s+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class Ja{constructor(t,e,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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Za(i),this.nonDisplayedMemory=new Za(i),this.lastOutputScreen=new Za(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(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"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=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+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(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}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 t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=s[i]}this.logger.log(2,"MIDROW: "+Xt(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class to{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new Ya;this.channels=[null,new Ja(t,e,s),new Ja(t+1,i,s)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],s=127&e[t+1];let r=!1,n=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+Wa([e[t],e[t+1]])+"] -> ("+Wa([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(io(i,s,a)){eo(null,null,a),this.logger.log(3,()=>"Repeated command ("+Wa([i,s])+") is dropped");continue}eo(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 eo(null,null,a);if(!r&&(n=this.parseChars(i,s),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+Wa([i,s])+" orig: "+Wa([e[t],e[t+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const i=20===t||21===t||23===t?1:2,s=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?s.ccRCL():33===e?s.ccBS():34===e?s.ccAOF():35===e?s.ccAON():36===e?s.ccDER():37===e?s.ccRU(2):38===e?s.ccRU(3):39===e?s.ccRU(4):40===e?s.ccFON():41===e?s.ccRDC():42===e?s.ccTR():43===e?s.ccRTD():44===e?s.ccEDM():45===e?s.ccCR():46===e?s.ccENM():47===e&&s.ccEOC():s.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?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(e),this.logger.log(3,()=>"MIDROW ("+Wa([t,e])+")"),!0)}return!1}parsePAC(t,e){let i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const s=t<=23?1:2;i=e>=64&&e<=95?1===s?Ka[t]:Ha[t]:1===s?Va[t]:ja[t];const r=this.channels[s];return!!r&&(r.setPAC(this.interpretPAC(i,e)),this.currentChannel=s,!0)}interpretPAC(t,e){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-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(t,e){let i,s=null,r=null;if(t>=25?(i=2,r=t-8):(i=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,()=>"Special char '"+Ua(t)+"' in channel "+i),s=[t]}else t>=32&&t<=127&&(s=0===e?[t]:[t,e]);return s&&this.logger.log(3,()=>"Char codes = "+Wa(s).join(",")),s}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const s={};16===t||24===t?(i=Math.floor((e-32)/2),s.background=qa[i],e%2==1&&(s.background=s.background+"_semi")):45===e?s.background="transparent":(s.foreground="black",47===e&&(s.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(s),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}eo(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function eo(t,e,i){i.a=t,i.b=e}function io(t,e,i){return i.a===t&&i.b===e}var so=function(){if(null!=pi&&pi.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function s(t){return i(e,t)}function r(t,...e){let i=1;for(;i<arguments.length;i++){const e=arguments[i];for(const i in e)t[i]=e[i]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=e,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,b="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(e){const s=function(e){return i(t,e)}(e);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(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return b},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");b=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class ro{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function no(t){function e(t,e,i,s){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(s||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class ao{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let s=0;s<i.length;++s)if(e===i[s]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function oo(t,e,i,s){const r=s?t.split(s):[t];for(const t in r){if("string"!=typeof r[t])continue;const s=r[t].split(i);if(2!==s.length)continue;e(s[0],s[1])}}const lo=new so(0,0,""),ho="middle"===lo.align?"middle":"center";function co(t,e,i){const s=t;function r(){const e=no(t);if(null===e)throw new Error("Malformed timestamp: "+s);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const s=new ao;oo(t,function(t,e){let r;switch(t){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===e){s.set(t,i[r].region);break}break;case"vertical":s.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),s.integer(t,r[0]),s.percent(t,r[0])&&s.set("snapToLines",!1),s.alt(t,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",ho,"end"]);break;case"position":r=e.split(","),s.percent(t,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",ho,"end","line-left","line-right","auto"]);break;case"size":s.percent(t,e);break;case"align":s.alt(t,e,["start",ho,"end","left","right"])}},/:/,/\s/),e.region=s.get("region",null),e.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===lo.line&&(r=-1),e.line=r,e.lineAlign=s.get("lineAlign","start"),e.snapToLines=s.get("snapToLines",!0),e.size=s.get("size",100),e.align=s.get("align",ho);let n=s.get("position","auto");"auto"===n&&50===lo.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function uo(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class fo{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ro,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=uo(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const s=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),s}function s(t){oo(t,function(t,e){},/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=i();const s=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=i(),e.state){case"HEADER":/:/.test(t)?s(t):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new so(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{co(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==t.indexOf("--\x3e");if(!t||i&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const go=/\r\n|\n\r|\n|\r/g,mo=function(t,e,i=0){return t.slice(i,i+e.length)===e};function po(t,e,i){return ba(t.toString())+ba(e.toString())+ba(i)}function vo(t,i,s,r,n,a,o){const l=new fo,d=w(new Uint8Array(t)).trim().replace(go,"\n").split("\n"),h=[],c=i?function(t,e=1){return Br(t,9e4,1/e)}(i.baseTime,i.timescale):0;let u,f="00:00.000",g=0,m=0,p=!0;l.oncue=function(t){const e=s[r];let a=s.ccOffset;const o=(g-c)/9e4;if(null!=e&&e.new&&(void 0!==m?a=s.ccOffset=e.start:function(t,e,i){let s=t[e],r=t[s.prevCC];if(!r||!r.new&&s.new)return t.ccOffset=t.presentationOffset=s.start,void(s.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=s.start-r.start,s.new=!1,s=r,r=t[s.prevCC]}t.presentationOffset=i}(s,r,o)),o){if(!i)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,d=qr(9e4*(t.startTime+a-m),9e4*n)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+l,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id||(t.id=po(t.startTime,t.endTime,f)),t.endTime>0&&h.push(t)},l.onparsingerror=function(t){u=t},l.onflush=function(){u?o(u):a(h)},d.forEach(t=>{if(p){if(mo(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach(t=>{mo(t,"LOCAL:")?f=t.slice(6):mo(t,"MPEGTS:")&&(g=parseInt(t.slice(7)))});try{m=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(e(i)&&e(s)&&e(r)&&e(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*r,i+=36e5*n,i}(f)/1e3}catch(t){u=t}return}""===t&&(p=!1)}l.parse(t+"\n")}),l.flush()}const yo="stpp.ttml.im1t",Eo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,To=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,So={left:"start",center:"center",right:"end",start:"start",end:"end"};function bo(t,e,i,s){const r=J(new Uint8Array(t),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map(t=>w(t)),a=function(t,e,i=1,s=!1){return Br(t,e,1/i,s)}(e.baseTime,1,e.timescale);try{n.forEach(t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"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((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||r[e],t),{}),a="preserve"!==s.getAttribute("xml:space"),o=Lo(Ao(s,"styling","style")),l=Lo(Ao(s,"layout","region")),d=Ao(s,"body","[begin]");return[].map.call(d,t=>{const i=Io(t,a);if(!i||!t.hasAttribute("begin"))return null;const s=_o(t.getAttribute("begin"),n),r=_o(t.getAttribute("dur"),n);let d=_o(t.getAttribute("end"),n);if(null===s)throw ko(t);if(null===d){if(null===r)throw ko(t);d=s+r}const h=new so(s-e,d-e,i);h.id=po(h.startTime,h.endTime,h.text);const c=function(t,e,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce((i,n)=>{const a=Ro(e,s,n)||Ro(t,s,n)||Ro(r,s,n);return a&&(i[n]=a),i},{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:u}=c;if(u){const t=So[u];t&&(h.lineAlign=t),h.align=u}return v(h,c),h}).filter(t=>null!==t)}(t,a)))}catch(t){s(t)}}function Ao(t,e,i){const s=t.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function Lo(t){return t.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function Io(t,e){return[].slice.call(t.childNodes).reduce((t,i,s)=>{var r;return"br"===i.nodeName&&s?t+"\n":null!=(r=i.childNodes)&&r.length?Io(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Ro(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function ko(t){return new Error(`Could not parse ttml timestamp ${t}`)}function _o(t,e){if(!t)return null;let i=no(t);return null===i&&(Eo.test(t)?i=function(t,e){const i=Eo.exec(t),s=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/e.frameRate}(t,e):To.test(t)&&(i=function(t,e){const i=To.exec(t),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/e.frameRate;case"t":return s/e.tickRate}return s}(t,e))),i}class wo{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function Do(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Po(t,e){return!!t&&t.kind===Do(e)&&dn(e,t)}function Co(t,e,i,s){return Math.min(e,s)-Math.max(t,i)}const xo=/\s/,Mo={newCue(t,e,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 t=0;t<n.chars.length;t++)xo.test(n.chars[t].uchar)&&o?l++:(d+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const s=uo(d.trim()),f=po(e,i,s);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new h(e,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 t&&r.length&&(r.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),r.forEach(e=>ya(t,e))),r}};const Oo=/(\d+)-(\d+)\/(\d+)/;class Fo{constructor(t){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=t.fetchSetup||No,this.controller=new self.AbortController,this.stats=new F}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 t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,i,s){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(v({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(t,this.controller.signal),a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=i.loadPolicy;this.context=t,this.config=i,this.callbacks=s,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),i.timeout=l&&e(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))},i.timeout);(tn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(s=>{var n;this.response=this.loader=s;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),i.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))},d-(o-r.loading.start)),!s.ok){const{status:t,statusText:e}=s;throw new Bo(e||"fetch, bad network response",t,s)}r.loading.first=o,r.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const e=Oo.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(i);if(e(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(s.headers)||r.total;const l=null==(n=this.callbacks)?void 0:n.onProgress;return l&&e(i.highWaterMark)?this.loadProgressively(s,r,t,i.highWaterMark,l):a?s.arrayBuffer():"json"===t.responseType?s.json():s.text()}).then(s=>{var n,a;const l=this.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const d=s[o];d&&(r.loaded=r.total=d);const h={url:l.url,data:s,code:l.status},c=null==(n=this.callbacks)?void 0:n.onProgress;c&&!e(i.highWaterMark)&&c(r,t,s,l),null==(a=this.callbacks)||a.onSuccess(h,r,t,l)}).catch(e=>{var i;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=e&&e.code||0,n=e?e.message:null;null==(i=this.callbacks)||i.onError({code:s,text:n},t,e?e.details:null,r)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,r){const n=new ws,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(e,i,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<s||n.dataLength?(n.push(l),n.dataLength>=s&&r(e,i,n.flush().buffer,t)):r(e,i,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function No(t,e){return new self.Request(t.url,e)}class Bo extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Uo=/^age:\s*[\d.]+\s*$/im;class $o{constructor(t){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=t&&t.xhrSetup||null,this.stats=new F,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)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,e.url)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),r(i,e.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:t.message},e,i,s)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,i,s){t.readyState||t.open("GET",i.url,!0);const r=i.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[e]);i.rangeEnd&&t.setRequestHeader("Range","bytes="+i.rangeStart+"-"+(i.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=i.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&e(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const s=e.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),e.onreadystatechange=null,e.onprogress=null;const s=e.status,l="text"===e.responseType?e.responseText:null;if(s>=200&&s<300){const r=null!=l?l:e.response;if(null!=r){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.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,t,r,e);const d={url:e.responseURL,data:r,code:s};return void(null==(a=this.callbacks)||a.onSuccess(d,i,t,e))}}const d=r.loadPolicy.errorRetry;var o;if(pe(d,i.retry,!1,{url:t.url,data:void 0,code:s}))this.retry(d);else R.error(`${s} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:s,text:e.statusText},t,e,i)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(pe(t,this.stats.retry,!0))this.retry(t);else{var e;R.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=ge(t,i.retry),i.retry++,R.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Uo.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Go=E(E({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:$o,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends T{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:l}=n;if(!s||!l)return;const d=performance.now(),h=r?r.stats:s.stats,c=r?r.duration:s.duration,u=d-h.loading.start,f=n.minAutoLevel,g=s.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!o)return;const p=m>-1&&m!==g,v=!!t||p;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const y=n.mainForwardBufferInfo;if(!v&&null===y)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(u<=Math.max(E,c/(2*T)*1e3))return;const S=y?y.len/T:0,b=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&b>-1,L=this.getBwEstimate(),I=n.levels,R=I[g],k=Math.max(h.loaded,Math.round(c*(s.bitrate||R.averageBitrate)/8));let _=A?u-b:u;_<1&&A&&(_=Math.min(u,8*h.loaded/L));const w=A?1e3*h.loaded/_:0,D=E/1e3,P=w?(k-h.loaded)/w:8*k/L+D;if(P<=S)return;const C=w?8*w:L,x=!0===(null==(i=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:i.live),M=this.hls.config.abrBandWidthUpFactor;let O,F=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){const t=I[O].maxBitrate,e=!I[O].details||x;if(F=this.getTimeToLoadFrag(D,C,c*t,e),F<Math.min(S,c+D))break}if(F>=P)return;if(F>10*c)return;A?this.bwEstimator.sample(u-Math.min(E,b),h.loaded):this.bwEstimator.sampleTTFB(u);const N=I[O].maxBitrate;this.getBwEstimate()*M>N&&this.resetEstimator(N);const B=this.findBestLevel(N,f,O,0,S,1,1);B>-1&&(O=B),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${P.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|b} ms\n Current BW estimate: ${e(L)?0|L:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|N} bps`),n.nextLoadLevel=n.nextAutoLevel=O,this.clearTimer();const U=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===O&&O>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,O>f){let e=this.findBestLevel(this.hls.levels[f].bitrate,f,O,0,t,1,1);-1===e&&(e=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};p||P>2*F?U():this.timer=self.setInterval(U,1e3*F),n.trigger(a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:h})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new m(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(a.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){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(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=e.part)?s:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case n.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:s}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){const e=performance.now(),i=s?s.stats:t.stats,r=e-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,i,s){return t+i/e+(s?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:r}=i.stats,n=r.end-r.first;e(n)&&(this.lastLevelLoadSec=n/1e3),i.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(i.levelInfo)}onFragLoaded(t,{frag:e,part:i}){const s=i?i.stats:e.stats;if(e.type===c&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=i?i.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+s.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(a.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:s}=e,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(t){return t.type!==c||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,e,t,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);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 t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const s=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,s,l,0,d,h);if(t>=0)return this.rebufferNotice=-1,t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}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 t=this.hls,e=t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,i,s,r,n,a,o){var l;const d=r+n,h=this.lastLoadedFragLevel,c=-1===h?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:v}=this.hls;if(1===g.length)return 0;const y=g[c],E=!(null==(l=this.hls.latestLevelDetails)||!l.live),T=-1===p||-1===h;let S,b="SDR",A=(null==y?void 0:y.frameRate)||0;const{audioPreference:L,videoPreference:I}=v,R=this.audioTracksByGroup||(this.audioTracksByGroup=Zt(m));let k=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(t,e,i,s){return t.slice(i,s+1).reduce((t,i,s)=>{if(!i.codecSet)return t;const r=i.audioGroups;let n=t[i.codecSet];n||(t[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(t=>{if(!t)return;const i=e.groups[t];i&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach(t=>{n.channels[t]=(n.channels[t]||0)+i.channels[t]}))}),t},{})}(g,R,i,s)),n=function(t,i,s,r,n){const a=Object.keys(t),o=null==r?void 0:r.channels,l=null==r?void 0:r.audioCodec,d=null==n?void 0:n.videoCodec,h=o&&2===parseInt(o);let c=!1,u=!1,f=1/0,g=1/0,m=1/0,p=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=zt(i,n);for(let e=a.length;e--;){const i=t[a[e]];c||(c=i.channels[2]>0),f=Math.min(f,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter(t=>i.videoRanges[t]>0).length>0&&(u=!0)}f=e(f)?f:0,g=e(g)?g:0;const S=Math.max(1080,f),b=Math.max(30,g);m=e(m)?m:s,s=Math.max(m,s),u||(i=void 0);const A=a.length>1;return{codecSet:a.reduce((e,i)=>{const r=t[i];if(i===e)return e;if(y=u?T.filter(t=>r.videoRanges[t]>0):[],A){if(r.minBitrate>s)return Qt(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return Qt(i,"no renditions with default or auto-select sound found"),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Qt(i,`audio codec preference "${l}" not found`),e;if(o&&!h){if(!r.channels[o])return Qt(i,`no renditions with ${o} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!l||h)&&c&&0===r.channels[2])return Qt(i,"no renditions with stereo sound found"),e;if(r.minHeight>S)return Qt(i,`min resolution of ${r.minHeight} > maximum of ${S}`),e;if(r.minFramerate>b)return Qt(i,`min framerate of ${r.minFramerate} > maximum of ${b}`),e;if(!y.some(t=>r.videoRanges[t]>0))return Qt(i,`no variants with VIDEO-RANGE of ${Xt(y)} found`),e;if(d&&i.indexOf(d.substring(0,4))%5!=0)return Qt(i,`video codec preference "${d}" not found`),e;if(r.maxScore<v)return Qt(i,`max score of ${r.maxScore} < selected max of ${v}`),e}return e&&(Lt(i)>=Lt(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,v=r.maxScore,i)},void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:m,minIndex:p}}(r,b,t,L,I),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:d,minIndex:h,preferHDR:c}=n;k=h,S=a,b=c?o[o.length-1]:o[0],A=l,t=Math.max(t,d),this.log(`picked start tier ${Xt(n)}`)}else S=null==y?void 0:y.codecSet,b=null==y?void 0:y.videoRange;const _=f?f.duration:u?u.duration:0,w=this.bwEstimator.getEstimateTTFB()/1e3,D=[];for(let l=s;l>=i;l--){var P;const i=g[l],u=l>c;if(!i)continue;if(v.useMediaCapabilities&&!i.supportedResult&&!i.supportedPromise){const e=navigator.mediaCapabilities;"function"==typeof(null==e?void 0:e.decodingInfo)&&Ft(i,R,b,A,t,L)?(i.supportedPromise=Nt(i,R,e,this.supportedCache),i.supportedPromise.then(t=>{if(!this.hls)return;i.supportedResult=t;const e=this.hls.levels,s=e.indexOf(i);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${s} ${Xt(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${s} not smooth or powerEfficient: ${Xt(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${Xt(t)}`),s>-1&&e.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):i.supportedResult=Mt}if((S&&i.codecSet!==S||b&&i.videoRange!==b||u&&A>i.frameRate||!u&&A>0&&A<i.frameRate||null!=(P=i.supportedResult)&&null!=(P=P.decodingInfoResults)&&P.some(t=>!1===t.smooth))&&(!T||l!==k)){D.push(l);continue}const m=i.details,y=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||_;let I;I=u?o*t:a*t;const C=_&&r>=2*_&&0===n?i.averageBitrate:i.maxBitrate,x=this.getTimeToLoadFrag(w,I,C*y,void 0===m);if(I>=C&&(l===h||0===i.loadError&&0===i.fragmentError)&&(x<=w||!e(x)||E&&!this.bitrateTestDelay||x<d)){const t=this.forcedAutoLevel;return l===p||-1!==t&&t===p||(D.length&&this.trace(`Skipped level(s) ${D.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[D[0]].codecs}" ${g[D[0]].videoRange}; not compatible with "${S}" ${b}`),this.info(`switch candidate:${c}->${l} adjustedbw(${Math.round(I)})-bitrate=${Math.round(I-C)} ttfb:${w.toFixed(1)} avgDuration:${y.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${T} codecSet:${i.codecSet} videoRange:${i.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=l),l}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}},bufferController:class extends T{constructor(t,e){var i;super("buffer-controller",t.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=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:i}=this;t&&this.log("Media source opened"),e&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(a.MEDIA_ATTACHED,{media:e,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:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(i=k(t.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:t}=this;t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.BUFFER_EOS,this.onBufferEos,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.FRAG_PARSED,this.onFragParsed,this),t.on(a.FRAG_CHANGED,this.onFragChanged,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_EOS,this.onBufferEos,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.FRAG_PARSED,this.onFragParsed,this),t.off(a.FRAG_CHANGED,this.onFragChanged,this),t.off(a.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===e?v(i,s.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(i[e]=v({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,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(t,e){var i;let s=2;(e.audio&&!e.video||!e.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(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const s=k(this.appendSource);if(s){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(r),t)this._objectUrl=i.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&r instanceof e,gn(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,i;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(i=t.constructor)?void 0:i.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,s=e.tracks,r=s?Object.keys(s):null,n=r?r.length:0,o=()=>{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: ${Xt(i,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${Xt(s,(t,e)=>"initSegment"===t?void 0:e)}}`),!_(s,i)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,o=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return o-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${o}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${o} currentTime: ${r}`),this.onMediaDetaching(a.MEDIA_DETACHING,{}),this.onMediaAttaching(a.MEDIA_ATTACHING,e),void(t.currentTime=o))}this.transferData=void 0,r.forEach(t=>{const e=t,i=s[e];if(i){const t=i.buffer;if(t){const s=this.fragmentTracker,r=i.id;if(s.hasFragments(r)||s.hasParts(r)){const i=ze.getBuffered(t);s.detectEvictedFragments(e,i,r,null,!0)}const n=mn(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,i)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const i=!!e.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(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),r.removeSourceBuffer(e[i]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.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&&gn(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(a.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[mn(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new hn(this.tracks)}onBufferCodecs(t,e){var i;const s=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(t=>!s[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var i,r;const n=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:c}=n;let u=s[t];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[t],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[t]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:d,levelCodec:l,metadata:h,id:a});const v=_t(m,p),y=null==v?void 0:v.replace(cn,"$1");let E=_t(o,l);const T=null==(r=E)?void 0:r.replace(cn,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=kt(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=d,this.appendChangeType(t,d,E))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(i=e.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((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){const s=`${e};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),n.changeType(s),r.codec=i,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,s=i+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,c))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>s||null!=e&&e.buffer&&ze.isBuffered(e.buffer,s)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,c))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:r,frag:t},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,i){const{tracks:s}=this,{data:o,type:l,parent:d,frag:h,part:u,chunkMeta:f,offset:g}=i,m=f.buffering[l],{sn:p,cc:v}=h,y=self.performance.now();m.start=y;const E=h.stats.buffering,T=u?u.stats.buffering:null;0===E.start&&(E.start=y),T&&0===T.start&&(T.start=y);const S=s.audio;let b=!1;"audio"===l&&"audio/mpeg"===(null==S?void 0:S.container)&&(b=!this.lastMpegAudioChunk||1===f.id||this.lastMpegAudioChunk.sn!==f.sn,this.lastMpegAudioChunk=f);const A=s.video,L=null==A?void 0:A.buffer;if(L&&"initSegment"!==p){const t=u||h,e=this.blockedAudioAppend;if("audio"!==l||"main"===d||this.blockedAudioAppend||A.ending||A.ended){if("video"===l){const i=t.end;if(e){const t=e.frag.start;(i>t||i<this.lastVideoAppendEnd||ze.isBuffered(L,t))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const e=t.start+.05*t.duration,i=L.buffered,s=this.currentOp("video");i.length||s?!s&&!ze.isBuffered(L,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const I=(u||h).start,R={label:`append-${l}`,execute:()=>{var t;m.executeStart=self.performance.now();const i=null==(t=this.tracks[l])?void 0:t.buffer;i&&(b?this.updateTimestampOffset(i,I,.1,l,p,v):void 0!==g&&e(g)&&this.updateTimestampOffset(i,g,1e-6,l,p,v)),this.appendExecutor(o,l)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();m.executeEnd=m.end=t,0===E.first&&(E.first=t),T&&0===T.first&&(T.first=t);const e={};this.sourceBuffers.forEach(([t,i])=>{t&&(e[t]=ze.getBuffered(i))}),this.appendErrors[l]=0,"audio"===l||"video"===l?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(a.BUFFER_APPENDED,{type:l,frag:h,part:u,chunkMeta:f,parent:h.type,timeRanges:e})},onError:t=>{var e;const i={type:r.MEDIA_ERROR,parent:h.type,details:n.BUFFER_APPEND_ERROR,sourceBufferName:l,frag:h,part:u,chunkMeta:f,error:t,err:t,fatal:!1},s=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)i.details=n.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!s)i.errorAction=Re(!0);else if(t.name===un&&0===this.sourceBufferCount)i.errorAction=Re(!0);else{const t=++this.appendErrors[l];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${l}" sourceBuffer (${s||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}this.hls.trigger(a.ERROR,i)}};this.log(`queuing "${l}" append sn: ${p}${u?" p: "+u.index:""} of ${h.type===c?"level":"track"} ${h.level} cc: ${v}`),this.append(R,l,this.isPending(this.tracks[l]))}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(a.BUFFER_FLUSHED,{type:t})},onError:s=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,s)}}}onBufferFlushing(t,e){const{type:i,startOffset:s,endOffset:r}=e;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,s,r),t)})}onFragParsed(t,e){const{frag:i,part:s}=e,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[U]?r.push("audiovideo"):(n[N]&&r.push("audio"),n[B]&&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 t=self.performance.now();i.stats.buffering.end=t,s&&(s.stats.buffering.end=t);const e=s?s.stats:i.stats;this.hls.trigger(a.FRAG_BUFFERED,{frag:i,part:s,stats:e,id:i.type})},r).catch(t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(([t])=>{if(t){const i=this.tracks[t];e.type&&e.type!==t||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${t} buffer reached EOS`)))}});const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(a.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(a.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,i){if(i.details===n.BUFFER_APPEND_ERROR&&i.frag){var s;const t=null==(s=i.errorAction)?void 0:s.nextAutoLevel;e(t)&&t!==i.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:i,media:s}=this;if(!s||null===i)return;if(!this.sourceBufferCount)return;const r=t.config,n=s.currentTime,a=i.levelTargetDuration,o=i.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(e(o)&&o>=0){const t=Math.max(o,a),e=Math.floor(n/a)*a-t;this.flushBackBuffer(n,a,e)}const l=r.frontBufferFlushThreshold;if(e(l)&&l>0){const t=Math.max(r.maxBufferLength,l),e=Math.max(t,a),i=Math.floor(n/a)*a+e;this.flushFrontBuffer(n,a,i)}}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([t,e])=>{if(e){const r=ze.getBuffered(e);if(r.length>0&&i>r.start(0)){var s;this.hls.trigger(a.BACK_BUFFER_REACHED,{bufferEnd:i});const e=this.tracks[t];if(null!=(s=this.details)&&s.live)this.hls.trigger(a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([e,s])=>{if(s){const r=ze.getBuffered(s),n=r.length;if(n<2)return;const o=r.start(n-1),l=r.end(n-1);if(i>o||t>=o&&t<=l)return;this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:i,mediaSource:s}=this;if(!i||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const r=i.edge;if(i.live&&this.hls.config.liveDurationInfinity){if(i.fragments.length&&s.setLiveSeekableRange){const t=Math.max(0,i.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,r)}}return{duration:1/0}}const n=null==(t=this.overrides)?void 0:t.duration;if(n)return e(n)?{duration:n}:null;const a=this.media.duration;return r>(e(s.duration)?s.duration:0)&&r>a||!e(a)?{duration:r}:null}updateMediaSource({duration:t,start:i,end:s}){const r=this.mediaSource;this.media&&r&&"open"===r.readyState&&(r.duration!==t&&(e(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),r.duration=t),void 0!==i&&void 0!==s&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${i}-${s}.`),r.setLiveSeekableRange(i,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Xt(i)}`),this.tracksReady){var s;const t=null==(s=this.transferData)?void 0:s.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,i])=>{if(e){const s=this.tracks[e];t[e]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(a.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const o in t){const l=o,d=t[l];if(this.isPending(d)){const t=this.getTrackCodec(d,l),o=`${d.container};codecs=${t}`;d.codec=t,this.log(`creating sourceBuffer(${o})${this.currentOp(l)?" Queued":""} ${Xt(d)}`);try{const t=i.addSourceBuffer(o),s=mn(l),r=[l,t];e[s]=r,d.buffer=t}catch(t){var s;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(l),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[l],void this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:l,mimeType:o,parent:d.id})}this.trackSourceBuffer(l,d)}}this.bufferCreated()}getTrackCodec(t,e){const i=t.supplemental;let s=t.codec;i&&("video"===e||"audiovideo"===e)&&Tt(i,"video")&&(s=function(t,e){const i=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)Et(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(s,i));const r=_t(s,t.levelCodec);return r?"audio"===e.slice(0,5)?kt(r,this.appendSource):r:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const s=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:s,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(a.BUFFER_FLUSHED,{type:t})})}get mediaSrc(){var t,e;const i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const i=this.currentOp(t);i&&(i.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var i;const s=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,e),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:s,fatal:!1});const o=this.currentOp(t);o&&o.onError(s)}updateTimestampOffset(t,e,i,s,r,n){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,i,s){const{media:r,mediaSource:n}=this,a=this.tracks[t],o=null==a?void 0:a.buffer;if(!r||!n||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const l=e(r.duration)?r.duration:1/0,d=e(n.duration)?n.duration:1/0,h=Math.max(0,i),c=Math.min(s,l,d);c>h&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${h},${c}] from the ${t} SourceBuffer`),o.remove(h,c)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.tracks[e],s=null==i?void 0:i.buffer;if(!s)throw new fn(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,s=e.map(t=>this.appendBlocker(t));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;i&&!i.updating&&this.shiftAndExecuteNext(t)})}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,i){const s=this.tracks[t];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,t);s.listeners.push({event:e,listener:n}),r.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(t=>{i.removeEventListener(t.event,t.listener)}),e.listeners.length=0)}},capLevelController:pn,errorController:class extends T{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.ERROR,this.onError,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.ERROR,this.onError,this),t.off(a.ERROR,this.onErrorOut,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===c?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,i=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===i?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if(null!=(i=t.details)&&i.hasKey(e))return!0;const s=t.audioGroups;if(s){return this.hls.allAudioTracks.filter(t=>s.indexOf(t.groupId)>=0).some(t=>{var i;return null==(i=t.details)?void 0:i.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const s=this.hls,a=e.context;switch(e.details){case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case n.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=Re());case n.FRAG_GAP:case n.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ee);case n.LEVEL_EMPTY_ERROR:case n.LEVEL_PARSING_ERROR:{var o;const t=e.parent===c?e.level:s.loadLevel;e.details===n.LEVEL_EMPTY_ERROR&&null!=(o=e.context)&&null!=(o=o.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case n.LEVEL_LOAD_ERROR:case n.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==a?void 0:a.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level)));case n.AUDIO_TRACK_LOAD_ERROR:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.SUBTITLE_LOAD_ERROR:case n.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const t=s.loadLevelObj;if(t&&(a.type===d&&t.hasAudioGroup(a.groupId)||a.type===h&&t.hasSubtitleGroup(a.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=Ee,void(e.errorAction.flags=Ae)}return;case n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:Ee,flags:Le});case n.KEY_SYSTEM_SESSION_UPDATE_FAILED:case n.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case n.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:Ee,flags:Ie});case n.BUFFER_ADD_CODEC_ERROR:case n.REMUX_ALLOC_ERROR:case n.BUFFER_APPEND_ERROR:var l;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(l=e.level)?l:s.loadLevel);return;case n.INTERNAL_EXCEPTION:case n.BUFFER_APPENDING_ERROR:case n.BUFFER_FULL_ERROR:case n.LEVEL_SWITCH_ERROR:case n.BUFFER_STALLED_ERROR:case n.BUFFER_SEEK_OVER_HOLE:case n.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=Re())}e.type===r.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=Re())}getPlaylistRetryOrSwitchAction(t,e){const i=fe(this.hls.config.playlistLoadPolicy,t),s=this.playlistError++;if(pe(i,s,he(t),t.response))return{action:Se,flags:be,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(t,e);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=e.config,o=fe(ce(t)?a:r,t),l=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(s&&(t.details!==n.FRAG_GAP&&s.fragmentError++,!ue(t))){if(pe(o,l,he(t),t.response))return{action:Se,flags:be,retryConfig:o,retryCount:l}}const d=this.getLevelSwitchAction(t,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var r,a;const e=t.details;s.loadError++,e===n.BUFFER_APPEND_ERROR&&s.fragmentError++;let g=-1;const{levels:m,loadLevel:p,minAutoLevel:v,maxAutoLevel:y}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const E=null==(r=t.frag)?void 0:r.type,T=(E===u&&e===n.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===n.BUFFER_ADD_CODEC_ERROR||e===n.BUFFER_APPEND_ERROR))&&m.some(({audioCodec:t})=>s.audioCodec!==t),S="video"===t.sourceBufferName&&(e===n.BUFFER_ADD_CODEC_ERROR||e===n.BUFFER_APPEND_ERROR)&&m.some(({codecSet:t,audioCodec:e})=>s.codecSet!==t&&s.audioCodec===e),{type:b,groupId:A}=null!=(a=t.context)?a:{};for(let i=m.length;i--;){const r=(i+p)%m.length;if(r!==p&&r>=v&&r<=y&&0===m[r].loadError){var o,l;const i=m[r];if(e===n.FRAG_GAP&&E===c&&t.frag){const e=m[r].details;if(e){const i=ae(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(b===d&&i.hasAudioGroup(A)||b===h&&i.hasSubtitleGroup(A))continue;if(E===u&&null!=(o=s.audioGroups)&&o.some(t=>i.hasAudioGroup(t))||E===f&&null!=(l=s.subtitleGroups)&&l.some(t=>i.hasSubtitleGroup(t))||T&&s.audioCodec===i.audioCodec||S&&s.codecSet===i.codecSet||!T&&s.codecSet!==i.codecSet)continue}g=r;break}}if(g>-1&&i.loadLevel!==g)return t.levelRetry=!0,this.playlistError=0,{action:Ee,flags:be,nextAutoLevel:g}}return{action:Ee,flags:Ae}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case ye:break;case Ee:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===n.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:s}=i,r=i.nextAutoLevel;switch(s){case be:this.switchLevel(t,r);break;case Le:{const s=this.getVariantLevelIndex(t.frag),r=e.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){e.maxHdcpLevel=$t[$t.indexOf(n)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case Ie:{const e=t.decryptdata;if(e){const s=this.hls.levels,r=s.length;for(let i=r;i--;){var n,a;if(this.variantHasKey(s[i],e))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=t.frag)?void 0:a.type} fragment) ${D(e.keyId||[])}`),s[i].fragmentError++,s[i].loadError++,this.log(`Removing level ${i} with key error (${t.error})`),this.hls.removeLevel(i)}const o=t.frag;if(this.hls.levels.length<r)i.resolved=!0;else if(o&&o.type!==c){const t=o.decryptdata;t&&!e.matches(t)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(t,r)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===n.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Ct(t.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${s} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(s))}}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(a.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(a.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const t=s-this.lastTime,r=i-this.lastDroppedFrames,n=e-this.lastDecodedFrames,o=1e3*r/t,l=this.hls;if(l.trigger(a.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),o>0&&r>l.config.fpsDroppedMonitoringThreshold*n){let t=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=t)&&(t-=1,l.trigger(a.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:l.currentLevel}),l.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.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:Ii,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:Mo,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 ks{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",f),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=ps,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:s}=e;if(this.fragContextChanged(i)||(G(i)&&(this.fragPrevious=i),this.state=ps),!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let t=0;t<r.length;t++)if(a>=r[t].start&&a<=r[t].end){n=r[t];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(t,e){const{startOffset:i,endOffset:s}=e;if(0===i&&s!==Number.POSITIVE_INFINITY){const t=s-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{for(let i=0;i<e.length;)if(e[i].end<=t)e.shift();else{if(!(e[i].start<t))break;e[i].start=t,i++}}),this.fragmentTracker.removeFragmentsInRange(i,t,f)}}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===f&&(e.details===n.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ms&&(this.state=ps))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&on(this.levels,e)?this.levels=e.map(t=>new Yt(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new Yt(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,f),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.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!==ms&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:o}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${o}`);const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(n.live||null!=(i=l.details)&&i.live){if(n.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);const e=t.fragments[0];var h;if(l.details)d=this.alignPlaylists(n,l.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===d&&e&&(d=e.start,Ji(n,d));else n.hasProgramDateTime&&t.hasProgramDateTime?(cs(n,t),d=n.fragmentStart):e&&(d=e.start,Ji(n,d));t&&!this.startFragRequested&&this.setStartPosition(t,d)}if(l.details=n,this.levelLastLoaded=l,o===s&&(this.hls.trigger(a.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===ps)){ae(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,s=e.decryptdata,o=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&hi(s.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,ci(s.method)).catch(t=>{throw o.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(i=>{const s=performance.now();o.trigger(a.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:s}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=ps})}}doTick(){if(this.media){if(this.state===ps){const{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;if(this.waitForLive(i))return;const{config:s}=this,r=this.getLoadPosition(),n=ze.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 t=s.maxFragLookUpTolerance,e=a>c-t?0:t;u=ae(f,d,Math.max(d[0].start,a),e),!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)===ke&&(u=g),this.fragmentTracker.getState(u)===ke){const t=this.mapToInitFragWhenRequired(u);t&&this.loadFragment(t,i,a)}}}else this.state=ps}loadFragment(t,e,i){G(t)?super.loadFragment(t,e,i):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new Na(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends an{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Sa(this.media.textTracks);for(let i=0;i<e.length;i++)if("hidden"===e[i].mode)t=e[i];else if("showing"===e[i].mode){t=e[i];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.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(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const i=this.media;if(!i)return;const s=!!e.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;Sa(i.textTracks).forEach(t=>{Ea(t)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,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=e.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.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(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!i||-1!==i.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const i=te(e,t);if(i>-1)r=t[i];else{const t=te(e,this.tracks);r=this.tracks[t]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(a.SUBTITLE_TRACKS_UPDATED,n),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const r=e[s];if((!i||r.default)&&(i||t)&&(!t||ee(r,t)))return s}if(t){for(let i=0;i<e.length;i++){const s=e[i];if(ln(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(ln(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){if(dn(e[i],t))return i}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==h||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&ee(t,i))return i;const s=te(t,this.tracksInGroup);if(s>-1){const t=this.tracksInGroup[s];return this.setSubtitleTrack(s),t}if(i)return null;{const i=te(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,o=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(a.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Sa(t.textTracks),i=this.currentTrack;let s;if(i&&(s=e.filter(t=>dn(i,t))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach(t=>{"disabled"!==t.mode&&t!==s&&(t.mode="disabled")}),s){const t=this.subtitleDisplay?"showing":"hidden";s.mode!==t&&(s.mode=t)}}setSubtitleTrack(t){const i=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=i.length||!e(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,r=i[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t});const n=!!r.details&&!r.details.live;if(t===this.trackId&&r===s&&n)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:o,groupId:l="",name:d,type:h,url:c}=r;this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:d,type:h,url:c});const u=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(u)}},timelineController:class{constructor(t){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=t,this.config=t.config,this.Cues=t.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}},t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new wo(this,"textTrack1"),e=new wo(this,"textTrack2"),i=new wo(this,"textTrack3"),s=new wo(this,"textTrack4");this.cea608Parser1=new to(1,t,e),this.cea608Parser2=new to(3,i,s)}addCues(t,e,i,s,r){let n=!1;for(let t=r.length;t--;){const s=r[t],a=Co(s[0],s[1],e,i);if(a>=0&&(s[0]=Math.min(s[0],e),s[1]=Math.max(s[1],i),n=!0,a/(i-e)>.5))return}if(n||r.push([e,i]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,i,s)}else{const r=this.Cues.newCue(null,e,i,s);this.hls.trigger(a.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r,trackId:n}){const{unparsedVttFrags:o}=this;i===c&&(this.initPTS[e.cc]={baseTime:s,timescale:r,trackId:n}),o.length&&(this.unparsedVttFrags=[],o.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(a.FRAG_LOADED,t):this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(Po(r,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:s}=this,{label:r,languageCode:n}=e[t],a=this.getExistingTrack(r,n);if(a)i[t]=a,Ea(i[t]),va(i[t],s);else{const e=this.createTextTrack("captions",r,n);e&&(e[t]=!0,i[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(t,e,i){const s=this.media;if(s)return s.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(t=>{Ea(s[t]),delete s[t]}),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:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)Ea(e[t])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],s=i.some(t=>t.textCodec===yo);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(on(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const t=this.media,e=t?Sa(t.textTracks):null;if(this.tracks.forEach((t,i)=>{let s;if(e){let i=null;for(let s=0;s<e.length;s++)if(e[s]&&Po(e[s],t)){i=e[s],e[s]=null;break}i&&(s=i)}if(s)Ea(s);else{const e=Do(t);s=this.createTextTrack(e,t.name,t.lang),s&&(s.mode="disabled")}s&&this.textTracks.push(s)}),null!=e&&e.length){const t=e.filter(t=>null!==t).map(t=>t.label);t.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const i=`textTrack${e[1]}`,s=this.captionsProperties[i];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===c){var i,s;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(s=e.part)?void 0:s.index)?i:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:s}=e;if(i.type===f)if(s.byteLength){const t=i.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=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),t&&t.textCodec===yo?this._parseIMSC1(i,s):this._parseVTTs(e)}}else this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;bo(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),i.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{i.logger.log(`Failed to parse IMSC1: ${e}`),i.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[i.cc]&&-1===o)return void n.push(t);const l=this.hls;vo(null!=(e=i.initSegment)&&e.data?dt(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,t=>{this._appendCues(t,i.level),l.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(i,s),l.logger.log(`Failed to parse VTT cue: ${e}`),r&&o>i.cc||l.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})})}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||bo(e,this.initPTS[t.cc],()=>{i.textCodec=yo,this._parseIMSC1(t,e)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach(t=>ya(i,t))}else{const s=this.tracks[e];if(!s)return;const r=s.default?"default":"subtitles"+e;i.trigger(a.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===f&&this.onFragLoaded(a.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=e;if(i.type!==c||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<s.length;t++){const e=s[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(e);this.cea608Parser1.addData(s[t].pts,i[0]),this.cea608Parser2.addData(s[t].pts,i[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!r||"video"===r){const{captionsTracks:t}=this;Object.keys(t).forEach(s=>Ta(t[s],e,i))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==s){const{textTracks:t}=this;Object.keys(t).forEach(i=>Ta(t[i],e,s))}}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let s=2;for(let r=0;r<i;r++){const i=t[s++],r=127&t[s++],n=127&t[s++];if(0===r&&0===n)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},audioStreamController:class extends ks{constructor(t,e,i){super(t,e,i,"audio-stream-controller",u),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:t}=this;t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r,trackId:n}){if(i===c){const t=e.cc,i=this.fragCurrent;if(this.initPTS[t]={baseTime:s,timescale:r,trackId:n},this.log(`InitPTS for cc: ${t} found from main: ${s/r} (${s}/${r}) trackId: ${n}`),this.mainAnchor=e,this.state===Is){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==t)&&this.syncWithAnchor(e,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==t?(i.abortRequests(),this.syncWithAnchor(e,i)):this.state===ps&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const s=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==s?void 0:s.cc)===e.cc)return;const r=(s||t).cc,n=de(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===ps&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=ms);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=ps):this.state=Ts,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case ps:this.doTickIdle();break;case Ts:{const{levels:t,trackId:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=Is}break}case Es:this.checkRetryDate();break;case Is:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:s,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=ys;const t={frag:e,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=ps}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:i,media:s,trackId:r}=this,n=e.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[r])return;const o=i[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l))return this.state=Ts,void(this.startFragRequested=!1);const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,N,u));const h=this.getFwdBufferInfo(d,u);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,l))return e.trigger(a.BUFFER_EOS,{type:"audio"}),void(this.state=As);const f=h.len,g=e.maxBufferLength,m=l.fragments,p=m[0].start,v=this.getLoadPosition(),y=this.flushing?v:h.end;if(this.switchingTrack&&s){const t=v;l.PTSKnown&&t<p&&(h.end>p||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=p+.05)}if(f>=g&&!this.switchingTrack&&y<m[m.length-1].start)return;let E=this.getNextFragment(y,l);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,l,h,c,g)),!E)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(h,g,E))return;let T=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&G(E)&&!E.endList&&(!l.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===De&&(this.mainFragLoading=T=null),T&&G(T))){if(E.start>T.end){const t=this.fragmentTracker.getFragAtPos(y,c);t&&t.end>T.end&&(T=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(E.start>T.end)return}this.loadFragment(E,o,y)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Yt(t))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==ms&&(this.setInterval(100),this.state=ps,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(a.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:s}=this,{details:r,id:n,groupId:o,track:l}=e;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${l.name}" of "${o}"`);const d=this.mainDetails;if(!d||r.endCC>d.endCC||d.expired)return this.cachedTrackLoadedData=e,void(this.state!==ms&&(this.state=Ts));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=s[n];let c=0;if(r.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;if(h.details)c=this.alignPlaylists(r,h.details,null==(u=this.levelLastLoaded)?void 0:u.details);r.alignedSliding||(hs(r,d),r.alignedSliding||cs(r,d),c=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(a.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==Ts||this.waitForCdnTuneIn(r)||(this.state=ps),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{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 nn(this.hls,u,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],g=null==(e=i.initSegment)?void 0:e.data;if(void 0!==f){const t=!1,e=s?s.index:-1,n=-1!==e,a=new Ye(i.level,i.sn,i.stats.chunkCount,r.byteLength,e,n);c.push(r,g,h,"",i,s,d.totalduration,t,a,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new ws,complete:!1};t.push(new Uint8Array(r)),this.state!==ms&&(this.state=Is)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===c&&G(e.frag)&&(this.mainFragLoading=e,this.state===ps&&this.tick())}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type===u)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(G(i)){this.fragPrevious=i;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(a.AUDIO_TRACK_SWITCHED,E({},t)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==c||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var i;if(e.fatal)this.state=Ls;else switch(e.details){case n.FRAG_GAP:case n.FRAG_PARSING_ERROR:case n.FRAG_DECRYPT_ERROR:case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(u,e);break;case n.AUDIO_TRACK_LOAD_ERROR:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ts||(null==(i=e.context)?void 0:i.type)!==d||(this.state=ps);break;case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case n.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case n.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==B&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==B){this.flushing=!1,this.bufferFlushed=!0,this.state===As&&(this.state=ps);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,u),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,o=this.getCurrentContext(n);if(!o)return void this.resetWhenMissingContext(n);const{frag:l,part:d,level:h}=o,{details:c}=h,{audio:u,text:f,id3:g,initSegment:m}=r;if(!this.fragContextChanged(l)&&c){if(this.state=Ss,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){const t=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(h,m.tracks,t,n),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:m.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=u;d&&(d.elementaryStreams[N]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(N,t,e,i,s),this.bufferFragmentData(u,l,d,n)}if(null!=g&&null!=(e=g.samples)&&e.length){const t=v({id:i,frag:l,details:c},g);s.trigger(a.FRAG_PARSING_METADATA,t)}if(f){const t=v({id:i,frag:l,details:c},f);s.trigger(a.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(l)}_bufferInitSegment(t,e,i,s){if(this.state!==Ss)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=u;const n=t.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(a.BUFFER_CODECS,e);const o=r.initSegment;if(null!=o&&o.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(a.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||s===ke||s===we)if(G(t))if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Is;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&cs(e.details,i)}else super.loadFragment(t,e,i);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;ee({name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},t,ie)||(re(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(a.AUDIO_TRACK_SWITCHED,E({},t))}},audioTrackController:class extends an{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.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(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,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=e.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,s=this.groupIds;let o=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!i||-1!==i.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!o&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!o&&e){const i=te(e,t,ie);if(i>-1)o=t[i];else{const t=te(e,this.tracks);o=this.tracks[t]}}let s=this.findTrackId(o);-1===s&&o&&(s=this.findTrackId(null));const d={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(a.AUDIO_TRACKS_UPDATED,d);const h=this.trackId;if(-1!==s&&-1===h)this.setAudioTrack(s);else if(t.length&&-1===h){var l;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(l=this.groupIds)?void 0:l.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==d||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&ee(t,s,ie))return s;const r=te(t,this.tracksInGroup,ie);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(s){let s=e.loadLevel;-1===s&&(s=e.firstAutoLevel);const r=function(t,e,i,s,r){const n=e[s],a=e.reduce((t,e,i)=>{const s=e.uri;return(t[s]||(t[s]=[])).push(i),t},{})[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=se(e,s,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==d)return!1;const s=e.audioGroups,n=i.filter(t=>!s||-1!==s.indexOf(t.groupId));return te(t,n,r)>-1});return h>-1?h:se(e,s,e=>{const s=e.audioGroups,n=i.filter(t=>!s||-1!==s.indexOf(t.groupId));return te(t,n,r)>-1})}(t,e.levels,i,s,ie);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=te(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t],r=s.details&&!s.details.live;if(t===this.trackId&&s===i&&r)return;if(this.log(`Switching to audio-track ${t} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=t,this.currentTrack=s,this.hls.trigger(a.AUDIO_TRACK_SWITCHING,E({},s)),r)return;const n=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if((!this.selectDefaultTrack||s.default)&&(!t||ee(t,s,ie)))return i}if(t){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(ee({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],ie))return t}for(let i=0;i<e.length;i++){const s=e[i];if(ln(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(ln(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&re(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,o=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(a.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}},emeController:ua,cmcdController:class{constructor(t){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=t=>{try{this.apply(t,{ot:vn.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:e,part:i}=t,s=this.hls.levels[e.level],r=this.getObjectType(e),n={d:1e3*(i||e).duration,ot:r};r!==vn.VIDEO&&r!==vn.AUDIO&&r!=vn.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(e);null!=a&&a.url&&a.url!==e.url&&(n.nor=a.url),this.apply(t,n)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;null!=i&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||t.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHED,this.onMediaDetached,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHED,this.onMediaDetached,this),t.off(a.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(t,e){this.media=e.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(t,e){var i,s;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=e.tracks.video)?void 0:s.buffer}createData(){var t;return{v:1,sf:yn.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){v(e,this.createData());const i=e.ot===vn.INIT||e.ot===vn.VIDEO||e.ot===vn.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:s}=this;s&&(e=Object.keys(e).reduce((t,i)=>(s.includes(i)&&(t[i]=e[i]),t),{}));const r={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),aa(t.headers,e,r)):t.url=da(t.url,e,r)}getNextFrag(t){var e;const i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){const e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;const{index:i,fragment:s}=t,r=null==(e=this.hls.levels[s.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=s;for(let e=r.length-1;e>=0;e--){const s=r[e];if(s.index===i&&s.fragment.sn===t)return r[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?vn.TIMED_TEXT:"initSegment"===t.sn?vn.INIT:"audio"===e?vn.AUDIO:"main"===e?this.hls.audioTracks.length?vn.VIDEO:vn.MUXED:void 0}getTopBandwidth(t){let e,i=0;const s=this.hls;if(t===vn.AUDIO)e=s.audioTracks;else{const t=s.maxAutoLevel,i=t>-1?t+1:s.levels.length;e=s.levels.slice(0,i)}return e.forEach(t=>{t.bitrate>i&&(i=t.bitrate)}),i>0?i:NaN}getBufferLength(t){const e=this.media,i=t===vn.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!e)return NaN;return 1e3*ze.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}},contentSteeringController:class extends T{constructor(t){super("content-steering",t.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=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}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(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}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(t,e){const{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===Ee&&i.flags===Ae){const t=this.levels;let s=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:i,pathwayId:s,type:n}=e.context;i&&t?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&t&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r),e.details!==n.BUFFER_APPEND_ERROR||e.fatal?i.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${Xt(s)} penalized: ${Xt(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(t=>{s-i[t]>3e5&&delete i[t]});for(let s=0;s<t.length;s++){const r=t[s];if(r in i)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,o=this.hls.levels[n];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,rs(e),this.hls.trigger(a.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];o&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(e===d&&s[i].hasAudioGroup(t)||e===h&&s[i].hasSubtitleGroup(t))return s[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new si(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(i[e.AUDIO]=n,e.AUDIO=n),o&&(s[e.SUBTITLES]=o,e.SUBTITLES=o);const l=ca(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Yt({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${r}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${r}`);return d});e.push(...o),ha(this.audioTracks,i,a,r),ha(this.subtitleTracks,s,a,r)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let s;this.loader&&this.loader.destroy(),this.loader=new i(e);try{s=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==s.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+t)}const r={responseType:"json",url:s.href},n=e.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(t,e,i,r)=>{this.log(`Loaded steering manifest: "${s}"`);const n=t.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":o,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":d}=n;if(o)try{this.uri=new self.URL(o,s).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`)}this.scheduleRefresh(this.uri||i.url),l&&this.clonePathways(l);const h={steeringManifest:n,url:s.toString()};this.hls.trigger(a.STEERING_MANIFEST_LOADED,h),d&&this.updatePathwayPriority(d)},onError:(t,e,i,s)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,d)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}},interstitialsController:class extends T{constructor(t,e){super("interstitials",t.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 t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const i=e<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=t,this.bufferedPos=t;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&t<s.start||t>=s.end){var r;const e=this.findItemIndex(s);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(s)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(s)){const e=s.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(i&&t<a||t>=a+o)&&(null!=(l=s.event)&&l.appendInPlace&&(this.clearAssetPlayers(s.event,s),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const i=this.playingAsset;if(!i)return;t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{const i=this.schedule;if(!i)return;const s=this.playingItem,r=i.events||[],n=i.items||[],o=i.durations,l=t.map(t=>t.identifier),d=!(!r.length&&!l.length);(d||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(t=>xa(t))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let h=null,c=null;s&&(h=this.updateItem(s,this.timelinePos),this.itemsMatch(s,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const u=this.bufferingItem;if(u&&(c=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,c)?this.bufferingItem=c:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(s){Math.abs(i)>Aa&&this.warn(`${s} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}}),d||e){if(this.hls.trigger(a.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:o,removedIds:l}),this.isInterstitial(s)&&l.includes(s.event.identifier))return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);s&&this.trimInPlace(h,s),u&&c!==h&&this.trimInPlace(c,u),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new Ma(t),this.schedule=new Ca(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(a.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(a.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(a.MEDIA_ENDED,this.onMediaEnded,this),t.on(a.ERROR,this.onError,this),t.on(a.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(a.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(a.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(a.MEDIA_ENDED,this.onMediaEnded,this),t.off(a.ERROR,this.onError,this),t.off(a.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.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 t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){fs(t,"play",this.onPlay),fs(t,"pause",this.onPause),fs(t,"seeking",this.onSeeking),fs(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;us(i,"seeking",this.onSeeking),us(i,"timeupdate",this.onTimeupdate),us(i,"play",this.onPlay),us(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,s=(e,s,n,a,o)=>{if(e){let l=e[s].start;const d=e.event;if(d){if("playout"===s||d.timelineOccupancy!==La.Point){const t=i(n);(null==t?void 0:t.interstitial)===d&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?r():t[a])-e.start}return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var i,s;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(s=t.schedule)?void 0:s.durations[e])||0},a=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,d=t.schedule.findItemIndexAtTime(e,r),h=null==(a=t.schedule.items)?void 0:a[d],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,h);if(l&&(f||g)){const n=i(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const i="primary"===r?a.currentTime:s(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-i,d=(f?i:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(h){let i=e;if("primary"!==r){const t=e-h[r].start;i=h.start+t}const s=!t.isInterstitial(h);if(t.isInterstitial(l)&&!l.event.appendInPlace||!s&&!h.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(d>n){const e=t.schedule.findJumpRestrictedIndex(n+1,d);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(s)t.timelinePos=i,t.checkBuffer();else{const t=h.event.assetList,i=e-(h[r]||h).start;for(let e=t.length;e--;){const s=t[e];if(s.duration&&i>=s.startOffset&&i<s.startOffset+s.duration){a=e;break}}}t.setSchedulePosition(d,a)}}else{const e=t.media||(f?null==c?void 0:c.media:null);e&&(e.currentTime=i)}}},o=()=>{const i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;const s=e();return t.isInterstitial(s)?s:null},l={get bufferedEnd(){const i=e(),r=t.bufferingItem;var n;return r&&r===i&&(s(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),i=t.effectivePlayingItem;return i&&i===e?s(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){const i=o(),s=t.effectivePlayingItem;s&&s===i&&a(e+s.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const i=null==(e=o())?void 0:e.event.assetList;return i?i.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const i=null==(e=o())?void 0:e.event;return i&&t.effectivePlayingAsset?i.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){var e;return((e,i)=>{var s;if(0!==e&&"primary"!==i&&null!=(s=t.schedule)&&s.length){var r;const s=t.schedule.findItemIndexAtTime(e),n=null==(r=t.schedule.items)?void 0:r[s];if(n)return e+(n[i].start-n.start)}return e})((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){const s=t.findItemIndex(e);if(i.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(i,s,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,i;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let r=this.media;!r&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(r=this.primaryMedia);const n=null==(i=r)?void 0:i.currentTime;return void 0!==n&&e(n)?n:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,s=t.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&s)return void(this.detachedData={media:s});const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Xt(i)}`),this.detachedData=i}else e&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(t,e){var i,s;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.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 t=this.getBufferingPlayer();t?(r=t.transferMedia(),d=`${t}`):d="detached MediaSource"}else d="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Xt(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const h=r&&"mediaSource"in r&&"closed"!==(null==(s=r.mediaSource)?void 0:s.readyState),c=h&&r?r:e;this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`);const u=this.schedule;if(c===r&&u){const e=a&&t.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events;if(!e||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.timelinePos=i,0===e.length)this.setSchedulePosition(0);else if(e[0].cue.pre){this.log(Fa("checkStart (preroll)",i));const s=t.findEventIndex(e[0].identifier);this.setSchedulePosition(s)}else if(i>=0||!this.primaryLive){this.log(Fa("checkStart",i));const e=this.timelinePos=i>0?i:0,s=t.findItemIndexAtTime(e);this.setSchedulePosition(s)}else 0===this.hls.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(s&&!this.playingItem){this.log(Fa("checkStart (playing item)",s.start));const e=t.findItemIndex(s);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,s=i.findAssetIndex(e),r=wa(i,s);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const e=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(t)+1];e&&this.bufferedToItem(e)}}else this.bufferedToEvent(t,r)}advanceAfterAssetEnded(t,e,i){const s=wa(t,i);if(t.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=e+1;if(s>=i.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos<r&&(this.log(Fa("advanceAfterAssetEnded",r)),this.timelinePos=r,t.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(s)}}}else{if(t.appendInPlace){const e=t.assetList[s];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,s)}}setScheduleToAssetAtTime(t,e){const i=this.schedule;if(!i)return;const s=e.parentIdentifier,r=i.getEvent(s);if(r){const e=i.findEventIndex(s),n=i.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,n-1)}}setSchedulePosition(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const r=t>=0?s[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?xa(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,h=this.playingAsset,c=null==h?void 0:h.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(n,r)||void 0!==e&&c!==i.assetList[e].identifier)){var l;const e=i.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${i.assetList.length} ${Da(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(a.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:e,event:i,schedule:s.slice(0),scheduleIndex:t,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(c,r),!u.media||null!=(l=this.detachedData)&&l.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${xa(n)}`),i.hasPlayed=!0,this.hls.trigger(a.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:t}),i.cue.once)){var d;this.updateSchedule();const t=null==(d=this.schedule)?void 0:d.items;if(r&&t){const i=this.findItemIndex(r);this.advanceSchedule(i,t,e,n,o)}return}}this.advanceSchedule(t,s,e,n,o)}advanceSchedule(t,e,i,s,r){const n=this.schedule;if(!n)return;const o=e[t]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(e=>{const i=e.interstitial,s=n.findEventIndex(i.identifier);(s<t||s>t+1)&&this.clearInterstitial(i,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const r=o.event;if(void 0===i){const e=wa(r,(i=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(r,t,i);i=e}const d=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(r,i);if(this.eventItemsMatch(o,d||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${xa(o)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(a.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!l)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=o;const c=r.assetList[i];if(!c)return void this.advanceAfterAssetEnded(r,t,i||0);if(h||(h=this.getAssetPlayer(c.identifier)),null===h||h.destroyed){const t=r.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${r}`),h=this.createAssetPlayer(r,c,i),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(h,i,e,t,l),this.shouldPlay&&Oa(h.media)}else o?(this.resumePrimary(o,t,s),this.shouldPlay&&Oa(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 t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,i){var s,r;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${xa(t)}`),null==(s=this.detachedData)||!s.mediaSource){let i=this.timelinePos;(i<t.start||i>=t.end)&&(i=this.getPrimaryResumption(t,e),this.log(Fa("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,t)}if(!i)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${xa(t)}`),this.hls.trigger(a.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const i=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(i<t.fragmentStart||i>t.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return ze.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):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(t,i)),i||(this.log(Fa("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs(((null==(i=s.mainForwardBufferInfo)?void 0:i.start)||s.media.currentTime)-t)>.5?s.startLoad(t,e):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.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(a.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(a.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const i=this.hls.levels[e.level];if(!i.details)return;const s=E(E({},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(t,e){const i=this.hls.audioTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=E(E({},this.altSelection),{},{audio:i}));const r=E(E({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=E(E({},this.altSelection),{},{subtitles:i}));const r=E(E({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(t,e){const i=Jt(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i)))}onSubtitleTrackSwitch(t,e){const i=Jt(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(i)))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const s=e[t];if(s.cue.post){var i;const t=this.schedule.findEventIndex(s.identifier),e=null==(i=this.schedule.items)?void 0:i[t];this.isInterstitial(e)&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(t&&s){return s[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)});const i=t.end+.25,s=ze.bufferInfo(this.primaryMedia,i,0);if(s.end>i||(s.nextStart||0)>i){this.log(`trim buffered interstitial ${xa(t)} (was ${xa(e)})`);const s=!0;this.attachPrimary(i,null,s),this.flushFrontBuffer(i)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e;const i=this.mediaSelection;i&&(null==(e=this.schedule)||e.updateSchedule(i,[],t))}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const s=ze.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=s.len<1),this.updateBufferedPos(s.end,i,t)}updateBufferedPos(t,e,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!s)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(r),s=Math.min(i+1,e.length-1),n=e[s];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=s),this.isInterstitial(r)){const t=r.event;if(s-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>i&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.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(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){const{items:s,events:r}=i;if(!s||!r)return e;const n=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const l=o?o.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${xa(t)}`+(e?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,i)=>{const s=this.getAssetPlayer(t.identifier);s&&(i===e&&s.loadSource(),s.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger(a.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;const e=this.detachedData;if(e)if(e.mediaSource){const e=!0;this.attachPrimary(t.start,t,e)}else this.preloadPrimary(t);else this.preloadPrimary(t)}}preloadPrimary(t){const e=this.findItemIndex(t),i=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(i)}bufferedToEvent(t,e){const i=t.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){const t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const i=t.assetUrl,s=t.assetList.length,r=0===s&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart;if(t.appendInPlace){var a;const e=this.playingItem;this.isInterstitial(e)||(null==e||null==(a=e.nextEvent)?void 0:a.identifier)!==t.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&&!t.cue.pre&&!t.cue.post){const t=o-r;t>0&&(n=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:s} ${t}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(t,0,0,r,t.duration,i);const l=this.assetListLoader.loadAssetList(t,n);l&&(t.assetListLoader=l)}else if(!n&&s){for(let i=e;i<s;i++){const e=t.assetList[i],s=this.getAssetPlayerQueueIndex(e.identifier);-1!==s&&!this.playerQueue[s].destroyed||e.error||this.createAssetPlayer(t,e,i)}const i=t.assetList[e];if(i){const t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach(e=>{this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null}createAsset(t,e,i,s,r,n){const a={parentIdentifier:t.identifier,identifier:Ia(t,n,e),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,i){const s=this.hls,o=s.userConfig;let l=o.videoPreference;const d=s.loadLevelObj||s.levels[s.currentLevel];(l||d)&&(l=v({},l),d.videoCodec&&(l.videoCodec=d.videoCodec),d.videoRange&&(l.allowedVideoRanges=[d.videoRange]));const h=s.audioTracks[s.audioTrack],c=s.subtitleTracks[s.subtitleTrack];let u=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>1){const i=e.duration;i&&t<i&&(u=t)}}const f=e.identifier,g=E(E({},o),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:f,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:l,audioPreference:h||o.audioPreference,subtitlePreference:c||o.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(g.timelineOffset=e.timelineStart));const m=g.cmcd;null!=m&&m.sessionId&&m.contentId&&(g.cmcd=v({},m,{contentId:ba(e.uri)})),this.getAssetPlayer(f)&&this.warn(`Duplicate date range identifier ${t} and asset ${f}`);const p=new Pa(this.HlsPlayerClass,g,t,e);this.playerQueue.push(p),t.assetList[i]=e;let y=!0;const T=s=>{if(s.live){var a;const e=new Error(`Interstitials MUST be VOD assets ${t}`),s={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},o=(null==(a=this.schedule)?void 0:a.findEventIndex(t.identifier))||-1;return void this.handleAssetItemError(s,t,o,i,e.message)}const o=s.edge-s.fragmentStart,l=e.duration;(y||null===l||o>l)&&(y=!1,this.log(`Interstitial asset "${f}" duration change ${l} > ${o}`),e.duration=o,this.updateSchedule())};p.on(a.LEVEL_UPDATED,(t,{details:e})=>T(e)),p.on(a.LEVEL_PTS_UPDATED,(t,{details:e})=>T(e)),p.on(a.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const S=(t,e)=>{const i=this.getAssetPlayer(f);if(i&&e.tracks){i.off(a.BUFFER_CODECS,S),i.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};p.on(a.BUFFER_CODECS,S);p.on(a.BUFFERED_TO_END,()=>{var i;const s=this.getAssetPlayer(f);if(this.log(`buffered to end of asset ${s}`),!s||!this.schedule)return;const r=this.schedule.findEventIndex(t.identifier),n=null==(i=this.schedule.items)?void 0:i[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,e)});const b=e=>()=>{if(!this.getAssetPlayer(f)||!this.schedule)return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return p.once(a.MEDIA_ENDED,b(i)),p.once(a.PLAYOUT_LIMIT_REACHED,b(1/0)),p.on(a.ERROR,(e,s)=>{if(!this.schedule)return;const r=this.getAssetPlayer(f);if(s.details===n.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(s,t,this.schedule.findEventIndex(t.identifier),i,`Asset player error ${s.error} ${t}`)}),p.on(a.DESTROYING,()=>{if(!this.getAssetPlayer(f)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${f}`),s={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(s,t,this.schedule.findEventIndex(t.identifier),i,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Da(e)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:p}),p}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){const t=this.playerQueue[i];this.log(`clear ${t} toSegment: ${e?xa(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(i,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,s,r){const{interstitial:n,assetItem:o,assetId:l}=t,d=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,h&&h.identifier===l||(h&&(this.clearAssetPlayer(h.identifier,i[s]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${d} ${Da(o)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:e,event:n,schedule:i.slice(0),scheduleIndex:s,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var i,s;if(!this.schedule)return;const{interstitial:a,assetItem:o}=t,l=this.schedule.findEventIndex(a.identifier),d=null==(i=this.schedule.items)?void 0:i[l];if(!d)return;t.loadSource(),this.setBufferingItem(d),this.bufferingAsset=o;const h=this.getBufferingPlayer();if(h===t)return;const c=a.appendInPlace;if(c&&!1===(null==h?void 0:h.interstitial.appendInPlace))return;const u=(null==h?void 0:h.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(c&&o!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(u&&!_(u,t.tracks)){const e=new Error(`Asset ${Da(o)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),i={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},s=a.findAssetIndex(o);return void this.handleAssetItemError(i,a,l,s,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,i=this.primaryMedia;if(!e||!i)return;const s=i.currentTime,r=e.findAssetIndex(t,s),n=t.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} ${t} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,r)}}}}advanceInPlace(t){const e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)}handleAssetItemError(t,e,i,s,r){if(t.details===n.BUFFER_STALLED_ERROR)return;const o=e.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o?Da(o):o} ${t.error}`),!this.schedule)return;const l=(null==o?void 0:o.identifier)||"",d=this.getAssetPlayerQueueIndex(l),h=this.playerQueue[d]||null,c=this.schedule.items,u=v({},t,{fatal:!1,errorAction:Re(!0),asset:o,assetListIndex:s,event:e,schedule:c,scheduleIndex:i,player:h});if(this.hls.trigger(a.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;const f=this.playingAsset,g=this.bufferingAsset,m=new Error(r);if(o&&(this.clearAssetPlayer(l,null),o.error=m),e.assetList.some(t=>!t.error))for(let t=s;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=m;this.updateSchedule(!0),e.error?this.primaryFallback(e):f&&f.identifier===l?this.advanceAfterAssetEnded(e,i,s):g&&g.identifier===l&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem;let s=this.timelinePos;if(i){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${s} playing: ${xa(i)} error: ${t.error}`),-1===s&&(s=this.hls.startPosition);const r=this.updateItem(i,s);this.itemsMatch(i,r)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===s)return void this.checkStart();if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(r)}onAssetListLoaded(t,e){var i,s;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(r,e,d,o+d,i,t.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 t=this.schedule.findEventIndex(n),e=null==(f=this.schedule.items)?void 0:f[t];if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===n){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(u.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case n.ASSET_LIST_PARSING_ERROR:case n.ASSET_LIST_LOAD_ERROR:case n.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case n.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function Ko(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Ko):Object.keys(t).reduce((e,i)=>(e[i]=Ko(t[i]),e),{}):t}function Vo(t,e){const i=t.loader;if(i!==Fo&&i!==$o)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=Fo,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Ho extends qe{constructor(t,e){super("gap-controller",t.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 t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const i=this.media=e.media;us(i,"playing",this.onMediaPlaying),us(i,"waiting",this.onMediaWaiting),us(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(fs(i,"playing",this.onMediaPlaying),fs(i,"waiting",this.onMediaWaiting),fs(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){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:o}=n,l=this.seeking&&!o,d=!this.seeking&&o,h=n.paused&&!o||n.ended||0===n.playbackRate;if(this.seeking=o,t!==e)return e&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(d||l)return void(l&&this.stallResolved(t));if(h)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1})));if(!ze.getBuffered(n).length)return void(this.nudgeRetry=0);const c=ze.bufferInfo(n,t,0),u=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const e=jo(this.hls.inFlightFragments,t),i=c.len>2,s=!u||e||u-t>2&&!f.getPartialFragment(t);if(i||s)return;this.moved=!1}const g=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(c.len>0)&&!u)return;const e=Math.max(u,c.start||0)-t,i=!(null==g||!g.live)?2*g.targetduration:2,s=Yo(t,f);if(e>0&&(e<=i||s))return void(n.paused||this._trySkipBufferHole(s))}const m=r.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting;let y=this.stalled;if(null===y){if(!(v>0&&p-v<m))return void(this.stalled=p);y=this.stalled=v}const E=p-y;if(!o&&(E>=m||v)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==g||!g.live)&&Math.abs(t-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(a.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}const S=ze.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(S,E,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(a.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){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&&t>s.end(0)){const i=ze.bufferedInfo(ze.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=ze.timeRangesToArray(s),o=ze.bufferedInfo(i,e,0).bufferedIndex;if(o>-1&&o<i.length-1){const e=ze.bufferedInfo(i,t,0).bufferedIndex,s=i[o].end,l=i[o+1].start;if((-1===e||e>o)&&l-s<1&&t-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${s} -> ${l} buffered index: ${e}`);this.warn(i.message),this.media.currentTime+=1e-6;let o=Yo(t,this.fragmentTracker);o&&"fragment"in o?o=o.fragment:o||(o=void 0);const d=ze.bufferInfo(this.media,t,0);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:o,buffer:d.len,bufferInfo:d})}}}}}_tryFixBufferStall(t,e,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=Yo(i,n);if(d||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=t.buffered,c=this.adjacentTraversal(t,i);(h&&h.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||c))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,s=t.nextStart;if(i&&s){const t=i.getFragAtPos(e,c),r=i.getFragAtPos(s,c);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:s,stalled:o}=this;if(!s&&null!==o&&i&&e){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Xt(t)})`);this.warn(s.message),e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:t.len,bufferInfo:t,stalled:{start:o}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:i,media:s}=this,o=null==(e=this.hls)?void 0:e.config;if(!s||!i||!o)return 0;const l=s.currentTime,d=ze.bufferInfo(s,l,0),h=l<d.start?d.start:d.nextStart;if(h&&this.hls){const e=d.len<=o.maxBufferHole,f=d.len>0&&d.len<1&&s.readyState<3,g=h-l;if(g>0&&(e||f)){if(g>o.maxBufferHole){let e=!1;if(0===l){const t=i.getAppendedFrag(0,c);t&&h<t.end&&(e=!0)}if(!e&&t){var u;if(null==(u=this.hls.loadLevelObj)||!u.details)return 0;if(jo(this.hls.inFlightFragments,h))return 0;let e=!1,s=t.end;for(;s<h;){const t=Yo(s,i);if(!t){e=!0;break}s+=t.duration}if(e)return 0}}const e=Math.max(h+.05,l+.1);if(this.warn(`skipping hole, adjusting currentTime from ${l} to ${e}`),this.moved=!0,s.currentTime=e,null==t||!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${l} to ${e}`),s={type:r.MEDIA_ERROR,details:n.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:d.len,bufferInfo:d};t&&("fragment"in t?s.part=t:s.frag=t),this.hls.trigger(a.ERROR,s)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:s}=this,o=null==e?void 0:e.config;if(!i||!o)return 0;const l=i.currentTime;if(this.nudgeRetry++,s<o.nudgeMaxRetry){const d=l+(s+1)*o.nudgeOffset,h=new Error(`Nudging 'currentTime' from ${l} to ${d}`);this.warn(h.message),i.currentTime=d,e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_NUDGE_ON_STALL,error:h,fatal:!1,buffer:t.len,bufferInfo:t})}else{const i=new Error(`Playhead still not moving while enough data buffered @${l} after ${o.nudgeMaxRetry} nudges`);this.error(i.message),e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}}function jo(t,e){const i=qo(t.main);if(i&&i.start<=e)return i;const s=qo(t.audio);return s&&s.start<=e?s:null}function qo(t){if(!t)return null;switch(t.state){case ps:case ms:case As:case Ls:return null}return t.frag}function Yo(t,e){return e.getAppendedFrag(t,c)||e.getPartialFragment(t)}function Wo(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function zo(t,e,i,s,r){let n=new t(e,i,"");try{n.value=s,r&&(n.type=r)}catch(a){n=new t(e,i,Xt(r?E({type:r},s):s))}return n}const Xo=(()=>{const t=Wo();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Qo{constructor(t){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(a.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var i;this.media=e.media,!1===(null==(i=e.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.removeCues&&Ea(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const i=t[e];if("metadata"===i.kind&&"id3"===i.label)return va(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Wo();if(n)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===sr.emsg&&!i||!s)continue;const a=Js(r[t].data),o=r[t].pts;let l=o+r[t].duration;l>Xo&&(l=Xo);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!tr(i)){this.updateId3CueEnds(o,e);const t=zo(n,o,l,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(t,e){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===e&&r.startTime<t&&r.endTime===Xo&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,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 t;t="audio"===s?t=>t.type===sr.audioId3&&o:"video"===s?t=>t.type===sr.emsg&&a:t=>t.type===sr.audioId3&&o||t.type===sr.emsg&&a,Ta(r,e,i,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,i){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Wo();if(s&&r&&!a){const{fragmentStart:e,fragmentEnd:i}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=i):o&&(r=this.assetCue=zo(o,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:d}=t,h=Object.keys(d);let c=this.dateRangeCuesAppended;var u;if(l&&i)if(null!=(u=l.cues)&&u.length){const t=Object.keys(c).filter(t=>!h.includes(t));for(let e=t.length;e--;){var f;const i=t[e],s=null==(f=c[i])?void 0:f.cues;delete c[i],s&&Object.keys(s).forEach(t=>{const e=s[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(e)}catch(t){}}})}}else c=this.dateRangeCuesAppended={};const g=t.fragments[t.fragments.length-1];if(0!==h.length&&e(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<h.length;t++){const e=h[t],i=d[e],s=i.startTime,r=c[e],n=(null==r?void 0:r.cues)||{};let l=(null==r?void 0:r.durationKnown)||!1,u=Xo;const{duration:f,endDate:g}=i;if(g&&null!==f)u=s+f,l=!0;else if(i.endOnNext&&!l){const t=h.reduce((t,e)=>{if(e!==i.id){const s=d[e];if(s.class===i.class&&s.startDate>i.startDate&&(!t||i.startDate<t.startDate))return s}return t},null);t&&(u=t.startTime,l=!0)}const m=Object.keys(i.attr);for(let t=0;t<m.length;t++){const d=m[t];if(!ri(d))continue;const h=n[d];if(h)!l||null!=r&&r.durationKnown?Math.abs(h.startTime-s)>.01&&(h.startTime=s,h.endTime=u):h.endTime=u;else if(o){let t=i.attr[d];ni(d)&&(t=P(t));const r=zo(o,s,u,{key:d,data:t},sr.dateRange);r&&(r.id=e,this.id3Track.addCue(r),n[d]=r,a&&("X-ASSET-LIST"!==d&&"X-ASSET-URL"!==d||r.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:n,dateRange:i,durationKnown:l}}}}}class Zo{constructor(t){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:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,s=Math.min(e,Math.max(1,i));this.changeMediaPlaybackRate(t,s)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(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(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,r=t-e-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 t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.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(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var i;e.details===n.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(t,e){var i,s;t.playbackRate!==e&&(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 ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}class Jo extends an{constructor(t,e){super(t,"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=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{const e=t.attrs;let{audioCodec:d,videoCodec:h}=t;d&&(t.audioCodec=d=kt(d,i)||void 0),h&&(h=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}(h));const{width:c,height:u,unknownCodecs:f}=t,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 "${e.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=e,S=`${`${y||"."}-`}${t.bitrate}-${E}-${p}-${m}-${T}-${v}`;if(r[S])if(r[S].uri===t.url||t.attrs["PATHWAY-ID"])r[S].addGroupId("audio",e.AUDIO),r[S].addGroupId("text",e.SUBTITLES);else{const e=n[S]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);r[S]=i,s.push(i)}else{const e=this.createLevel(t);r[S]=e,n[S]=1,s.push(e)}}),this.filterAndSortMediaOptions(s,e,a,o,l)}createLevel(t){const e=new Yt(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(t.message),e.supportedResult=Ot(t,[])}return e}isAudioSupported(t){return Tt(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Tt(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,s,o){var l;let d=[],h=[],c=t;const u=(null==(l=e.stats)?void 0:l.parsing)||{};if((i||s)&&o&&(c=c.filter(({videoCodec:t,videoRange:e,width:i,height:s})=>{return(!!t||!(!i||!s))&&(!!(r=e)&&Gt.indexOf(r)>-1);var r})),0===c.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i=`one or more CODECS in variant not supported: ${Xt(e.levels.map(t=>t.attrs.CODECS).filter((t,e,i)=>i.indexOf(t)===e))}`,this.warn(i),t+=` (${i})`);const s=new Error(t);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:s,reason:i})}}),void(u.end=performance.now());e.audioTracks&&(d=e.audioTracks.filter(t=>!t.audioCodec||this.isAudioSupported(t.audioCodec)),tl(d)),e.subtitles&&(h=e.subtitles,tl(h));const f=c.slice(0);c.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Gt.indexOf(t.videoRange)-Gt.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=At(t.videoCodec),s=At(e.videoCodec);if(i!==s)return s-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=Lt(t.codecSet),s=Lt(e.codecSet);if(i!==s)return s-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let g=f[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==f.length))for(let t=0;t<f.length;t++)if(f[t].pathwayId===c[0].pathwayId){g=f[t];break}this._levels=c;for(let t=0;t<c.length;t++)if(c[t]===g){var m;this._firstLevel=t;const e=g.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${e}`),void 0===(null==(m=this.hls.userConfig)?void 0:m.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const p=o&&!s,v=this.hls.config,y=!(!v.audioStreamController||!v.audioTrackController),E={levels:c,audioTracks:d,subtitleTracks:h,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:s,altAudio:y&&!p&&d.some(t=>!!t.url)};u.end=performance.now(),this.hls.trigger(a.MANIFEST_PARSED,E)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const i=new Error("invalid level idx"),s=t<0;if(this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.LEVEL_SWITCH_ERROR,level:t,fatal:s,error:i,reason:i.message}),s)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,o=s?s.attrs["PATHWAY-ID"]:void 0,l=e[t],d=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,i===t&&s&&o===d)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${d?" with Pathway "+d:""} from level ${i}${o?" with Pathway "+o:""}`);const h={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(a.LEVEL_SWITCHING,h);const c=l.details;if(!c||c.live){const t=this.switchParams(l.uri,null==s?void 0:s.details,c);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),i=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===l&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===c){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(s,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),s=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,o=null==n?void 0:n.age;this.log(`Loading level index ${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(a.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const i=this._levels.filter((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));rs(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.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(a.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(a.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function tl(t){const e={};t.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function el(){return self.SourceBuffer||self.WebKitSourceBuffer}function il(){if(!k())return!1;const t=el();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class sl extends ks{constructor(t,i,s){super(t,i,s,"stream-controller",c),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 t=this.media,i=t?t.currentTime:null;if(null===i||!e(i))return;if(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i))return;const s=this.getFwdBufferInfoAtPos(t,i,c,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${i} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=ps,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=ms}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Rs:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=ps;break}if(this.hls.nextLoadLevel!==this.level){this.state=ps;break}break}case Es:this.checkRetryDate()}this.state===ps&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(null===e||!s&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[r])return;const n=i[r],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger(a.BUFFER_EOS,t),void(this.state=As)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const d=n.details;if(!d||this.state===Rs||this.waitForLive(n))return this.level=r,this.state=Rs,void(this.startFragRequested=!1);const h=o.len,u=this.getMaxBufferLength(n.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&G(g)&&this.fragmentTracker.getState(g)!==De){var m;const t=(null!=(m=this.backtrackFragment)?m:g).sn-d.startSN,e=d.fragments[t-1];e&&g.cc===e.cc&&(g=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){const t=this.audioOnly&&!this.altAudio?N:B,e=(t===B?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,c)}g=this.getNextFragmentLoopLoading(g,d,o,c,u)}g&&(this.exceedsMaxBuffer(o,u,g)||(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),this.loadFragment(g,n,f)))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===ke||s===we?G(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,i):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,c)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),0!==this.altAudio){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let i;const s=this.getAppendedFrag(e.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*s)+1:0}else i=0;const n=this.getBufferedFrag(e.currentTime+i);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,s=Math.max(n.end,e+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 t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case vs:case ys:case Es:case Ss:case bs:this.state=ps}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;us(i,"playing",this.onMediaPlaying),us(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(fs(i,"playing",this.onMediaPlaying),fs(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(a.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,s=!1;for(let t=0;t<e.levels.length;t++){const r=e.levels[t].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),s=s||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&s&&!function(){var t;const e=el();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==ps)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=Rs)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:r}=this,n=e.level,o=e.details,l=o.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const d=e.levelInfo,h=this.fragCurrent;!h||this.state!==ys&&this.state!==Es||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let c=0;if(o.live||null!=(i=d.details)&&i.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(d.details=o,this.levelLastLoaded=d,r||this.setStartPosition(o,c),this.hls.trigger(a.LEVEL_UPDATED,{details:o,level:n}),this.state===Rs){if(this.waitForCdnTuneIn(o))return;this.state=ps}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r<s||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.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 t=ze.bufferInfo(i,s,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=s);if(t.start<=r)return void(i.currentTime=s);const{nextStart:e}=ze.bufferedInfo(t.buffered,r,0);e&&(i.currentTime=e)}else i.currentTime=s}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{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==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),f=this.transmuxer=this.transmuxer||new nn(this.hls,c,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,m=-1!==g,p=new Ye(i.level,i.sn,i.stats.chunkCount,r.byteLength,g,m),v=this.initPTS[i.cc];f.push(r,h,u,l,i,s,o.totalduration,d,p,v)}onAudioTrackSwitching(t,e){const i=this.hls,s=0!==this.altAudio;if(re(e.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 t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(a.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(a.AUDIO_TRACK_SWITCHED,e)}),void i.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(a.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=re(e.url,this.hls);if(i){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i?2:0,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,r,n=!1;for(const t in i){const e=i[t];if("main"===e.id){if(r=t,s=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.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(t,e){const{frag:i,part:s}=e,r=i.type===c;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===bs&&(this.state=ps));const t=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),G(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const n=this.media;n&&(!this._hasEnoughToStart&&ze.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=Ls;else switch(e.details){case n.FRAG_GAP:case n.FRAG_PARSING_ERROR:case n.FRAG_DECRYPT_ERROR:case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(c,e);break;case n.LEVEL_LOAD_ERROR:case n.LEVEL_LOAD_TIMEOUT:case n.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Rs||(null==(i=e.context)?void 0:i.type)!==l||(this.state=ps);break;case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case n.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case n.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=ps,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==N||!this.altAudio){const t=(e===B?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,c),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log(`could not seek to ${i}, already seeking at ${e}`);const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=ze.getBuffered(t),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),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),t.currentTime=i)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{const{hls:i}=this,s=null==t?void 0:t.frag;if(!s||this.fragContextChanged(s))return;e.fragmentError=0,this.state=ps,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(a.FRAG_LOADED,t),s.bitrateTest=!1}).catch(e=>{this.state!==ms&&this.state!==Ls&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const i=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,o=this.getCurrentContext(n);if(!o)return void this.resetWhenMissingContext(n);const{frag:l,part:d,level:h}=o,{video:c,text:u,id3:f,initSegment:g}=r,{details:m}=h,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l))this.fragmentTracker.removeFragment(l);else{if(this.state=Ss,g){const t=g.tracks;if(t){const e=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(h,t,e,n),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:t})}const r=g.initPTS,o=g.timescale,d=this.initPTS[l.cc];if(e(r)&&(!d||d.baseTime!==r||d.timescale!==o)){const t=g.trackId;this.initPTS[l.cc]={baseTime:r,timescale:o,trackId:t},s.trigger(a.INIT_PTS_FOUND,{frag:l,id:i,initPTS:r,timescale:o,trackId:t})}}if(c&&m){p&&"audiovideo"===c.type&&this.logMuxedErr(l);const t=m.fragments[l.sn-1-m.startSN],e=l.sn===m.startSN,i=!t||l.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:s,startDTS:r,endDTS:a}=c;if(d)d.elementaryStreams[c.type]={startPTS:t,endPTS:s,startDTS:r,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=c.firstKeyFramePTS?c.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!i)return void this.backtrack(l);i&&(l.gap=!0),l.setElementaryStreamInfo(c.type,l.start,s,l.start,a,!0)}else e&&t-(m.appliedTimelineOffset||0)>2&&(l.gap=!0);l.setElementaryStreamInfo(c.type,t,s,r,a),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,d,n,e||i)}else{if(!e&&!i)return void this.backtrack(l);l.gap=!0}}if(p){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=p;d&&(d.elementaryStreams[N]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(N,t,e,i,s),this.bufferFragmentData(p,l,d,n)}if(m&&null!=f&&f.samples.length){const t={id:i,frag:l,details:m,samples:f.samples};s.trigger(a.FRAG_PARSING_METADATA,t)}if(m&&u){const t={id:i,frag:l,details:m,samples:u.samples};s.trigger(a.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${G(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,s){if(this.state!==Ss)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:o}=e;if(r){const i=t.audioCodec;let s=_t(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 t=r.metadata;t&&"channelCount"in t&&1!==(t.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=c,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=c;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]=[${t.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete e.video,delete e.audio);const l=Object.keys(e);if(l.length){if(this.hls.trigger(a.BUFFER_CODECS,e),!this.hls)return;l.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(a.BUFFER_APPENDING,{type:t,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,c)}get maxBufferLength(){const{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=ps}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(ze.isBuffered(t,i)?e=this.getAppendedFrag(i):ze.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,i=e.level;t&&e.sn===t.sn&&t.level===i||(this.fragPlaying=e,this.hls.trigger(a.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(a.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return e(i)?this.getAppendedFrag(i):null}get currentProgramDateTime(){var t;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(e(i)){const t=this.getLevelDetails(),e=this.currentFrag||(t?ae(null,t.fragments,i):null);if(e){const t=e.programDateTime;if(null!==t){const s=t+1e3*(i-e.start);return new Date(s)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class rl extends T{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var e;if(t&&t!==(null==(e=s.context)?void 0:e.frag.type))return;s.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=n.KEY_LOAD_ERROR,i,s,a){return new je({type:r.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:a,error:i,networkDetails:s})}loadClear(t,e,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(let s=0,r=e.length;s<r;s++){const n=e[s];if(t.cc<=n.cc&&(!G(t)||!G(n)||t.sn<n.sn)||!i&&s==r-1)return this.emeController.selectKeySystemFormat(n).then(t=>{if(!this.emeController)return;n.setKeyFormat(t);const e=bi(t);return e?this.emeController.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=Li(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var i,s;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const i=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,n.KEY_LOAD_ERROR,i))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(t,n.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=nl(r);let l=this.keyIdToKeyInfo[o];if(null!=(i=l)&&i.decryptdata.key)return r.key=l.decryptdata.key,Promise.resolve({frag:t,keyInfo:l});if(this.emeController&&null!=(s=l)&&s.keyLoadPromise){switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(e=>{const{keyInfo:i}=e;return r.key=i.decryptdata.key,{frag:t,keyInfo:i}})}}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+D(r.keyId):""} URI: ${r.uri} from ${t.type} ${t.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(l,t):this.loadKeyEME(l,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,t);default:return Promise.reject(this.createKeyLoadError(t,n.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var s;if(!t.decryptdata.keyId&&null!=(s=e.initSegment)&&s.data){const i=function(t){const e=[];return ot(t,t=>e.push(t.subarray(8,24))),e}(e.initSegment.data);if(i.length){let e=i[0];e.some(t=>0!==t)?(this.log(`Using keyId found in init segment ${D(e)}`),wi.setKeyIdForUri(t.decryptdata.uri,e)):(e=wi.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${D(e)}`)),t.decryptdata.keyId=e}}if(!t.decryptdata.keyId&&!G(e))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(t.keyLoadPromise=r.then(e=>(t.mediaKeySessionContext=e,i))).catch(i=>{throw t.keyLoadPromise=null,"data"in i&&(i.data.frag=e),i})}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,s=new(0,i.loader)(i);return e.keyLoader=t.loader=s,t.keyLoadPromise=new Promise((r,a)=>{const o={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=i.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,s)=>{const{frag:o,keyInfo:l}=i,d=nl(l.decryptdata);if(!o.decryptdata||l!==this.keyIdToKeyInfo[d])return a(this.createKeyLoadError(o,n.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(t.data),o.keyLoader=null,l.loader=null,r({frag:o,keyInfo:l})},onError:(t,i,s,r)=>{this.resetLoader(i),a(this.createKeyLoadError(e,n.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),s,E({url:o.url,data:void 0},t)))},onTimeout:(t,i,s)=>{this.resetLoader(i),a(this.createKeyLoadError(e,n.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(t,i,s)=>{this.resetLoader(i),a(this.createKeyLoadError(e,n.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(o,d,h)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=null,i.loader=null);const n=nl(i.decryptdata)||s;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function nl(t){if(t.keyFormat!==Ei){const e=t.keyId;if(e)return D(e)}return t.uri}function al(t){const{type:e}=t;switch(e){case d:return u;case h:return f;default:return c}}function ol(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class ll{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,r=new(i||s)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:o,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:l,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:d,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:h,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const i=this.loaders[l];if(i){const t=i.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(i.abort(),delete this.loaders[l])}}load(t){var i;const s=this.hls.config;let r,n=this.getInternalLoader(t);if(n){const e=this.hls.logger,i=n.context;if(i&&i.levelOrTrack===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives))return void(i.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${i.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(r=t.type===o?s.manifestLoadPolicy.default:v({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),e(null==(i=t.deliveryDirectives)?void 0:i.part)){let e;if(t.type===l&&null!==t.level?e=this.hls.levels[t.level].details:t.type===d&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===h&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);r=v({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},c={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},u={onSuccess:(t,e,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=t.data;e.parsing.start=performance.now(),Fi.isMediaPlaylist(n)||i.type!==o?this.handleTrackOrLevelPlaylist(t,e,i,s||null,r):this.handleMasterPlaylist(t,e,i,s)},onError:(t,e,i,s)=>{this.handleNetworkError(e,i,!1,t,s)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};n.load(t,c,u)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,s){const r=this.hls,n=t.data,o=ol(t,i),l=Fi.parseMasterPlaylist(n,o);if(l.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);const{contentSteering:d,levels:h,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g}=l;this.variableList=g,h.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:r}=t;for(let n=e.length;n--;){const a=e[n];Tt(a,"audio",i)?(t.audioCodec=s=s?`${s},${a}`:a,yt.audio[s.substring(0,4)]=2,e.splice(n,1)):Tt(a,"video",i)&&(t.videoCodec=r=r?`${r},${a}`:a,yt.video[r.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=Fi.parseMasterPlaylistMedia(n,o,l);if(m.length){m.some(t=>!t.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new si({}),bitrate:0,url:""}))}r.trigger(a.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,captions:v,contentSteering:d,url:o,stats:e,networkDetails:s,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,i,s,r,n){const l=this.hls,{id:d,level:h,type:c}=s,u=ol(t,s),f=e(h)?h:e(d)?d:0,g=al(s),m=Fi.parseLevelPlaylist(t.data,u,f,g,0,this.variableList);if(c===o){const t={attrs:new si({}),bitrate:0,details:m,name:"",url:u};m.requestScheduled=i.loading.start+ts(m,0),l.trigger(a.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:u,stats:i,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}i.parsing.end=performance.now(),s.levelDetails=m,this.handlePlaylistLoaded(m,t,i,s,r,n)}handleManifestParsingError(t,e,i,s,l){this.hls.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.MANIFEST_PARSING_ERROR,fatal:e.type===o,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:l})}handleNetworkError(t,e,i=!1,s,c){let u=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===l?u+=`: ${t.level} id: ${t.id}`:t.type!==d&&t.type!==h||(u+=` id: ${t.id} group-id: "${t.groupId}"`);const f=new Error(u);this.hls.logger.warn(`[playlist-loader]: ${u}`);let g=n.UNKNOWN,m=!1;const p=this.getInternalLoader(t);switch(t.type){case o:g=i?n.MANIFEST_LOAD_TIMEOUT:n.MANIFEST_LOAD_ERROR,m=!0;break;case l:g=i?n.LEVEL_LOAD_TIMEOUT:n.LEVEL_LOAD_ERROR,m=!1;break;case d:g=i?n.AUDIO_TRACK_LOAD_TIMEOUT:n.AUDIO_TRACK_LOAD_ERROR,m=!1;break;case h:g=i?n.SUBTITLE_TRACK_LOAD_TIMEOUT:n.SUBTITLE_LOAD_ERROR,m=!1}p&&this.resetInternalLoader(t.type);const v={type:r.NETWORK_ERROR,details:g,fatal:m,url:t.url,loader:p,context:t,error:f,networkDetails:e,stats:c};if(s){const i=(null==e?void 0:e.url)||t.url;v.response=E({url:i,data:void 0},s)}this.hls.trigger(a.ERROR,v)}handlePlaylistLoaded(t,e,i,s,u,f){const g=this.hls,{type:m,level:p,levelOrTrack:v,id:y,groupId:E,deliveryDirectives:T}=s,S=ol(e,s),b=al(s);let A="number"==typeof s.level&&b===c?p:void 0;const L=t.playlistParsingError;if(L){if(this.hls.logger.warn(`${L} ${t.url}`),!g.config.ignorePlaylistParsingErrors)return void g.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_PARSING_ERROR,fatal:!1,url:S,error:L,reason:L.message,response:e,context:s,level:A,parent:b,networkDetails:u,stats:i});t.playlistParsingError=null}if(!t.fragments.length){const o=t.playlistParsingError=new Error("No Segments found in Playlist");return void g.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_EMPTY_ERROR,fatal:!1,url:S,error:o,reason:o.message,response:e,context:s,level:A,parent:b,networkDetails:u,stats:i})}switch(t.live&&f&&(f.getCacheAge&&(t.ageHeader=f.getCacheAge()||0),f.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),m){case o:case l:if(A)if(v){if(v!==g.levels[A]){const t=g.levels.indexOf(v);t>-1&&(A=t)}}else A=0;g.trigger(a.LEVEL_LOADED,{details:t,levelInfo:v||g.levels[0],level:A||0,id:y||0,stats:i,networkDetails:u,deliveryDirectives:T,withoutMultiVariant:m===o});break;case d:g.trigger(a.AUDIO_TRACK_LOADED,{details:t,track:v,id:y||0,groupId:E||"",stats:i,networkDetails:u,deliveryDirectives:T});break;case h:g.trigger(a.SUBTITLE_TRACK_LOADED,{details:t,track:v,id:y||0,groupId:E||"",stats:i,networkDetails:u,deliveryDirectives:T})}}}class dl{static get version(){return Ms}static isMSESupported(){return il()}static isSupported(){return function(){if(!il())return!1;const t=k();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(bt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(bt(e,"audio"))))}()}static getMediaSource(){return k()}static get Events(){return a}static get MetadataSchema(){return sr}static get ErrorTypes(){return r}static get ErrorDetails(){return n}static get DefaultConfig(){return dl.defaultConfig?dl.defaultConfig:Go}static set DefaultConfig(t){dl.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new xs,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 e=this.logger=function(t,e,i){const s=A();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach(e=>{s[e]=L(e,t,i)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch(t){return A()}r.forEach(e=>{I[e]=L(e,t)})}else v(I,s);return s}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(t,e,i){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Ko(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];r.forEach(i=>{const r=`${t}Loading${i}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=s[n].default;switch(e[n]={default:t},i){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Xt(e[n])}`)}),E(E({},s),e)}(dl.DefaultConfig,t,e);this.userConfig=t,i.progressive&&Vo(i,e);const{abrController:s,bufferController:r,capLevelController:n,errorController:o,fpsController:l}=i,d=new o(this),h=this.abrController=new s(this),c=new Pe(this),u=i.interstitialsController,f=u?this.interstitialsController=new u(this,dl):null,g=this.bufferController=new r(this,c),m=this.capLevelController=new n(this),p=new l(this),y=new ll(this),T=i.contentSteeringController,S=T?new T(this):null,b=this.levelController=new Jo(this,S),R=new Qo(this),k=new rl(this.config,this.logger),_=this.streamController=new sl(this,c,k),w=this.gapController=new Ho(this,c);m.setStreamController(_),p.setStreamController(_);const D=[y,b,_];f&&D.splice(1,0,f),S&&D.splice(1,0,S),this.networkControllers=D;const P=[h,g,w,m,p,R,c];this.audioTrackController=this.createController(i.audioTrackController,D);const C=i.audioStreamController;C&&D.push(this.audioStreamController=new C(this,c,k)),this.subtitleTrackController=this.createController(i.subtitleTrackController,D);const x=i.subtitleStreamController;x&&D.push(this.subtititleStreamController=new x(this,c,k)),this.createController(i.timelineController,P),k.emeController=this.emeController=this.createController(i.emeController,P),this.cmcdController=this.createController(i.cmcdController,P),this.latencyController=this.createController(Zo,P),this.coreComponents=P,D.push(d);const M=d.onErrorOut;"function"==typeof M&&this.on(a.ERROR,M,d),this.on(a.MANIFEST_LOADED,y.onManifestLoaded,y)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===a.ERROR;this.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(a.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,s=e?t:{media:i};this._media=i,this.trigger(a.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(a.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(a.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,i=this._url,s=this._url=O.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),e&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(a.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[c]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[u]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[f]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)})}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return $t.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(s=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=s;e--;){const s=t[e].attrs["HDCP-LEVEL"];if(s&&s<=i)return e}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}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(t){this.latencyController.targetLatency=t}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(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return Nt(t,Zt(e),navigator.mediaCapabilities)}}function hl(t){const{baseUrl:e,apiKey:i,clientId:s,fetch:r,apiVersion:n}=t,a=r??globalThis.fetch;if(!a)throw new Error("No fetch implementation found. Provide one in SDKConfig.fetch for Node or custom environments.");const o={"Content-Type":"application/json","x-api-key":i},l=t=>function(t,e,i,s){if(/^https?:\/\//i.test(s))return s;const r=t.replace(/\/+$/,""),n=s.replace(/^\/+/,"");return`${r}/b2b/${e}/subscription/${encodeURIComponent(i)}${n.startsWith("/")?n:`/${n}`}`}(e,function(t){const e=t.toLowerCase();return"v1"===e||"v2"===e?e:"v1"}(n),s,t),d=async(t,e,i,s)=>{const r={method:t,headers:{...o,...i?.headers},...i};void 0!==s&&(r.body=JSON.stringify(s));return async function(t){if(!t.ok){const e=await t.text().catch(()=>"");throw new Error(`HTTP ${t.status}: ${e||t.statusText}`)}if(204!==t.status)return t.json()}(await a(l(e),r))};return{get:(t,e)=>d("GET",t,e),post:(t,e,i)=>d("POST",t,i,e),put:(t,e,i)=>d("PUT",t,i,e),patch:(t,e,i)=>d("PATCH",t,i,e),delete:(t,e)=>d("DELETE",t,e)}}dl.defaultConfig=void 0;const cl="https://api.jaaq.app";class ul{constructor(t,e){"v2"===e?(this.videos=function(t){return{async getById(e){const i=`/videos/${encodeURIComponent(e)}`;return(await t.get(i)).video}}}(t),this.collections=function(t){return{list:async()=>(await t.get("/collections")).collections,async getById(e){const i=`/collections/${encodeURIComponent(e)}`;return(await t.get(i)).collection}}}(t)):(this.videos=function(t){return{async getById(e){const i=`/videos/${encodeURIComponent(e)}`;return(await t.get(i)).video}}}(t),this.collections=function(t){return{list:async()=>(await t.get("/collections")).collections,async getById(e){const i=`/collections/${encodeURIComponent(e)}`;return(await t.get(i)).collection}}}(t))}static fromHttp(t,e){return new ul(t,e)}static init(t){return fl(t)}}function fl(t){const{baseUrl:e=cl,apiKey:i,clientId:s,fetch:r,apiVersion:n="v1"}=t,a=hl({baseUrl:e,apiKey:i,clientId:s,fetch:r??globalThis.fetch,apiVersion:n});return ul.fromHttp(a,n)}function gl(t,e,i){return Math.max(e,Math.min(i,t))}var ml=".jaaq-video-player {\n position: relative;\n width: 100%;\n max-width: none;\n margin: 0;\n background: #000;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n aspect-ratio: 9 / 16;\n}\n\n.jaaq-video-player video {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n display: block;\n background: #000;\n object-fit: cover;\n}\n\n.jaaq-video-player.fullscreen {\n max-width: 100%;\n border-radius: 0;\n aspect-ratio: auto;\n}\n\n.jaaq-controls {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);\n padding: 40px 16px 16px;\n opacity: 1;\n z-index: 5;\n}\n\n.jaaq-progress-bar {\n width: 100%;\n flex: 1 1 0;\n min-width: 80px;\n height: 4px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 2px;\n cursor: pointer;\n position: relative;\n}\n\n.jaaq-progress-filled {\n height: 100%;\n background: #007bff;\n border-radius: 2px;\n width: 0%;\n transition: width 0.1s linear;\n}\n\n.jaaq-progress-bar:hover .jaaq-progress-filled {\n background: #0056b3;\n}\n\n.jaaq-controls-bottom {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n color: white;\n}\n\n.jaaq-control-btn {\n background: transparent;\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 20px;\n line-height: 1;\n}\n\n.jaaq-control-btn:hover {\n transform: scale(1.1);\n}\n\n.jaaq-control-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n}\n\n.jaaq-loading {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 50px;\n height: 50px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-spin 1s linear infinite;\n}\n\n@keyframes jaaq-spin {\n to {\n transform: translate(-50%, -50%) rotate(360deg);\n }\n}\n\n.jaaq-error {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n max-width: 80%;\n text-align: center;\n font-size: 14px;\n}\n\n.jaaq-video-info {\n padding: 16px;\n background: #f8f9fa;\n border-radius: 0 0 12px 12px;\n margin-top: -12px;\n}\n\n.jaaq-video-info h3 {\n margin: 0 0 8px 0;\n color: #333;\n font-size: 18px;\n font-weight: 600;\n}\n\n.jaaq-video-info p {\n margin: 4px 0;\n color: #666;\n font-size: 14px;\n}\n\n.jaaq-video-info strong {\n color: #333;\n}\n\n.jaaq-logo {\n position: absolute;\n top: 20px;\n left: 22px;\n color: white;\n font-size: 16px;\n font-weight: 600;\n z-index: 10;\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n letter-spacing: 0.5px;\n pointer-events: none;\n}\n\n.jaaq-center-play-btn {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 84px;\n height: 84px;\n background: transparent;\n border: none;\n cursor: pointer;\n z-index: 15;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n padding: 0;\n}\n\n.jaaq-center-play-btn:hover {\n transform: translate(-50%, -50%) scale(1.1);\n}\n\n.jaaq-center-play-btn svg {\n width: 100%;\n height: 100%;\n filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3));\n}\n\n.jaaq-video-player.is-playing .jaaq-center-play-btn {\n display: none;\n}\n\n.jaaq-gradient-overlay {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(180deg, transparent 0%, #0f0f0f 100%);\n padding: 80px 22px 85px;\n pointer-events: none;\n z-index: 5;\n}\n\n.jaaq-caption-display {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 400;\n font-size: 16px;\n line-height: 20px;\n color: white;\n background: rgba(0, 0, 0, 0.8);\n padding: 8px 16px;\n margin-bottom: 12px;\n border-radius: 4px;\n text-align: center;\n max-width: 90%;\n margin-left: auto;\n margin-right: auto;\n}\n\n.jaaq-video-title {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 600;\n font-size: 18.695px;\n line-height: 21.5px;\n color: white;\n margin-bottom: 8px;\n letter-spacing: 0.37px;\n}\n\n.jaaq-video-author {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 500;\n font-size: 14.021px;\n line-height: 16.825px;\n color: white;\n opacity: 0.7;\n margin-bottom: 8px;\n letter-spacing: -0.14px;\n}\n\n.jaaq-video-description {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 400;\n font-size: 11px;\n line-height: 16px;\n color: #aaa8aa;\n letter-spacing: -0.11px;\n}\n\n.jaaq-description-text {\n color: #aaa8aa;\n}\n\n.jaaq-read-more {\n color: white;\n cursor: pointer;\n pointer-events: auto;\n}\n\n.jaaq-read-more:hover {\n text-decoration: underline;\n}\n\n.jaaq-progress-bar {\n background: rgba(255, 255, 255, 0.2);\n}\n\n.jaaq-progress-filled {\n background: white;\n}\n\n.jaaq-captions-btn {\n font-size: 14px;\n font-weight: 600;\n border: 1.5px solid white;\n border-radius: 3px;\n padding: 4px 6px;\n line-height: 1;\n}\n\n.jaaq-captions-btn.active {\n background: white;\n color: #000;\n}\n";class pl{constructor(t,e){if(this.client=null,this.hls=null,this.videoElement=null,this.listeners=new Map,this.captionCues=[],this.elements={},this.container="string"==typeof t?document.querySelector(t):t,!this.container)throw new Error("Container element not found");if(this.config=e,this.state={isPlaying:!1,currentTime:0,duration:0,volume:1,isMuted:!0===e.startMuted,isFullscreen:!1,isLoading:!0,error:null,videoData:null,captionsEnabled:!1},e.client)this.client=e.client;else{if(!e.apiKey||!e.clientId)throw new Error("Please provide either a client instance or apiKey and clientId");this.client=function(t){return fl(t)}({apiKey:e.apiKey,clientId:e.clientId,baseUrl:e.baseUrl})}this.init()}async init(){this.createDOM(),await this.loadVideo(),this.attachEventListeners(),!0===this.config.startMuted&&this.updateVolumeUI()}createDOM(){this.container.innerHTML="";const t=document.createElement("div");t.style.width=this.config.width||"100%",t.style.height=this.config.height||"auto";const e=document.createElement("div");e.className=`jaaq-video-player jaaq-vanilla-player ${this.config.className||""}`,this.elements.player=e;const i=document.createElement("video");this.videoElement=i,!0===this.config.startMuted&&(i.muted=!0,i.setAttribute("muted","")),e.appendChild(i);const s=document.createElement("div");s.className="jaaq-logo",s.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" width="50" height="15" viewBox="0 0 50 15" fill="none">\n <path d="M48.0329 10.7826C48.7578 9.6622 49.1402 8.37108 49.1402 7.02322C49.1402 3.19784 46.0283 0.0859375 42.2029 0.0859375C38.3775 0.0859375 35.2656 3.19784 35.2656 7.02322C35.2656 10.8486 38.3753 13.9578 42.1985 13.9605C42.1991 13.9605 42.2002 13.9605 42.2007 13.9605H42.2029C43.8475 13.9605 45.4305 13.3687 46.6698 12.3285L49.9971 14.56V12.0999L48.0334 10.7826H48.0329ZM37.309 7.02322C37.309 4.32479 39.5045 2.12927 42.2035 2.12927C44.9024 2.12927 47.0974 4.32479 47.0974 7.02322C47.0974 7.96252 46.8345 8.862 46.3359 9.64475L43.9817 8.06561C43.4531 7.71378 42.8373 7.52778 42.2002 7.52778C40.4394 7.52778 39.0054 8.95036 38.9846 10.7062C37.9586 9.80839 37.3084 8.49053 37.3084 7.02322H37.309ZM42.2035 11.9172C42.2035 11.9172 42.2002 11.9172 42.1985 11.9172C41.5527 11.9161 41.0274 11.3903 41.0274 10.7439C41.0274 10.0975 41.5538 9.57056 42.2007 9.57056C42.4331 9.57056 42.6578 9.6382 42.8493 9.76584L44.8714 11.1224C44.0853 11.633 43.1586 11.9172 42.2029 11.9172H42.2035Z" fill="white"/>\n <path d="M31.0751 0.686201C30.9856 0.579834 30.8858 0.483286 30.7767 0.39983C30.4374 0.138004 30.0283 0 29.5946 0C29.161 0 28.7524 0.138549 28.4126 0.39983C28.2304 0.540561 28.0755 0.711838 27.9533 0.909844C27.8835 1.02276 27.8257 1.14003 27.7815 1.25785L23.1172 13.7317H25.4551L29.5946 2.66135L33.7342 13.7317H36.0721L31.4078 1.25785C31.3303 1.05003 31.218 0.858024 31.0745 0.686746L31.0751 0.686201Z" fill="white"/>\n <path d="M17.4969 0.686201C17.4075 0.579834 17.3076 0.483286 17.1986 0.39983C16.8593 0.138004 16.4502 0 16.0165 0C15.5829 0 15.1743 0.138549 14.8345 0.39983C14.6523 0.540561 14.4974 0.711838 14.3752 0.909844C14.3054 1.02276 14.2476 1.14003 14.2034 1.25785L9.53906 13.7317H11.8769L16.0165 2.66135L20.1561 13.7317H22.494L17.8302 1.25731C17.7527 1.04948 17.6404 0.857478 17.4969 0.686201Z" fill="white"/>\n <path d="M9.86046 0.511825V0.371094H7.82204V9.02333C7.82204 10.6248 6.51891 11.928 4.91741 11.928C3.47028 11.928 2.23261 10.849 2.03897 9.41771L2.01988 9.27807L1.88024 9.29716L0.13964 9.5328L0 9.5519L0.0190914 9.69154C0.348555 12.1292 2.45462 13.9669 4.91741 13.9669C7.64313 13.9669 9.86046 11.7496 9.86046 9.02388V0.511825Z" fill="white"/>\n </svg>\n ',this.elements.logo=s,e.appendChild(s);const r=document.createElement("button");r.className="jaaq-center-play-btn",r.innerHTML='\n <svg viewBox="0 0 84 84" fill="none">\n <circle cx="42" cy="42" r="42" fill="white" fill-opacity="0.9"/>\n <path d="M33 28L56 42L33 56V28Z" fill="#000"/>\n </svg>\n ',r.setAttribute("aria-label","Play video"),this.elements.centerPlayBtn=r,e.appendChild(r);const n=document.createElement("div");n.className="jaaq-gradient-overlay",this.elements.gradientOverlay=n;const a=document.createElement("div");a.className="jaaq-caption-display",a.style.display="none",this.elements.captionDisplay=a,n.appendChild(a);const o=document.createElement("div");o.className="jaaq-video-title",this.elements.videoTitle=o,n.appendChild(o);const l=document.createElement("div");l.className="jaaq-video-author",this.elements.videoAuthor=l,n.appendChild(l);const d=document.createElement("div");d.className="jaaq-video-description",this.elements.videoDescription=d,n.appendChild(d),e.appendChild(n);const h=document.createElement("div");h.className="jaaq-loading",this.elements.loading=h,e.appendChild(h);const c=document.createElement("div");c.className="jaaq-error",c.style.display="none",this.elements.error=c,e.appendChild(c);const u=document.createElement("div");u.className="jaaq-controls",this.elements.controls=u;const f=document.createElement("div");f.className="jaaq-controls-bottom";const g=document.createElement("button");g.className="jaaq-control-btn",g.textContent="▶",g.setAttribute("aria-label","Play"),this.elements.playPauseBtn=g,f.appendChild(g);const m=document.createElement("button");m.className="jaaq-control-btn",m.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287ZM14.0215 0.150391C16.2405 0.150468 18.1409 1.39074 19.4385 3.17676C20.7365 4.9634 21.499 7.36811 21.499 9.96484C21.499 12.5613 20.7363 14.9654 19.4385 16.752C18.1409 18.538 16.2405 19.7792 14.0215 19.7793V17.1025C15.2032 17.1025 16.3824 16.4464 17.3135 15.165C18.2442 13.8839 18.8593 12.0493 18.8594 9.96484C18.8594 7.88034 18.2442 6.04581 17.3135 4.76465C16.3824 3.4832 15.2033 2.82723 14.0215 2.82715V0.150391ZM14.0215 5.75879C15.5701 5.75896 16.8252 7.64189 16.8252 9.96484C16.8251 12.2877 15.57 14.1707 14.0215 14.1709V5.75879Z" fill="white"/>\n </svg>\n ',m.setAttribute("aria-label","Mute"),this.elements.volumeBtn=m,f.appendChild(m);const p=document.createElement("div");p.className="jaaq-progress-bar",this.elements.progressBar=p;const v=document.createElement("div");v.className="jaaq-progress-filled",this.elements.progressFilled=v,p.appendChild(v),f.appendChild(p);const y=document.createElement("button");y.className="jaaq-control-btn jaaq-captions-btn",y.innerHTML="CC",y.setAttribute("aria-label","Captions"),this.elements.captionsBtn=y,f.appendChild(y);const E=document.createElement("button");E.className="jaaq-control-btn",E.textContent="⛶",E.setAttribute("aria-label","Fullscreen"),this.elements.fullscreenBtn=E,f.appendChild(E),u.appendChild(f),e.appendChild(u),t.appendChild(e),this.container.appendChild(t),this.updateControlsVisibility()}updateControlsVisibility(){const t=!1!==this.config.controls;this.elements.controls&&(this.elements.controls.style.display=t?"":"none")}async loadVideo(){if(this.client&&this.videoElement)try{this.setState({isLoading:!0,error:null});const t=await this.client.videos.getById(this.config.videoId);this.setState({videoData:t}),t.subtitle&&(this.captionCues=this.parseWebVTT(t.subtitle)),this.updateOverlayContent(t),this.emit("loaded",t);const e=t.videoUrl;if(e.includes(".m3u8"))if(dl.isSupported()){this.hls&&this.hls.destroy();const t=new dl({enableWorker:!0,lowLatencyMode:!0});!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted","")),t.loadSource(e),t.attachMedia(this.videoElement),!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted","")),t.on(dl.Events.MANIFEST_PARSED,()=>{this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}),t.on(dl.Events.ERROR,(t,e)=>{if(e.fatal){const t=`HLS Error: ${e.type} - ${e.details}`;this.showError(t),this.emit("error",new Error(t))}}),this.hls=t}else{if(!this.videoElement.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS is not supported in this browser");this.videoElement.src=e,!0===this.config.startMuted&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}else this.videoElement.src=e,!0===this.config.startMuted&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}catch(t){const e=t instanceof Error?t.message:"Failed to load video";this.showError(e),this.setState({isLoading:!1}),this.emit("error",t instanceof Error?t:new Error(e))}}parseWebVTT(t){const e=[],i=t.split("\n");let s=0;for(;s<i.length;){const t=i[s].trim();if(t.includes("--\x3e")){const[r,n]=t.split("--\x3e").map(t=>t.trim()),a=t=>{const e=t.split(":");if(3===e.length){return 3600*parseFloat(e[0])+60*parseFloat(e[1])+parseFloat(e[2])}if(2===e.length){return 60*parseFloat(e[0])+parseFloat(e[1])}return 0},o=a(r),l=a(n);s++;const d=[];for(;s<i.length&&""!==i[s].trim();)d.push(i[s].trim()),s++;d.length>0&&e.push({start:o,end:l,text:d.join(" ")})}s++}return e}updateOverlayContent(t){const e=!1!==this.config.showLogo,i=!1!==this.config.showTitle,s=!1!==this.config.showAuthor,r=!1!==this.config.showDescription,n=!1!==this.config.showCaptions;if(this.elements.logo&&(this.elements.logo.style.display=e?"block":"none"),this.elements.videoTitle){const e=t.question||"",s=t.creator||"",r=s?`${e} - ${s}`:e;this.elements.videoTitle.textContent=r,this.elements.videoTitle.style.display=i&&e?"block":"none"}if(this.elements.videoAuthor){const e=t.author||t.creator||t.userName||"";this.elements.videoAuthor.textContent=e,this.elements.videoAuthor.style.display=s&&e?"block":"none"}if(this.elements.videoDescription){const e=t.creatorBiography||t.description||"";if(e){const t=150,i=e.length>t?e.substring(0,t)+"...":e;this.elements.videoDescription.innerHTML=`\n <span class="jaaq-description-text">${i}</span>\n ${e.length>t?'<span class="jaaq-read-more"> Read more</span>':""}\n `}this.elements.videoDescription.style.display=r&&e?"block":"none"}this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=n?"flex":"none")}attachEventListeners(){this.videoElement&&(this.videoElement.addEventListener("play",()=>{this.setState({isPlaying:!0}),this.updatePlayPauseButton(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="none"),this.emit("play",void 0)}),this.videoElement.addEventListener("pause",()=>{this.setState({isPlaying:!1}),this.updatePlayPauseButton(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="flex"),this.emit("pause",void 0)}),this.videoElement.addEventListener("timeupdate",()=>{this.setState({currentTime:this.videoElement.currentTime}),this.updateProgress(),this.updateCaptions(),this.emit("timeupdate",this.videoElement.currentTime)}),this.videoElement.addEventListener("durationchange",()=>{this.setState({duration:this.videoElement.duration})}),this.videoElement.addEventListener("volumechange",()=>{this.setState({volume:this.videoElement.volume,isMuted:this.videoElement.muted}),this.updateVolumeUI(),this.emit("volumechange",this.videoElement.volume)}),this.videoElement.addEventListener("ended",()=>{this.emit("ended",void 0)}),this.elements.playPauseBtn?.addEventListener("click",()=>{this.togglePlayPause()}),this.elements.centerPlayBtn?.addEventListener("click",()=>{this.play(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="none")}),this.elements.progressBar?.addEventListener("click",t=>{this.handleSeek(t)}),this.elements.volumeBtn?.addEventListener("click",()=>{this.toggleMute()}),this.elements.captionsBtn?.addEventListener("click",()=>{this.toggleCaptions()}),this.elements.fullscreenBtn?.addEventListener("click",()=>{this.toggleFullscreen()}),document.addEventListener("fullscreenchange",()=>{const t=!!document.fullscreenElement;this.setState({isFullscreen:t}),this.elements.player?.classList.toggle("fullscreen",t),this.emit("fullscreenchange",t)}),this.elements.player?.addEventListener("mousemove",()=>{this.elements.player?.classList.remove("is-paused")}),this.videoElement.addEventListener("pause",()=>{this.elements.player?.classList.add("is-paused")}),this.videoElement.addEventListener("play",()=>{this.elements.player?.classList.remove("is-paused")}))}setState(t){this.state={...this.state,...t}}updatePlayPauseButton(){this.elements.playPauseBtn&&(this.elements.playPauseBtn.textContent=this.state.isPlaying?"⏸":"▶",this.elements.playPauseBtn.setAttribute("aria-label",this.state.isPlaying?"Pause":"Play"))}updateProgress(){if(this.elements.progressFilled&&this.state.duration>0){const t=this.state.currentTime/this.state.duration*100;this.elements.progressFilled.style.width=`${t}%`}}updateVolumeUI(){if(this.elements.volumeBtn){const{isMuted:t,volume:e}=this.state;this.elements.volumeBtn.innerHTML=t||0===e?'\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287Z" fill="white"/>\n </svg>\n ':'\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287ZM14.0215 0.150391C16.2405 0.150468 18.1409 1.39074 19.4385 3.17676C20.7365 4.9634 21.499 7.36811 21.499 9.96484C21.499 12.5613 20.7363 14.9654 19.4385 16.752C18.1409 18.538 16.2405 19.7792 14.0215 19.7793V17.1025C15.2032 17.1025 16.3824 16.4464 17.3135 15.165C18.2442 13.8839 18.8593 12.0493 18.8594 9.96484C18.8594 7.88034 18.2442 6.04581 17.3135 4.76465C16.3824 3.4832 15.2033 2.82723 14.0215 2.82715V0.150391ZM14.0215 5.75879C15.5701 5.75896 16.8252 7.64189 16.8252 9.96484C16.8251 12.2877 15.57 14.1707 14.0215 14.1709V5.75879Z" fill="white"/>\n </svg>\n '}}updateCaptions(){if(!this.elements.captionDisplay||!this.state.captionsEnabled)return void(this.elements.captionDisplay&&(this.elements.captionDisplay.style.display="none"));const t=this.state.currentTime,e=this.captionCues.find(e=>t>=e.start&&t<=e.end);e?(this.elements.captionDisplay.textContent=e.text,this.elements.captionDisplay.style.display="block"):this.elements.captionDisplay.style.display="none"}handleSeek(t){if(!this.videoElement||!this.state.duration||!this.elements.progressBar)return;const e=this.elements.progressBar.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.videoElement.currentTime=this.state.duration*gl(i,0,1)}showError(t){this.setState({error:t,isLoading:!1}),this.elements.error&&(this.elements.error.textContent=t,this.elements.error.style.display="block"),this.elements.loading&&(this.elements.loading.style.display="none")}togglePlayPause(){this.state.isPlaying?this.pause():this.play()}toggleCaptions(){this.setState({captionsEnabled:!this.state.captionsEnabled}),this.updateCaptionsButton(),this.updateCaptions()}updateCaptionsButton(){this.elements.captionsBtn&&(this.state.captionsEnabled?this.elements.captionsBtn.classList.add("active"):this.elements.captionsBtn.classList.remove("active"))}toggleFullscreen(){var t;this.elements.player&&(t=this.elements.player,document.fullscreenElement?document.exitFullscreen():t.requestFullscreen())}play(){this.videoElement&&(!0!==this.config.startMuted||this.videoElement.muted||(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0})),this.videoElement.play())}pause(){this.videoElement?.pause()}setVolume(t){this.videoElement&&(this.videoElement.volume=gl(t,0,1),this.videoElement.muted=0===t)}toggleMute(){this.videoElement&&(this.videoElement.muted=!this.videoElement.muted)}seek(t){this.videoElement&&(this.videoElement.currentTime=gl(t,0,this.state.duration))}setFeatures(t){this.config={...this.config,...t},void 0!==t.controls&&this.updateControlsVisibility(),void 0!==t.startMuted&&this.videoElement&&(this.videoElement.muted=!0===t.startMuted,!0===t.startMuted?this.videoElement.setAttribute("muted",""):this.videoElement.removeAttribute("muted"),this.setState({isMuted:!0===t.startMuted}),this.updateVolumeUI()),this.state.videoData?this.updateOverlayContent(this.state.videoData):(void 0!==t.showLogo&&this.elements.logo&&(this.elements.logo.style.display=t.showLogo?"block":"none"),void 0!==t.showCaptions&&this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=t.showCaptions?"flex":"none"))}getState(){return{...this.state}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e)}off(t,e){const i=this.listeners.get(t);i&&i.delete(e)}emit(t,e){const i=this.listeners.get(t);i&&i.forEach(t=>t(e))}destroy(){this.hls&&(this.hls.destroy(),this.hls=null),this.videoElement&&(this.videoElement.pause(),this.videoElement.src="",this.videoElement=null),this.listeners.clear(),this.container.innerHTML=""}}class vl extends HTMLElement{static get observedAttributes(){return["video-id","api-key","client-id","autoplay","base-url","width","height","controls","show-logo","show-title","show-author","show-description","show-captions","start-muted"]}constructor(){super(),this.player=null,this.container=null,this.clientInstance=null,this.connected=!1,this.attachShadow({mode:"open"})}connectedCallback(){this.connected=!0,this.render(),this.initPlayer()}disconnectedCallback(){this.connected=!1,this.destroyPlayer()}attributeChangedCallback(t,e,i){if(this.connected&&e!==i)if("video-id"===t&&this.player)this.destroyPlayer(),this.initPlayer();else if("width"===t||"height"===t)this.updateContainerStyles();else if(("controls"===t||"show-logo"===t||"show-title"===t||"show-author"===t||"show-description"===t||"show-captions"===t||"start-muted"===t)&&this.player){const e={};"controls"===t?e.controls=!this.hasAttribute("controls")||"false"!==this.getAttribute("controls"):"show-logo"===t?e.showLogo=!this.hasAttribute("show-logo")||"false"!==this.getAttribute("show-logo"):"show-title"===t?e.showTitle=!this.hasAttribute("show-title")||"false"!==this.getAttribute("show-title"):"show-author"===t?e.showAuthor=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"):"show-description"===t?e.showDescription=!this.hasAttribute("show-description")||"false"!==this.getAttribute("show-description"):"show-captions"===t?e.showCaptions=!this.hasAttribute("show-captions")||"false"!==this.getAttribute("show-captions"):"start-muted"===t&&(e.startMuted=this.hasAttribute("start-muted")&&"false"!==this.getAttribute("start-muted")),this.player.setFeatures(e)}}render(){if(!this.shadowRoot)return;const t=document.createElement("style");t.textContent=`\n ${ml}\n .jaaq-vanilla-player {\n user-select: none;\n}\n\n.jaaq-vanilla-player video {\n outline: none;\n}\n\n.jaaq-collection-player {\n width: 100%;\n max-width: 1400px;\n margin: 0 auto;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n}\n\n.jaaq-collection-loading {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 400px;\n}\n\n.jaaq-collection-spinner {\n width: 50px;\n height: 50px;\n border: 4px solid rgba(0, 123, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-collection-spin 1s linear infinite;\n}\n\n@keyframes jaaq-collection-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n.jaaq-collection-error {\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n text-align: center;\n font-size: 14px;\n margin: 20px;\n}\n\n.jaaq-collection-carousel .splide__track {\n padding: 40px 0;\n}\n\n.jaaq-collection-carousel .splide__slide {\n opacity: 0.7;\n transition: all 0.3s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active {\n opacity: 1;\n}\n\n.jaaq-collection-carousel .splide__slide jaaq-video-player {\n width: 100%;\n max-width: 600px;\n transition: all 0.3s ease;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 800px;\n}\n\n.jaaq-collection-carousel .splide__arrow {\n background: rgba(0, 0, 0, 0.5);\n border: none;\n width: 48px;\n height: 48px;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n transition: all 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 20px;\n}\n\n.jaaq-collection-carousel .splide__arrow:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n}\n\n.jaaq-collection-carousel .splide__arrow:disabled {\n opacity: 0.3;\n cursor: not-allowed;\n}\n\n.jaaq-collection-carousel .splide__arrow svg {\n fill: white;\n width: 20px;\n height: 20px;\n}\n\n.jaaq-collection-carousel .splide__pagination {\n bottom: -30px;\n}\n\n.jaaq-collection-carousel .splide__pagination__page {\n background: #ccc;\n border: none;\n width: 10px;\n height: 10px;\n margin: 0 4px;\n border-radius: 50%;\n transition: all 0.2s;\n cursor: pointer;\n}\n\n.jaaq-collection-carousel .splide__pagination__page.is-active {\n background: #007bff;\n transform: scale(1.3);\n}\n\n@media (max-width: 1024px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 650px;\n }\n}\n\n@media (max-width: 768px) {\n .jaaq-collection-carousel .splide__track {\n padding: 20px 0;\n }\n\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 400px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__arrow {\n width: 40px;\n height: 40px;\n }\n}\n\n@media (max-width: 480px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 100%;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 100%;\n }\n}\n\n \n:host {\n display: block;\n width: 100%;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n `,this.container=document.createElement("div"),this.container.className="jaaq-webcomponent-container",this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(this.container),this.updateContainerStyles()}updateContainerStyles(){if(!this.container)return;const t=this.getAttribute("width")||"100%",e=this.getAttribute("height")||"auto";this.container.style.width=t,this.container.style.height=e}async initPlayer(){if(!this.container||this.player)return;const t=this.getAttribute("video-id");if(!t)return void this.emitError(new Error("video-id attribute is required"));const e=this.getAttribute("api-key"),i=this.getAttribute("client-id"),s=this.getAttribute("base-url")||void 0,r=this.getAttribute("api-version")||void 0,n=this.hasAttribute("autoplay")&&"false"!==this.getAttribute("autoplay"),a=!this.hasAttribute("controls")||"false"!==this.getAttribute("controls"),o=!this.hasAttribute("show-logo")||"false"!==this.getAttribute("show-logo"),l=!this.hasAttribute("show-title")||"false"!==this.getAttribute("show-title"),d=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"),h=!this.hasAttribute("show-description")||"false"!==this.getAttribute("show-description"),c=!this.hasAttribute("show-captions")||"false"!==this.getAttribute("show-captions"),u=this.hasAttribute("start-muted")&&"false"!==this.getAttribute("start-muted");if(this.clientInstance||e||i)try{this.player=new pl(this.container,{videoId:t??void 0,apiKey:e??void 0,clientId:i??void 0,client:this.clientInstance||void 0,baseUrl:s,apiVersion:r,autoplay:n,controls:a,showLogo:o,showTitle:l,showAuthor:d,showDescription:h,showCaptions:c,startMuted:u}),this.attachPlayerEvents()}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to initialize player"))}else this.emitError(new Error("Either client property or api-key and client-id attributes are required"))}attachPlayerEvents(){this.player&&(this.player.on("loaded",t=>{this.dispatchEvent(new CustomEvent("jaaq:loaded",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("play",()=>{this.dispatchEvent(new CustomEvent("jaaq:play",{bubbles:!0,composed:!0}))}),this.player.on("pause",()=>{this.dispatchEvent(new CustomEvent("jaaq:pause",{bubbles:!0,composed:!0}))}),this.player.on("timeupdate",t=>{this.dispatchEvent(new CustomEvent("jaaq:timeupdate",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("volumechange",t=>{this.dispatchEvent(new CustomEvent("jaaq:volumechange",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("ended",()=>{this.dispatchEvent(new CustomEvent("jaaq:ended",{bubbles:!0,composed:!0}))}),this.player.on("error",t=>{this.emitError(t)}),this.player.on("fullscreenchange",t=>{this.dispatchEvent(new CustomEvent("jaaq:fullscreenchange",{detail:t,bubbles:!0,composed:!0}))}))}emitError(t){this.dispatchEvent(new CustomEvent("jaaq:error",{detail:t,bubbles:!0,composed:!0}))}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null)}get client(){return this.clientInstance}set client(t){this.clientInstance=t,this.connected&&(this.destroyPlayer(),this.initPlayer())}get videoId(){return this.getAttribute("video-id")}set videoId(t){t?this.setAttribute("video-id",t):this.removeAttribute("video-id")}play(){this.player?.play()}pause(){this.player?.pause()}setVolume(t){this.player?.setVolume(t)}toggleMute(){this.player?.toggleMute()}seek(t){this.player?.seek(t)}getState(){return this.player?.getState()||null}destroy(){this.destroyPlayer()}}function yl(t,e,i){return e&&function(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}
|
|
2
2
|
/*!
|
|
3
3
|
* Splide.js
|
|
4
4
|
* Version : 4.1.4
|
|
5
5
|
* License : MIT
|
|
6
6
|
* Copyright: 2022 Naotoshi Fujita
|
|
7
|
-
*/var El="(prefers-reduced-motion: reduce)",Tl={CREATED:1,MOUNTED:2,IDLE:3,MOVING:4,SCROLLING:5,DRAGGING:6,DESTROYED:7};function Sl(t){t.length=0}function bl(t,e,i){return Array.prototype.slice.call(t,e,i)}function Al(t){return t.bind.apply(t,[null].concat(bl(arguments,1)))}var Ll=setTimeout,Il=function(){};function Rl(t){return requestAnimationFrame(t)}function kl(t,e){return typeof e===t}function _l(t){return!xl(t)&&kl("object",t)}var Dl=Array.isArray,wl=Al(kl,"function"),Pl=Al(kl,"string"),Cl=Al(kl,"undefined");function xl(t){return null===t}function Ml(t){try{return t instanceof(t.ownerDocument.defaultView||window).HTMLElement}catch(t){return!1}}function Ol(t){return Dl(t)?t:[t]}function Fl(t,e){Ol(t).forEach(e)}function Nl(t,e){return t.indexOf(e)>-1}function Bl(t,e){return t.push.apply(t,Ol(e)),t}function Ul(t,e,i){t&&Fl(e,function(e){e&&t.classList[i?"add":"remove"](e)})}function $l(t,e){Ul(t,Pl(e)?e.split(" "):e,!0)}function Gl(t,e){Fl(e,t.appendChild.bind(t))}function Kl(t,e){Fl(t,function(t){var i=(e||t).parentNode;i&&i.insertBefore(t,e)})}function Hl(t,e){return Ml(t)&&(t.msMatchesSelector||t.matches).call(t,e)}function Vl(t,e){var i=t?bl(t.children):[];return e?i.filter(function(t){return Hl(t,e)}):i}function jl(t,e){return e?Vl(t,e)[0]:t.firstElementChild}var ql=Object.keys;function Yl(t,e,i){return t&&(i?ql(t).reverse():ql(t)).forEach(function(i){"__proto__"!==i&&e(t[i],i)}),t}function Wl(t){return bl(arguments,1).forEach(function(e){Yl(e,function(i,s){t[s]=e[s]})}),t}function zl(t){return bl(arguments,1).forEach(function(e){Yl(e,function(e,i){Dl(e)?t[i]=e.slice():_l(e)?t[i]=zl({},_l(t[i])?t[i]:{},e):t[i]=e})}),t}function Xl(t,e){Fl(e||ql(t),function(e){delete t[e]})}function Ql(t,e){Fl(t,function(t){Fl(e,function(e){t&&t.removeAttribute(e)})})}function Zl(t,e,i){_l(e)?Yl(e,function(e,i){Zl(t,i,e)}):Fl(t,function(t){xl(i)||""===i?Ql(t,e):t.setAttribute(e,String(i))})}function Jl(t,e,i){var s=document.createElement(t);return e&&(Pl(e)?$l(s,e):Zl(s,e)),i&&Gl(i,s),s}function td(t,e,i){if(Cl(i))return getComputedStyle(t)[e];xl(i)||(t.style[e]=""+i)}function ed(t,e){td(t,"display",e)}function id(t){t.setActive&&t.setActive()||t.focus({preventScroll:!0})}function sd(t,e){return t.getAttribute(e)}function rd(t,e){return t&&t.classList.contains(e)}function nd(t){return t.getBoundingClientRect()}function ad(t){Fl(t,function(t){t&&t.parentNode&&t.parentNode.removeChild(t)})}function od(t){return jl((new DOMParser).parseFromString(t,"text/html").body)}function ld(t,e){t.preventDefault(),e&&(t.stopPropagation(),t.stopImmediatePropagation())}function dd(t,e){return t&&t.querySelector(e)}function hd(t,e){return e?bl(t.querySelectorAll(e)):[]}function cd(t,e){Ul(t,e,!1)}function ud(t){return t.timeStamp}function fd(t){return Pl(t)?t:t?t+"px":""}var gd="splide",md="data-"+gd;function pd(t,e){if(!t)throw new Error("["+gd+"] "+(e||""))}var vd=Math.min,yd=Math.max,Ed=Math.floor,Td=Math.ceil,Sd=Math.abs;function bd(t,e,i){return Sd(t-e)<i}function Ad(t,e,i,s){var r=vd(e,i),n=yd(e,i);return s?r<t&&t<n:r<=t&&t<=n}function Ld(t,e,i){var s=vd(e,i),r=yd(e,i);return vd(yd(s,t),r)}function Id(t){return+(t>0)-+(t<0)}function Rd(t,e){return Fl(e,function(e){t=t.replace("%s",""+e)}),t}function kd(t){return t<10?"0"+t:""+t}var _d={};function Dd(){var t=[];function e(t,e,i){Fl(t,function(t){t&&Fl(e,function(e){e.split(" ").forEach(function(e){var s=e.split(".");i(t,s[0],s[1])})})})}return{bind:function(i,s,r,n){e(i,s,function(e,i,s){var a="addEventListener"in e,o=a?e.removeEventListener.bind(e,i,r,n):e.removeListener.bind(e,r);a?e.addEventListener(i,r,n):e.addListener(r),t.push([e,i,s,r,o])})},unbind:function(i,s,r){e(i,s,function(e,i,s){t=t.filter(function(t){return!!(t[0]!==e||t[1]!==i||t[2]!==s||r&&t[3]!==r)||(t[4](),!1)})})},dispatch:function(t,e,i){var s,r=!0;return"function"==typeof CustomEvent?s=new CustomEvent(e,{bubbles:r,detail:i}):(s=document.createEvent("CustomEvent")).initCustomEvent(e,r,!1,i),t.dispatchEvent(s),s},destroy:function(){t.forEach(function(t){t[4]()}),Sl(t)}}}var wd="mounted",Pd="ready",Cd="move",xd="moved",Md="click",Od="active",Fd="inactive",Nd="visible",Bd="hidden",Ud="refresh",$d="updated",Gd="resize",Kd="resized",Hd="scroll",Vd="scrolled",jd="destroy",qd="arrows:mounted",Yd="navigation:mounted",Wd="autoplay:play",zd="autoplay:pause",Xd="lazyload:loaded",Qd="sk",Zd="sh",Jd="ei";function th(t){var e=t?t.event.bus:document.createDocumentFragment(),i=Dd();return t&&t.event.on(jd,i.destroy),Wl(i,{bus:e,on:function(t,s){i.bind(e,Ol(t).join(" "),function(t){s.apply(s,Dl(t.detail)?t.detail:[])})},off:Al(i.unbind,e),emit:function(t){i.dispatch(e,t,bl(arguments,1))}})}function eh(t,e,i,s){var r,n,a=Date.now,o=0,l=!0,d=0;function h(){if(!l){if(o=t?vd((a()-r)/t,1):1,i&&i(o),o>=1&&(e(),r=a(),s&&++d>=s))return c();n=Rl(h)}}function c(){l=!0}function u(){n&&cancelAnimationFrame(n),o=0,n=0,l=!0}return{start:function(e){e||u(),r=a()-(e?o*t:0),l=!1,n=Rl(h)},rewind:function(){r=a(),o=0,i&&i(o)},pause:c,cancel:u,set:function(e){t=e},isPaused:function(){return l}}}var ih="Arrow",sh=ih+"Left",rh=ih+"Right",nh=ih+"Up",ah=ih+"Down",oh="ttb",lh={width:["height"],left:["top","right"],right:["bottom","left"],x:["y"],X:["Y"],Y:["X"],ArrowLeft:[nh,rh],ArrowRight:[ah,sh]};var dh="role",hh="tabindex",ch="aria-",uh=ch+"controls",fh=ch+"current",gh=ch+"selected",mh=ch+"label",ph=ch+"labelledby",vh=ch+"hidden",yh=ch+"orientation",Eh=ch+"roledescription",Th=ch+"live",Sh=ch+"busy",bh=ch+"atomic",Ah=[dh,hh,"disabled",uh,fh,mh,ph,vh,yh,Eh],Lh=gd+"__",Ih="is-",Rh=gd,kh=Lh+"track",_h=Lh+"list",Dh=Lh+"slide",wh=Dh+"--clone",Ph=Dh+"__container",Ch=Lh+"arrows",xh=Lh+"arrow",Mh=xh+"--prev",Oh=xh+"--next",Fh=Lh+"pagination",Nh=Fh+"__page",Bh=Lh+"progress"+"__bar",Uh=Lh+"toggle",$h=Lh+"sr",Gh=Ih+"initialized",Kh=Ih+"active",Hh=Ih+"prev",Vh=Ih+"next",jh=Ih+"visible",qh=Ih+"loading",Yh=Ih+"focus-in",Wh=Ih+"overflow",zh=[Kh,jh,Hh,Vh,qh,Yh,Wh],Xh={slide:Dh,clone:wh,arrows:Ch,arrow:xh,prev:Mh,next:Oh,pagination:Fh,page:Nh,spinner:Lh+"spinner"};var Qh="touchstart mousedown",Zh="touchmove mousemove",Jh="touchend touchcancel mouseup click";var tc="slide",ec="loop",ic="fade";function sc(t,e,i,s){var r,n=th(t),a=n.on,o=n.emit,l=n.bind,d=t.Components,h=t.root,c=t.options,u=c.isNavigation,f=c.updateOnMove,g=c.i18n,m=c.pagination,p=c.slideFocus,v=d.Direction.resolve,y=sd(s,"style"),E=sd(s,mh),T=i>-1,S=jl(s,"."+Ph);function b(){var r=t.splides.map(function(t){var i=t.splide.Components.Slides.getAt(e);return i?i.slide.id:""}).join(" ");Zl(s,mh,Rd(g.slideX,(T?i:e)+1)),Zl(s,uh,r),Zl(s,dh,p?"button":""),p&&Ql(s,Eh)}function A(){r||L()}function L(){if(!r){var i=t.index;(n=I())!==rd(s,Kh)&&(Ul(s,Kh,n),Zl(s,fh,u&&n||""),o(n?Od:Fd,R)),function(){var e=function(){if(t.is(ic))return I();var e=nd(d.Elements.track),i=nd(s),r=v("left",!0),n=v("right",!0);return Ed(e[r])<=Td(i[r])&&Ed(i[n])<=Td(e[n])}(),i=!e&&(!I()||T);t.state.is([4,5])||Zl(s,vh,i||"");Zl(hd(s,c.focusableNodes||""),hh,i?-1:""),p&&Zl(s,hh,i?-1:0);e!==rd(s,jh)&&(Ul(s,jh,e),o(e?Nd:Bd,R));if(!e&&document.activeElement===s){var r=d.Slides.getAt(t.index);r&&id(r.slide)}}(),Ul(s,Hh,e===i-1),Ul(s,Vh,e===i+1)}var n}function I(){var s=t.index;return s===e||c.cloneStatus&&s===i}var R={index:e,slideIndex:i,slide:s,container:S,isClone:T,mount:function(){T||(s.id=h.id+"-slide"+kd(e+1),Zl(s,dh,m?"tabpanel":"group"),Zl(s,Eh,g.slide),Zl(s,mh,E||Rd(g.slideLabel,[e+1,t.length]))),l(s,"click",Al(o,Md,R)),l(s,"keydown",Al(o,Qd,R)),a([xd,Zd,Vd],L),a(Yd,b),f&&a(Cd,A)},destroy:function(){r=!0,n.destroy(),cd(s,zh),Ql(s,Ah),Zl(s,"style",y),Zl(s,mh,E||"")},update:L,style:function(t,e,i){td(i&&S||s,t,e)},isWithin:function(i,s){var r=Sd(i-e);return T||!c.rewind&&!t.is(ec)||(r=vd(r,t.length-r)),r<=s}};return R}var rc=md+"-interval";var nc={passive:!1,capture:!0};var ac={Spacebar:" ",Right:rh,Left:sh,Up:nh,Down:ah};function oc(t){return t=Pl(t)?t:t.key,ac[t]||t}var lc="keydown";var dc=md+"-lazy",hc=dc+"-srcset",cc="["+dc+"], ["+hc+"]";var uc=[" ","Enter"];var fc=Object.freeze({__proto__:null,Media:function(t,e,i){var s=t.state,r=i.breakpoints||{},n=i.reducedMotion||{},a=Dd(),o=[];function l(t){t&&a.destroy()}function d(t,e){var i=matchMedia(e);a.bind(i,"change",h),o.push([t,i])}function h(){var e=s.is(7),r=i.direction,n=o.reduce(function(t,e){return zl(t,e[1].matches?e[0]:{})},{});Xl(i),c(n),i.destroy?t.destroy("completely"===i.destroy):e?(l(!0),t.mount()):r!==i.direction&&t.refresh()}function c(e,r,n){zl(i,e),r&&zl(Object.getPrototypeOf(i),e),!n&&s.is(1)||t.emit($d,i)}return{setup:function(){var t="min"===i.mediaQuery;ql(r).sort(function(e,i){return t?+e-+i:+i-+e}).forEach(function(e){d(r[e],"("+(t?"min":"max")+"-width:"+e+"px)")}),d(n,El),h()},destroy:l,reduce:function(t){matchMedia(El).matches&&(t?zl(i,n):Xl(i,ql(n)))},set:c}},Direction:function(t,e,i){return{resolve:function(t,e,s){var r="rtl"!==(s=s||i.direction)||e?s===oh?0:-1:1;return lh[t]&&lh[t][r]||t.replace(/width|left|right/i,function(t,e){var i=lh[t.toLowerCase()][r]||t;return e>0?i.charAt(0).toUpperCase()+i.slice(1):i})},orient:function(t){return t*("rtl"===i.direction?1:-1)}}},Elements:function(t,e,i){var s,r,n,a=th(t),o=a.on,l=a.bind,d=t.root,h=i.i18n,c={},u=[],f=[],g=[];function m(){s=y("."+kh),r=jl(s,"."+_h),pd(s&&r,"A track/list element is missing."),Bl(u,Vl(r,"."+Dh+":not(."+wh+")")),Yl({arrows:Ch,pagination:Fh,prev:Mh,next:Oh,bar:Bh,toggle:Uh},function(t,e){c[e]=y("."+t)}),Wl(c,{root:d,track:s,list:r,slides:u}),function(){var t=d.id||(n=gd,""+n+kd(_d[n]=(_d[n]||0)+1)),e=i.role;var n;d.id=t,s.id=s.id||t+"-track",r.id=r.id||t+"-list",!sd(d,dh)&&"SECTION"!==d.tagName&&e&&Zl(d,dh,e);Zl(d,Eh,h.carousel),Zl(r,dh,"presentation")}(),v()}function p(t){var e=Ah.concat("style");Sl(u),cd(d,f),cd(s,g),Ql([s,r],e),Ql(d,t?e:["style",Eh])}function v(){cd(d,f),cd(s,g),f=E(Rh),g=E(kh),$l(d,f),$l(s,g),Zl(d,mh,i.label),Zl(d,ph,i.labelledby)}function y(t){var e=dd(d,t);return e&&function(t,e){if(wl(t.closest))return t.closest(e);for(var i=t;i&&1===i.nodeType&&!Hl(i,e);)i=i.parentElement;return i}(e,"."+Rh)===d?e:void 0}function E(t){return[t+"--"+i.type,t+"--"+i.direction,i.drag&&t+"--draggable",i.isNavigation&&t+"--nav",t===Rh&&Kh]}return Wl(c,{setup:m,mount:function(){o(Ud,p),o(Ud,m),o($d,v),l(document,Qh+" keydown",function(t){n="keydown"===t.type},{capture:!0}),l(d,"focusin",function(){Ul(d,Yh,!!n)})},destroy:p})},Slides:function(t,e,i){var s=th(t),r=s.on,n=s.emit,a=s.bind,o=e.Elements,l=o.slides,d=o.list,h=[];function c(){l.forEach(function(t,e){f(t,e,-1)})}function u(){m(function(t){t.destroy()}),Sl(h)}function f(e,i,s){var r=sc(t,i,s,e);r.mount(),h.push(r),h.sort(function(t,e){return t.index-e.index})}function g(t){return t?p(function(t){return!t.isClone}):h}function m(t,e){g(e).forEach(t)}function p(t){return h.filter(wl(t)?t:function(e){return Pl(t)?Hl(e.slide,t):Nl(Ol(t),e.index)})}return{mount:function(){c(),r(Ud,u),r(Ud,c)},destroy:u,update:function(){m(function(t){t.update()})},register:f,get:g,getIn:function(t){var s=e.Controller,r=s.toIndex(t),n=s.hasFocus()?1:i.perPage;return p(function(t){return Ad(t.index,r,r+n-1)})},getAt:function(t){return p(t)[0]},add:function(t,e){Fl(t,function(t){if(Pl(t)&&(t=od(t)),Ml(t)){var s=l[e];s?Kl(t,s):Gl(d,t),$l(t,i.classes.slide),r=t,o=Al(n,Gd),h=hd(r,"img"),(c=h.length)?h.forEach(function(t){a(t,"load error",function(){--c||o()})}):o()}var r,o,h,c}),n(Ud)},remove:function(t){ad(p(t).map(function(t){return t.slide})),n(Ud)},forEach:m,filter:p,style:function(t,e,i){m(function(s){s.style(t,e,i)})},getLength:function(t){return t?l.length:h.length},isEnough:function(){return h.length>i.perPage}}},Layout:function(t,e,i){var s,r,n,a=th(t),o=a.on,l=a.bind,d=a.emit,h=e.Slides,c=e.Direction.resolve,u=e.Elements,f=u.root,g=u.track,m=u.list,p=h.getAt,v=h.style;function y(){s=i.direction===oh,td(f,"maxWidth",fd(i.width)),td(g,c("paddingLeft"),T(!1)),td(g,c("paddingRight"),T(!0)),E(!0)}function E(t){var e=nd(f);(t||r.width!==e.width||r.height!==e.height)&&(td(g,"height",function(){var t="";s&&(pd(t=S(),"height or heightRatio is missing."),t="calc("+t+" - "+T(!1)+" - "+T(!0)+")");return t}()),v(c("marginRight"),fd(i.gap)),v("width",i.autoWidth?null:fd(i.fixedWidth)||(s?"":b())),v("height",fd(i.fixedHeight)||(s?i.autoHeight?null:b():S()),!0),r=e,d(Kd),n!==(n=_())&&(Ul(f,Wh,n),d("overflow",n)))}function T(t){var e=i.padding,s=c(t?"right":"left");return e&&fd(e[s]||(_l(e)?0:e))||"0px"}function S(){return fd(i.height||nd(m).width*i.heightRatio)}function b(){var t=fd(i.gap);return"calc((100%"+(t&&" + "+t)+")/"+(i.perPage||1)+(t&&" - "+t)+")"}function A(){return nd(m)[c("width")]}function L(t,e){var i=p(t||0);return i?nd(i.slide)[c("width")]+(e?0:k()):0}function I(t,e){var i=p(t);if(i){var s=nd(i.slide)[c("right")],r=nd(m)[c("left")];return Sd(s-r)+(e?0:k())}return 0}function R(e){return I(t.length-1)-I(0)+L(0,e)}function k(){var t=p(0);return t&&parseFloat(td(t.slide,c("marginRight")))||0}function _(){return t.is(ic)||R(!0)>A()}return{mount:function(){var t,e;y(),l(window,"resize load",(t=Al(d,Gd),e=eh(0,t,null,1),function(){e.isPaused()&&e.start()})),o([$d,Ud],y),o(Gd,E)},resize:E,listSize:A,slideSize:L,sliderSize:R,totalSize:I,getPadding:function(t){return parseFloat(td(g,c("padding"+(t?"Right":"Left"))))||0},isOverflow:_}},Clones:function(t,e,i){var s,r=th(t),n=r.on,a=e.Elements,o=e.Slides,l=e.Direction.resolve,d=[];function h(){n(Ud,c),n([$d,Gd],f),(s=g())&&(!function(e){var s=o.get().slice(),r=s.length;if(r){for(;s.length<e;)Bl(s,s);Bl(s.slice(-e),s.slice(0,e)).forEach(function(n,l){var h=l<e,c=function(e,s){var r=e.cloneNode(!0);return $l(r,i.classes.clone),r.id=t.root.id+"-clone"+kd(s+1),r}(n.slide,l);h?Kl(c,s[0].slide):Gl(a.list,c),Bl(d,c),o.register(c,l-e+(h?0:r),n.index)})}}(s),e.Layout.resize(!0))}function c(){u(),h()}function u(){ad(d),Sl(d),r.destroy()}function f(){var t=g();s!==t&&(s<t||!t)&&r.emit(Ud)}function g(){var s=i.clones;if(t.is(ec)){if(Cl(s)){var r=i[l("fixedWidth")]&&e.Layout.slideSize(0);s=r&&Td(nd(a.track)[l("width")]/r)||i[l("autoWidth")]&&t.length||2*i.perPage}}else s=0;return s}return{mount:h,destroy:u}},Move:function(t,e,i){var s,r=th(t),n=r.on,a=r.emit,o=t.state.set,l=e.Layout,d=l.slideSize,h=l.getPadding,c=l.totalSize,u=l.listSize,f=l.sliderSize,g=e.Direction,m=g.resolve,p=g.orient,v=e.Elements,y=v.list,E=v.track;function T(){e.Controller.isBusy()||(e.Scroll.cancel(),S(t.index),e.Slides.update())}function S(t){b(R(t,!0))}function b(i,s){if(!t.is(ic)){var r=s?i:function(i){if(t.is(ec)){var s=I(i),r=s>e.Controller.getEnd();(s<0||r)&&(i=A(i,r))}return i}(i);td(y,"transform","translate"+m("X")+"("+r+"px)"),i!==r&&a(Zd)}}function A(t,e){var i=t-_(e),s=f();return t-=p(s*(Td(Sd(i)/s)||1))*(e?1:-1)}function L(){b(k(),!0),s.cancel()}function I(t){for(var i=e.Slides.get(),s=0,r=1/0,n=0;n<i.length;n++){var a=i[n].index,o=Sd(R(a,!0)-t);if(!(o<=r))break;r=o,s=a}return s}function R(e,s){var r=p(c(e-1)-function(t){var e=i.focus;return"center"===e?(u()-d(t,!0))/2:+e*d(t)||0}(e));return s?function(e){i.trimSpace&&t.is(tc)&&(e=Ld(e,0,p(f(!0)-u())));return e}(r):r}function k(){var t=m("left");return nd(y)[t]-nd(E)[t]+p(h(!1))}function _(t){return R(t?e.Controller.getEnd():0,!!i.trimSpace)}return{mount:function(){s=e.Transition,n([wd,Kd,$d,Ud],T)},move:function(t,e,i,r){var n,l;t!==e&&(n=t>i,l=p(A(k(),n)),n?l>=0:l<=y[m("scrollWidth")]-nd(E)[m("width")])&&(L(),b(A(k(),t>i),!0)),o(4),a(Cd,e,i,t),s.start(e,function(){o(3),a(xd,e,i,t),r&&r()})},jump:S,translate:b,shift:A,cancel:L,toIndex:I,toPosition:R,getPosition:k,getLimit:_,exceededLimit:function(t,e){e=Cl(e)?k():e;var i=!0!==t&&p(e)<p(_(!1)),s=!1!==t&&p(e)>p(_(!0));return i||s},reposition:T}},Controller:function(t,e,i){var s,r,n,a,o=th(t),l=o.on,d=o.emit,h=e.Move,c=h.getPosition,u=h.getLimit,f=h.toPosition,g=e.Slides,m=g.isEnough,p=g.getLength,v=i.omitEnd,y=t.is(ec),E=t.is(tc),T=Al(R,!1),S=Al(R,!0),b=i.start||0,A=b;function L(){r=p(!0),n=i.perMove,a=i.perPage,s=D();var t=Ld(b,0,v?s:r-1);t!==b&&(b=t,h.reposition())}function I(){s!==D()&&d(Jd)}function R(t,e){var i=n||(x()?1:a),r=k(b+i*(t?-1:1),b,!(n||x()));return-1===r&&E&&!bd(c(),u(!t),1)?t?0:s:e?r:_(r)}function k(e,o,l){if(m()||x()){var d=function(e){if(E&&"move"===i.trimSpace&&e!==b)for(var s=c();s===f(e,!0)&&Ad(e,0,t.length-1,!i.rewind);)e<b?--e:++e;return e}(e);d!==e&&(o=e,e=d,l=!1),e<0||e>s?e=n||!Ad(0,e,o,!0)&&!Ad(s,o,e,!0)?y?l?e<0?-(r%a||a):r:e:i.rewind?e<0?s:0:-1:w(P(e)):l&&e!==o&&(e=w(P(o)+(e<o?-1:1)))}else e=-1;return e}function _(t){return y?(t+r)%r||0:t}function D(){for(var t=r-(x()||y&&n?1:a);v&&t-- >0;)if(f(r-1,!0)!==f(t,!0)){t++;break}return Ld(t,0,r-1)}function w(t){return Ld(x()?t:a*t,0,s)}function P(t){return x()?vd(t,s):Ed((t>=s?r-1:t)/a)}function C(t){t!==b&&(A=b,b=t)}function x(){return!Cl(i.focus)||i.isNavigation}function M(){return t.state.is([4,5])&&!!i.waitForTransition}return{mount:function(){L(),l([$d,Ud,Jd],L),l(Kd,I)},go:function(t,e,i){if(!M()){var r=function(t){var e=b;if(Pl(t)){var i=t.match(/([+\-<>])(\d+)?/)||[],r=i[1],n=i[2];"+"===r||"-"===r?e=k(b+ +(""+r+(+n||1)),b):">"===r?e=n?w(+n):T(!0):"<"===r&&(e=S(!0))}else e=y?t:Ld(t,0,s);return e}(t),n=_(r);n>-1&&(e||n!==b)&&(C(n),h.move(r,n,A,i))}},scroll:function(t,i,r,n){e.Scroll.scroll(t,i,r,function(){var t=_(h.toIndex(c()));C(v?vd(t,s):t),n&&n()})},getNext:T,getPrev:S,getAdjacent:R,getEnd:D,setIndex:C,getIndex:function(t){return t?A:b},toIndex:w,toPage:P,toDest:function(t){var e=h.toIndex(t);return E?Ld(e,0,s):e},hasFocus:x,isBusy:M}},Arrows:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.bind,l=n.emit,d=i.classes,h=i.i18n,c=e.Elements,u=e.Controller,f=c.arrows,g=c.track,m=f,p=c.prev,v=c.next,y={};function E(){!function(){var t=i.arrows;!t||p&&v||(m=f||Jl("div",d.arrows),p=A(!0),v=A(!1),s=!0,Gl(m,[p,v]),!f&&Kl(m,g));p&&v&&(Wl(y,{prev:p,next:v}),ed(m,t?"":"none"),$l(m,r=Ch+"--"+i.direction),t&&(a([wd,xd,Ud,Vd,Jd],L),o(v,"click",Al(b,">")),o(p,"click",Al(b,"<")),L(),Zl([p,v],uh,g.id),l(qd,p,v)))}(),a($d,T)}function T(){S(),E()}function S(){n.destroy(),cd(m,r),s?(ad(f?[p,v]:m),p=v=null):Ql([p,v],Ah)}function b(t){u.go(t,!0)}function A(t){return od('<button class="'+d.arrow+" "+(t?d.prev:d.next)+'" type="button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40" focusable="false"><path d="'+(i.arrowPath||"m15.5 0.932-4.3 4.38 14.5 14.6-14.5 14.5 4.3 4.4 14.6-14.6 4.4-4.3-4.4-4.4-14.6-14.6z")+'" />')}function L(){if(p&&v){var e=t.index,i=u.getPrev(),s=u.getNext(),r=i>-1&&e<i?h.last:h.prev,n=s>-1&&e>s?h.first:h.next;p.disabled=i<0,v.disabled=s<0,Zl(p,mh,r),Zl(v,mh,n),l("arrows:updated",p,v,i,s)}}return{arrows:y,mount:E,destroy:S,update:L}},Autoplay:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.bind,l=n.emit,d=eh(i.interval,t.go.bind(t,">"),function(t){var e=c.bar;e&&td(e,"width",100*t+"%"),l("autoplay:playing",t)}),h=d.isPaused,c=e.Elements,u=e.Elements,f=u.root,g=u.toggle,m=i.autoplay,p="pause"===m;function v(){h()&&e.Slides.isEnough()&&(d.start(!i.resetProgress),r=s=p=!1,T(),l(Wd))}function y(t){void 0===t&&(t=!0),p=!!t,T(),h()||(d.pause(),l(zd))}function E(){p||(s||r?y(!1):v())}function T(){g&&(Ul(g,Kh,!p),Zl(g,mh,i.i18n[p?"play":"pause"]))}function S(t){var s=e.Slides.getAt(t);d.set(s&&+sd(s.slide,rc)||i.interval)}return{mount:function(){m&&(!function(){i.pauseOnHover&&o(f,"mouseenter mouseleave",function(t){s="mouseenter"===t.type,E()});i.pauseOnFocus&&o(f,"focusin focusout",function(t){r="focusin"===t.type,E()});g&&o(g,"click",function(){p?v():y(!0)});a([Cd,Hd,Ud],d.rewind),a(Cd,S)}(),g&&Zl(g,uh,c.track.id),p||v(),T())},destroy:d.cancel,play:v,pause:y,isPaused:h}},Cover:function(t,e,i){var s=th(t).on;function r(t){e.Slides.forEach(function(e){var i=jl(e.container||e.slide,"img");i&&i.src&&n(t,i,e)})}function n(t,e,i){i.style("background",t?'center/cover no-repeat url("'+e.src+'")':"",!0),ed(e,t?"none":"")}return{mount:function(){i.cover&&(s(Xd,Al(n,!0)),s([wd,$d,Ud],Al(r,!0)))},destroy:Al(r,!1)}},Scroll:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.emit,l=t.state.set,d=e.Move,h=d.getPosition,c=d.getLimit,u=d.exceededLimit,f=d.translate,g=t.is(tc),m=1;function p(t,i,n,a,c){var f=h();if(E(),n&&(!g||!u())){var p=e.Layout.sliderSize(),T=Id(t)*p*Ed(Sd(t)/p)||0;t=d.toPosition(e.Controller.toDest(t%p))+T}var S=bd(f,t,1);m=1,i=S?0:i||yd(Sd(t-f)/1.5,800),r=a,s=eh(i,v,Al(y,f,t,c),1),l(5),o(Hd),s.start()}function v(){l(3),r&&r(),o(Vd)}function y(t,e,s,n){var a,o,l=h(),d=(t+(e-t)*(a=n,(o=i.easingFunc)?o(a):1-Math.pow(1-a,4))-l)*m;f(l+d),g&&!s&&u()&&(m*=.6,Sd(d)<10&&p(c(u(!0)),600,!1,r,!0))}function E(){s&&s.cancel()}function T(){s&&!s.isPaused()&&(E(),v())}return{mount:function(){a(Cd,E),a([$d,Ud],T)},destroy:E,scroll:p,cancel:T}},Drag:function(t,e,i){var s,r,n,a,o,l,d,h,c=th(t),u=c.on,f=c.emit,g=c.bind,m=c.unbind,p=t.state,v=e.Move,y=e.Scroll,E=e.Controller,T=e.Elements.track,S=e.Media.reduce,b=e.Direction,A=b.resolve,L=b.orient,I=v.getPosition,R=v.exceededLimit,k=!1;function _(){var t=i.drag;U(!t),a="free"===t}function D(t){if(l=!1,!d){var e=B(t);s=t.target,r=i.noDrag,Hl(s,"."+Nh+", ."+xh)||r&&Hl(s,r)||!e&&t.button||(E.isBusy()?ld(t,!0):(h=e?T:window,o=p.is([4,5]),n=null,g(h,Zh,w,nc),g(h,Jh,P,nc),v.cancel(),y.cancel(),x(t)))}var s,r}function w(e){if(p.is(6)||(p.set(6),f("drag")),e.cancelable)if(o){v.translate(s+M(e)/(k&&t.is(tc)?5:1));var r=O(e)>200,n=k!==(k=R());(r||n)&&x(e),l=!0,f("dragging"),ld(e)}else(function(t){return Sd(M(t))>Sd(M(t,!0))})(e)&&(o=function(t){var e=i.dragMinThreshold,s=_l(e),r=s&&e.mouse||0,n=(s?e.touch:+e)||10;return Sd(M(t))>(B(t)?n:r)}(e),ld(e))}function P(s){p.is(6)&&(p.set(3),f("dragged")),o&&(!function(s){var r=function(e){if(t.is(ec)||!k){var i=O(e);if(i&&i<200)return M(e)/i}return 0}(s),n=function(t){return I()+Id(t)*vd(Sd(t)*(i.flickPower||600),a?1/0:e.Layout.listSize()*(i.flickMaxPages||1))}(r),o=i.rewind&&i.rewindByDrag;S(!1),a?E.scroll(n,0,i.snap):t.is(ic)?E.go(L(Id(r))<0?o?"<":"-":o?">":"+"):t.is(tc)&&k&&o?E.go(R(!0)?">":"<"):E.go(E.toDest(n),!0);S(!0)}(s),ld(s)),m(h,Zh,w),m(h,Jh,P),o=!1}function C(t){!d&&l&&ld(t,!0)}function x(t){n=r,r=t,s=I()}function M(t,e){return N(t,e)-N(F(t),e)}function O(t){return ud(t)-ud(F(t))}function F(t){return r===t&&n||r}function N(t,e){return(B(t)?t.changedTouches[0]:t)["page"+A(e?"Y":"X")]}function B(t){return"undefined"!=typeof TouchEvent&&t instanceof TouchEvent}function U(t){d=t}return{mount:function(){g(T,Zh,Il,nc),g(T,Jh,Il,nc),g(T,Qh,D,nc),g(T,"click",C,{capture:!0}),g(T,"dragstart",ld),u([wd,$d],_)},disable:U,isDragging:function(){return o}}},Keyboard:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.bind,l=n.unbind,d=t.root,h=e.Direction.resolve;function c(){var t=i.keyboard;t&&(s="global"===t?window:d,o(s,lc,g))}function u(){l(s,lc)}function f(){var t=r;r=!0,Ll(function(){r=t})}function g(e){if(!r){var i=oc(e);i===h(sh)?t.go("<"):i===h(rh)&&t.go(">")}}return{mount:function(){c(),a($d,u),a($d,c),a(Cd,f)},destroy:u,disable:function(t){r=t}}},LazyLoad:function(t,e,i){var s=th(t),r=s.on,n=s.off,a=s.bind,o=s.emit,l="sequential"===i.lazyLoad,d=[xd,Vd],h=[];function c(){Sl(h),e.Slides.forEach(function(t){hd(t.slide,cc).forEach(function(e){var s=sd(e,dc),r=sd(e,hc);if(s!==e.src||r!==e.srcset){var n=i.classes.spinner,a=e.parentElement,o=jl(a,"."+n)||Jl("span",n,a);h.push([e,t,o]),e.src||ed(e,"none")}})}),l?m():(n(d),r(d,u),u())}function u(){(h=h.filter(function(e){var s=i.perPage*((i.preloadPages||1)+1)-1;return!e[1].isWithin(t.index,s)||f(e)})).length||n(d)}function f(t){var e=t[0];$l(t[1].slide,qh),a(e,"load error",Al(g,t)),Zl(e,"src",sd(e,dc)),Zl(e,"srcset",sd(e,hc)),Ql(e,dc),Ql(e,hc)}function g(t,e){var i=t[0],s=t[1];cd(s.slide,qh),"error"!==e.type&&(ad(t[2]),ed(i,""),o(Xd,i,s),o(Gd)),l&&m()}function m(){h.length&&f(h.shift())}return{mount:function(){i.lazyLoad&&(c(),r(Ud,c))},destroy:Al(Sl,h),check:u}},Pagination:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.emit,l=n.bind,d=e.Slides,h=e.Elements,c=e.Controller,u=c.hasFocus,f=c.getIndex,g=c.go,m=e.Direction.resolve,p=h.pagination,v=[];function y(){s&&(ad(p?bl(s.children):s),cd(s,r),Sl(v),s=null),n.destroy()}function E(t){g(">"+t,!0)}function T(t,e){var i=v.length,s=oc(e),r=S(),n=-1;s===m(rh,!1,r)?n=++t%i:s===m(sh,!1,r)?n=(--t+i)%i:"Home"===s?n=0:"End"===s&&(n=i-1);var a=v[n];a&&(id(a.button),g(">"+n),ld(e,!0))}function S(){return i.paginationDirection||i.direction}function b(t){return v[c.toPage(t)]}function A(){var t=b(f(!0)),e=b(f());if(t){var i=t.button;cd(i,Kh),Ql(i,gh),Zl(i,hh,-1)}if(e){var r=e.button;$l(r,Kh),Zl(r,gh,!0),Zl(r,hh,"")}o("pagination:updated",{list:s,items:v},t,e)}return{items:v,mount:function e(){y(),a([$d,Ud,Jd],e);var n=i.pagination;p&&ed(p,n?"":"none"),n&&(a([Cd,Hd,Vd],A),function(){var e=t.length,n=i.classes,a=i.i18n,o=i.perPage,f=u()?c.getEnd()+1:Td(e/o);$l(s=p||Jl("ul",n.pagination,h.track.parentElement),r=Fh+"--"+S()),Zl(s,dh,"tablist"),Zl(s,mh,a.select),Zl(s,yh,S()===oh?"vertical":"");for(var g=0;g<f;g++){var m=Jl("li",null,s),y=Jl("button",{class:n.page,type:"button"},m),b=d.getIn(g).map(function(t){return t.slide.id}),A=!u()&&o>1?a.pageX:a.slideX;l(y,"click",Al(E,g)),i.paginationKeyboard&&l(y,"keydown",Al(T,g)),Zl(m,dh,"presentation"),Zl(y,dh,"tab"),Zl(y,uh,b.join(" ")),Zl(y,mh,Rd(A,g+1)),Zl(y,hh,-1),v.push({li:m,button:y,page:g})}}(),A(),o("pagination:mounted",{list:s,items:v},b(t.index)))},destroy:y,getAt:b,update:A}},Sync:function(t,e,i){var s=i.isNavigation,r=i.slideFocus,n=[];function a(){var e,i;t.splides.forEach(function(e){e.isParent||(l(t,e.splide),l(e.splide,t))}),s&&(e=th(t),(i=e.on)(Md,h),i(Qd,c),i([wd,$d],d),n.push(e),e.emit(Yd,t.splides))}function o(){n.forEach(function(t){t.destroy()}),Sl(n)}function l(t,e){var i=th(t);i.on(Cd,function(t,i,s){e.go(e.is(ec)?s:t)}),n.push(i)}function d(){Zl(e.Elements.list,yh,i.direction===oh?"vertical":"")}function h(e){t.go(e.index)}function c(t,e){Nl(uc,oc(e))&&(h(t),ld(e))}return{setup:Al(e.Media.set,{slideFocus:Cl(r)?s:r},!0),mount:a,destroy:o,remount:function(){o(),a()}}},Wheel:function(t,e,i){var s=th(t).bind,r=0;function n(s){if(s.cancelable){var n=s.deltaY,a=n<0,o=ud(s),l=i.wheelMinThreshold||0,d=i.wheelSleep||0;Sd(n)>l&&o-r>d&&(t.go(a?"<":">"),r=o),function(s){return!i.releaseWheel||t.state.is(4)||-1!==e.Controller.getAdjacent(s)}(a)&&ld(s)}}return{mount:function(){i.wheel&&s(e.Elements.track,"wheel",n,nc)}}},Live:function(t,e,i){var s=th(t).on,r=e.Elements.track,n=i.live&&!i.isNavigation,a=Jl("span",$h),o=eh(90,Al(l,!1));function l(t){Zl(r,Sh,t),t?(Gl(r,a),o.start()):(ad(a),o.cancel())}function d(t){n&&Zl(r,Th,t?"off":"polite")}return{mount:function(){n&&(d(!e.Autoplay.isPaused()),Zl(r,bh,!0),a.textContent="…",s(Wd,Al(d,!0)),s(zd,Al(d,!1)),s([xd,Vd],Al(l,!0)))},disable:d,destroy:function(){Ql(r,[Th,bh,Sh]),ad(a)}}}}),gc={type:"slide",role:"region",speed:400,perPage:1,cloneStatus:!0,arrows:!0,pagination:!0,paginationKeyboard:!0,interval:5e3,pauseOnHover:!0,pauseOnFocus:!0,resetProgress:!0,easing:"cubic-bezier(0.25, 1, 0.5, 1)",drag:!0,direction:"ltr",trimSpace:!0,focusableNodes:"a, button, textarea, input, select, iframe",live:!0,classes:Xh,i18n:{prev:"Previous slide",next:"Next slide",first:"Go to first slide",last:"Go to last slide",slideX:"Go to slide %s",pageX:"Go to page %s",play:"Start autoplay",pause:"Pause autoplay",carousel:"carousel",slide:"slide",select:"Select a slide to show",slideLabel:"%s of %s"},reducedMotion:{speed:0,rewindSpeed:0,autoplay:"pause"}};function mc(t,e,i){var s=e.Slides;function r(){s.forEach(function(t){t.style("transform","translateX(-"+100*t.index+"%)")})}return{mount:function(){th(t).on([wd,Ud],r)},start:function(t,e){s.style("transition","opacity "+i.speed+"ms "+i.easing),Ll(e)},cancel:Il}}function pc(t,e,i){var s,r=e.Move,n=e.Controller,a=e.Scroll,o=e.Elements.list,l=Al(td,o,"transition");function d(){l(""),a.cancel()}return{mount:function(){th(t).bind(o,"transitionend",function(t){t.target===o&&s&&(d(),s())})},start:function(e,o){var d=r.toPosition(e,!0),h=r.getPosition(),c=function(e){var s=i.rewindSpeed;if(t.is(tc)&&s){var r=n.getIndex(!0),a=n.getEnd();if(0===r&&e>=a||r>=a&&0===e)return s}return i.speed}(e);Sd(d-h)>=1&&c>=1?i.useScroll?a.scroll(d,c,!1,o):(l("transform "+c+"ms "+i.easing),r.translate(d,!0),s=o):(r.jump(e),o())},cancel:d}}var vc=function(){function t(e,i){var s;this.event=th(),this.Components={},this.state=(s=1,{set:function(t){s=t},is:function(t){return Nl(Ol(t),s)}}),this.splides=[],this._o={},this._E={};var r=Pl(e)?dd(document,e):e;pd(r,r+" is invalid."),this.root=r,i=zl({label:sd(r,mh)||"",labelledby:sd(r,ph)||""},gc,t.defaults,i||{});try{zl(i,JSON.parse(sd(r,md)))}catch(t){pd(!1,"Invalid JSON")}this._o=Object.create(zl({},i))}var e=t.prototype;return e.mount=function(t,e){var i=this,s=this.state,r=this.Components;return pd(s.is([1,7]),"Already mounted!"),s.set(1),this._C=r,this._T=e||this._T||(this.is(ic)?mc:pc),this._E=t||this._E,Yl(Wl({},fc,this._E,{Transition:this._T}),function(t,e){var s=t(i,r,i._o);r[e]=s,s.setup&&s.setup()}),Yl(r,function(t){t.mount&&t.mount()}),this.emit(wd),$l(this.root,Gh),s.set(3),this.emit(Pd),this},e.sync=function(t){return this.splides.push({splide:t}),t.splides.push({splide:this,isParent:!0}),this.state.is(3)&&(this._C.Sync.remount(),t.Components.Sync.remount()),this},e.go=function(t){return this._C.Controller.go(t),this},e.on=function(t,e){return this.event.on(t,e),this},e.off=function(t){return this.event.off(t),this},e.emit=function(t){var e;return(e=this.event).emit.apply(e,[t].concat(bl(arguments,1))),this},e.add=function(t,e){return this._C.Slides.add(t,e),this},e.remove=function(t){return this._C.Slides.remove(t),this},e.is=function(t){return this._o.type===t},e.refresh=function(){return this.emit(Ud),this},e.destroy=function(t){void 0===t&&(t=!0);var e=this.event,i=this.state;return i.is(1)?th(this).on(Pd,this.destroy.bind(this,t)):(Yl(this._C,function(e){e.destroy&&e.destroy(t)},!0),e.emit(jd),e.destroy(),t&&Sl(this.splides),i.set(7)),this},yl(t,[{key:"options",get:function(){return this._o},set:function(t){this._C.Media.set(t,!0,!0)}},{key:"length",get:function(){return this._C.Slides.getLength(!0)}},{key:"index",get:function(){return this._C.Controller.getIndex()}}]),t}(),yc=vc;yc.defaults={},yc.STATES=Tl;class Ec extends HTMLElement{static get observedAttributes(){return["collection-id","api-key","client-id","subscription-id","base-url","autoplay","show-arrows","show-dots","video-settings"]}constructor(){super(),this.splide=null,this.container=null,this.carouselElement=null,this.clientInstance=null,this.connected=!1,this.collectionData=null,this.autoplayTimeoutId=null,this.attachShadow({mode:"open"})}connectedCallback(){this.connected=!0,this.render(),this.initCarousel()}disconnectedCallback(){this.connected=!1,this.destroyCarousel()}attributeChangedCallback(t,e,i){this.connected&&e!==i&&("collection-id"!==t&&"video-settings"!==t||(this.destroyCarousel(),this.initCarousel()),"show-arrows"!==t&&"show-dots"!==t||(this.destroyCarousel(),this.initCarousel()))}getBooleanAttr(t,e){const i=this.getAttribute(t);return null===i?e:"false"!==i}render(){if(!this.shadowRoot)return;const t=document.createElement("style");t.textContent=`\n ${ml}\n .jaaq-collection-player {\n width: 100%;\n max-width: 1400px;\n margin: 0 auto;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n}\n\n.jaaq-collection-loading {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 400px;\n}\n\n.jaaq-collection-spinner {\n width: 50px;\n height: 50px;\n border: 4px solid rgba(0, 123, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-collection-spin 1s linear infinite;\n}\n\n@keyframes jaaq-collection-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n.jaaq-collection-error {\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n text-align: center;\n font-size: 14px;\n margin: 20px;\n}\n\n.jaaq-collection-carousel .splide__track {\n padding: 40px 0;\n}\n\n.jaaq-collection-carousel .splide__slide {\n opacity: 0.7;\n transition: all 0.3s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active {\n opacity: 1;\n}\n\n.jaaq-collection-carousel .splide__slide jaaq-video-player {\n width: 100%;\n max-width: 600px;\n transition: all 0.3s ease;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 800px;\n}\n\n.jaaq-collection-carousel .splide__arrow {\n background: rgba(0, 0, 0, 0.5);\n border: none;\n width: 48px;\n height: 48px;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n transition: all 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 20px;\n}\n\n.jaaq-collection-carousel .splide__arrow:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n}\n\n.jaaq-collection-carousel .splide__arrow:disabled {\n opacity: 0.3;\n cursor: not-allowed;\n}\n\n.jaaq-collection-carousel .splide__arrow svg {\n fill: white;\n width: 20px;\n height: 20px;\n}\n\n.jaaq-collection-carousel .splide__pagination {\n bottom: -30px;\n}\n\n.jaaq-collection-carousel .splide__pagination__page {\n background: #ccc;\n border: none;\n width: 10px;\n height: 10px;\n margin: 0 4px;\n border-radius: 50%;\n transition: all 0.2s;\n cursor: pointer;\n}\n\n.jaaq-collection-carousel .splide__pagination__page.is-active {\n background: white;\n transform: scale(1.3);\n}\n\n@media (max-width: 1024px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 650px;\n }\n}\n\n@media (max-width: 768px) {\n .jaaq-collection-carousel .splide__track {\n padding: 20px 0;\n }\n\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 400px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__arrow {\n width: 40px;\n height: 40px;\n }\n}\n\n@media (max-width: 480px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 100%;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 100%;\n }\n}\n\n .splide__container{box-sizing:border-box;position:relative}.splide__list{backface-visibility:hidden;display:-ms-flexbox;display:flex;height:100%;margin:0!important;padding:0!important}.splide.is-initialized:not(.is-active) .splide__list{display:block}.splide__pagination{-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:center;justify-content:center;margin:0;pointer-events:none}.splide__pagination li{display:inline-block;line-height:1;list-style-type:none;margin:0;pointer-events:auto}.splide:not(.is-overflow) .splide__pagination{display:none}.splide__progress__bar{width:0}.splide{position:relative;visibility:hidden}.splide.is-initialized,.splide.is-rendered{visibility:visible}.splide__slide{backface-visibility:hidden;box-sizing:border-box;-ms-flex-negative:0;flex-shrink:0;list-style-type:none!important;margin:0;position:relative}.splide__slide img{vertical-align:bottom}.splide__spinner{animation:splide-loading 1s linear infinite;border:2px solid #999;border-left-color:transparent;border-radius:50%;bottom:0;contain:strict;display:inline-block;height:20px;left:0;margin:auto;position:absolute;right:0;top:0;width:20px}.splide__sr{clip:rect(0 0 0 0);border:0;height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.splide__toggle.is-active .splide__toggle__play,.splide__toggle__pause{display:none}.splide__toggle.is-active .splide__toggle__pause{display:inline}.splide__track{overflow:hidden;position:relative;z-index:0}@keyframes splide-loading{0%{transform:rotate(0)}to{transform:rotate(1turn)}}.splide__track--draggable{-webkit-touch-callout:none;-webkit-user-select:none;-ms-user-select:none;user-select:none}.splide__track--fade>.splide__list>.splide__slide{margin:0!important;opacity:0;z-index:0}.splide__track--fade>.splide__list>.splide__slide.is-active{opacity:1;z-index:1}.splide--rtl{direction:rtl}.splide__track--ttb>.splide__list{display:block}.splide__arrow{-ms-flex-align:center;align-items:center;background:#ccc;border:0;border-radius:50%;cursor:pointer;display:-ms-flexbox;display:flex;height:2em;-ms-flex-pack:center;justify-content:center;opacity:.7;padding:0;position:absolute;top:50%;transform:translateY(-50%);width:2em;z-index:1}.splide__arrow svg{fill:#000;height:1.2em;width:1.2em}.splide__arrow:hover:not(:disabled){opacity:.9}.splide__arrow:disabled{opacity:.3}.splide__arrow:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide__arrow--prev{left:1em}.splide__arrow--prev svg{transform:scaleX(-1)}.splide__arrow--next{right:1em}.splide.is-focus-in .splide__arrow:focus{outline:3px solid #0bf;outline-offset:3px}.splide__pagination{bottom:.5em;left:0;padding:0 1em;position:absolute;right:0;z-index:1}.splide__pagination__page{background:#ccc;border:0;border-radius:50%;display:inline-block;height:8px;margin:3px;opacity:.7;padding:0;position:relative;transition:transform .2s linear;width:8px}.splide__pagination__page.is-active{background:#fff;transform:scale(1.4);z-index:1}.splide__pagination__page:hover{cursor:pointer;opacity:.9}.splide__pagination__page:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide.is-focus-in .splide__pagination__page:focus{outline:3px solid #0bf;outline-offset:3px}.splide__progress__bar{background:#ccc;height:3px}.splide__slide{-webkit-tap-highlight-color:rgba(0,0,0,0)}.splide__slide:focus{outline:0}@supports(outline-offset:-3px){.splide__slide:focus-visible{outline:3px solid #0bf;outline-offset:-3px}}@media screen and (-ms-high-contrast:none){.splide__slide:focus-visible{border:3px solid #0bf}}@supports(outline-offset:-3px){.splide.is-focus-in .splide__slide:focus{outline:3px solid #0bf;outline-offset:-3px}}@media screen and (-ms-high-contrast:none){.splide.is-focus-in .splide__slide:focus{border:3px solid #0bf}.splide.is-focus-in .splide__track>.splide__list>.splide__slide:focus{border-color:#0bf}}.splide__toggle{cursor:pointer}.splide__toggle:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide.is-focus-in .splide__toggle:focus{outline:3px solid #0bf;outline-offset:3px}.splide__track--nav>.splide__list>.splide__slide{border:3px solid transparent;cursor:pointer}.splide__track--nav>.splide__list>.splide__slide.is-active{border:3px solid #000}.splide__arrows--rtl .splide__arrow--prev{left:auto;right:1em}.splide__arrows--rtl .splide__arrow--prev svg{transform:scaleX(1)}.splide__arrows--rtl .splide__arrow--next{left:1em;right:auto}.splide__arrows--rtl .splide__arrow--next svg{transform:scaleX(-1)}.splide__arrows--ttb .splide__arrow{left:50%;transform:translate(-50%)}.splide__arrows--ttb .splide__arrow--prev{top:1em}.splide__arrows--ttb .splide__arrow--prev svg{transform:rotate(-90deg)}.splide__arrows--ttb .splide__arrow--next{bottom:1em;top:auto}.splide__arrows--ttb .splide__arrow--next svg{transform:rotate(90deg)}.splide__pagination--ttb{bottom:0;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;left:auto;padding:1em 0;right:.5em;top:0}\n \n:host {\n display: block;\n width: 100%;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n `,this.container=document.createElement("div"),this.container.className="jaaq-collection-player",this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(this.container)}async initCarousel(){if(!this.container)return;const t=this.getAttribute("collection-id");if(!t)return void this.emitError(new Error("collection-id attribute is required"));const e=this.getAttribute("api-key"),i=this.getAttribute("client-id"),s=this.getAttribute("base-url")||void 0;if(this.clientInstance||e||i){this.showLoading();try{const r=this.clientInstance||ul.init({apiKey:e,clientId:i,baseUrl:s||cl});if(this.collectionData=await r.collections.getById(t),!this.collectionData.videos||0===this.collectionData.videos.length)return void this.emitError(new Error("No videos found in collection"));this.renderCarousel(),this.initSplide(),this.dispatchEvent(new CustomEvent("jaaq:collection:loaded",{detail:this.collectionData,bubbles:!0,composed:!0}))}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to load collection"))}}else this.emitError(new Error("Either client property or api-key and client-id attributes are required"))}showLoading(){this.container&&(this.container.innerHTML='\n <div class="jaaq-collection-loading">\n <div class="jaaq-collection-spinner"></div>\n </div>\n ')}renderCarousel(){if(!this.container||!this.collectionData)return;this.container.innerHTML="",this.carouselElement=document.createElement("div"),this.carouselElement.className="splide jaaq-collection-carousel";const t=document.createElement("div");t.className="splide__track";const e=document.createElement("ul");e.className="splide__list";const i=this.getAttribute("api-key"),s=this.getAttribute("client-id"),r=this.getAttribute("base-url"),n=this.getAttribute("video-settings");let a=null;if(n)try{a=JSON.parse(n)}catch(t){console.warn("[CollectionPlayer] Failed to parse video-settings attribute",t)}this.collectionData.videos.forEach(t=>{const n=document.createElement("li");n.className="splide__slide";const o=document.createElement("jaaq-video-player");o.setAttribute("video-id",t.videoId),i&&o.setAttribute("api-key",i),s&&o.setAttribute("client-id",s),r&&o.setAttribute("base-url",r),o.setAttribute("autoplay","false"),o.setAttribute("width","100%"),a&&(void 0!==a.controls&&o.setAttribute("controls",String(a.controls)),void 0!==a.showLogo&&o.setAttribute("show-logo",String(a.showLogo)),void 0!==a.showTitle&&o.setAttribute("show-title",String(a.showTitle)),void 0!==a.showAuthor&&o.setAttribute("show-author",String(a.showAuthor)),void 0!==a.showDescription&&o.setAttribute("show-description",String(a.showDescription)),void 0!==a.showCaptions&&o.setAttribute("show-captions",String(a.showCaptions)),void 0!==a.startMuted&&o.setAttribute("start-muted",String(a.startMuted)),void 0!==a.width&&o.setAttribute("width",String(a.width)),void 0!==a.height&&o.setAttribute("height",String(a.height))),n.appendChild(o),e.appendChild(n)}),t.appendChild(e),this.carouselElement.appendChild(t),this.container.appendChild(this.carouselElement)}initSplide(){if(!this.carouselElement)return;const t=this.getBooleanAttr("show-arrows",!0),e=this.getBooleanAttr("show-dots",!0);this.splide=new yc(this.carouselElement,{type:"loop",perPage:3,focus:"center",gap:"0.5rem",perMove:1,autoHeight:!0,updateOnMove:!0,padding:"5 rem",breakpoints:{768:{perPage:1},1024:{perPage:2}},arrows:t,pagination:e,autoplay:!1}),this.splide.on("moved",t=>{console.log("[CollectionPlayer] Splide moved event",{newIndex:t,splideIndex:this.splide?.index,Components:this.splide?.Components}),this.handleSlideChange(t),this.dispatchEvent(new CustomEvent("jaaq:collection:slidechange",{detail:{index:t,video:this.collectionData?.videos[t]},bubbles:!0,composed:!0}))}),this.splide.mount(),console.log("[CollectionPlayer] After mount",{splideIndex:this.splide.index,length:this.splide.length}),setTimeout(()=>{this.splide&&(console.log("[CollectionPlayer] Initial handleSlideChange after DOM update"),this.handleSlideChange(this.splide.index))},100)}handleSlideChange(t){if(!this.carouselElement)return;const e=this.hasAttribute("autoplay")&&"false"!==this.getAttribute("autoplay");console.log("[CollectionPlayer] handleSlideChange called",{activeIndex:t,isAutoplayEnabled:e}),null!==this.autoplayTimeoutId&&(console.log("[CollectionPlayer] Clearing existing autoplay timeout",{timeoutId:this.autoplayTimeoutId}),clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null);const i=this.carouselElement.querySelector(".splide__slide.is-active:not(.splide__slide--clone)"),s=i?.querySelector("jaaq-video-player"),r=s?.getAttribute("video-id");console.log("[CollectionPlayer] Active slide from DOM:",{activeIndex:t,activeVideoId:r,foundActiveSlide:!!i});const n=this.carouselElement.querySelectorAll(".splide__slide:not(.splide__slide--clone)");Array.from(n).map((t,e)=>{const i=t.querySelector("jaaq-video-player");return{index:e,videoId:i?.getAttribute("video-id")||"unknown",isActive:t.classList.contains("is-active")}}),n.forEach((t,i)=>{const s=t.querySelector("jaaq-video-player");if(!s)return;const r=s.getAttribute("video-id");t.classList.contains("is-active")?e&&(this.autoplayTimeoutId=window.setTimeout(()=>{console.log("[CollectionPlayer] 1s delay complete, playing video",{index:i,videoId:r}),s.play?.()},1e3)):s.pause?.()})}destroyCarousel(){null!==this.autoplayTimeoutId&&(clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null),this.splide&&(this.splide.destroy(),this.splide=null),this.container&&(this.container.innerHTML=""),this.collectionData=null}emitError(t){this.container&&(this.container.innerHTML=`\n <div class="jaaq-collection-error">\n ${t.message}\n </div>\n `),this.dispatchEvent(new CustomEvent("jaaq:collection:error",{detail:t,bubbles:!0,composed:!0}))}get client(){return this.clientInstance}set client(t){this.clientInstance=t,this.connected&&(this.destroyCarousel(),this.initCarousel())}get collectionId(){return this.getAttribute("collection-id")}set collectionId(t){t?this.setAttribute("collection-id",t):this.removeAttribute("collection-id")}refresh(){this.destroyCarousel(),this.initCarousel()}next(){this.splide?.go("+1")}prev(){this.splide?.go("-1")}go(t){this.splide?.go(t)}destroy(){this.destroyCarousel()}getCollection(){return this.collectionData}}const Tc="jaaq-video-player",Sc="jaaq-collection-player";function bc(){"undefined"!=typeof window&&"undefined"!=typeof customElements?(customElements.get(Tc)||customElements.define(Tc,vl),customElements.get(Sc)||customElements.define(Sc,Ec)):console.warn("Custom Elements API is not available. Web components cannot be registered.")}"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{bc()}):bc()),t.JaaqCollectionPlayerElement=Ec,t.JaaqVideoPlayerElement=vl,t.isRegistered=function(){return"undefined"!=typeof window&&"undefined"!=typeof customElements&&(!!customElements.get(Tc)&&!!customElements.get(Sc))},t.registerJaaqComponents=bc});
|
|
7
|
+
*/var El="(prefers-reduced-motion: reduce)",Tl={CREATED:1,MOUNTED:2,IDLE:3,MOVING:4,SCROLLING:5,DRAGGING:6,DESTROYED:7};function Sl(t){t.length=0}function bl(t,e,i){return Array.prototype.slice.call(t,e,i)}function Al(t){return t.bind.apply(t,[null].concat(bl(arguments,1)))}var Ll=setTimeout,Il=function(){};function Rl(t){return requestAnimationFrame(t)}function kl(t,e){return typeof e===t}function _l(t){return!xl(t)&&kl("object",t)}var wl=Array.isArray,Dl=Al(kl,"function"),Pl=Al(kl,"string"),Cl=Al(kl,"undefined");function xl(t){return null===t}function Ml(t){try{return t instanceof(t.ownerDocument.defaultView||window).HTMLElement}catch(t){return!1}}function Ol(t){return wl(t)?t:[t]}function Fl(t,e){Ol(t).forEach(e)}function Nl(t,e){return t.indexOf(e)>-1}function Bl(t,e){return t.push.apply(t,Ol(e)),t}function Ul(t,e,i){t&&Fl(e,function(e){e&&t.classList[i?"add":"remove"](e)})}function $l(t,e){Ul(t,Pl(e)?e.split(" "):e,!0)}function Gl(t,e){Fl(e,t.appendChild.bind(t))}function Kl(t,e){Fl(t,function(t){var i=(e||t).parentNode;i&&i.insertBefore(t,e)})}function Vl(t,e){return Ml(t)&&(t.msMatchesSelector||t.matches).call(t,e)}function Hl(t,e){var i=t?bl(t.children):[];return e?i.filter(function(t){return Vl(t,e)}):i}function jl(t,e){return e?Hl(t,e)[0]:t.firstElementChild}var ql=Object.keys;function Yl(t,e,i){return t&&(i?ql(t).reverse():ql(t)).forEach(function(i){"__proto__"!==i&&e(t[i],i)}),t}function Wl(t){return bl(arguments,1).forEach(function(e){Yl(e,function(i,s){t[s]=e[s]})}),t}function zl(t){return bl(arguments,1).forEach(function(e){Yl(e,function(e,i){wl(e)?t[i]=e.slice():_l(e)?t[i]=zl({},_l(t[i])?t[i]:{},e):t[i]=e})}),t}function Xl(t,e){Fl(e||ql(t),function(e){delete t[e]})}function Ql(t,e){Fl(t,function(t){Fl(e,function(e){t&&t.removeAttribute(e)})})}function Zl(t,e,i){_l(e)?Yl(e,function(e,i){Zl(t,i,e)}):Fl(t,function(t){xl(i)||""===i?Ql(t,e):t.setAttribute(e,String(i))})}function Jl(t,e,i){var s=document.createElement(t);return e&&(Pl(e)?$l(s,e):Zl(s,e)),i&&Gl(i,s),s}function td(t,e,i){if(Cl(i))return getComputedStyle(t)[e];xl(i)||(t.style[e]=""+i)}function ed(t,e){td(t,"display",e)}function id(t){t.setActive&&t.setActive()||t.focus({preventScroll:!0})}function sd(t,e){return t.getAttribute(e)}function rd(t,e){return t&&t.classList.contains(e)}function nd(t){return t.getBoundingClientRect()}function ad(t){Fl(t,function(t){t&&t.parentNode&&t.parentNode.removeChild(t)})}function od(t){return jl((new DOMParser).parseFromString(t,"text/html").body)}function ld(t,e){t.preventDefault(),e&&(t.stopPropagation(),t.stopImmediatePropagation())}function dd(t,e){return t&&t.querySelector(e)}function hd(t,e){return e?bl(t.querySelectorAll(e)):[]}function cd(t,e){Ul(t,e,!1)}function ud(t){return t.timeStamp}function fd(t){return Pl(t)?t:t?t+"px":""}var gd="splide",md="data-"+gd;function pd(t,e){if(!t)throw new Error("["+gd+"] "+(e||""))}var vd=Math.min,yd=Math.max,Ed=Math.floor,Td=Math.ceil,Sd=Math.abs;function bd(t,e,i){return Sd(t-e)<i}function Ad(t,e,i,s){var r=vd(e,i),n=yd(e,i);return s?r<t&&t<n:r<=t&&t<=n}function Ld(t,e,i){var s=vd(e,i),r=yd(e,i);return vd(yd(s,t),r)}function Id(t){return+(t>0)-+(t<0)}function Rd(t,e){return Fl(e,function(e){t=t.replace("%s",""+e)}),t}function kd(t){return t<10?"0"+t:""+t}var _d={};function wd(){var t=[];function e(t,e,i){Fl(t,function(t){t&&Fl(e,function(e){e.split(" ").forEach(function(e){var s=e.split(".");i(t,s[0],s[1])})})})}return{bind:function(i,s,r,n){e(i,s,function(e,i,s){var a="addEventListener"in e,o=a?e.removeEventListener.bind(e,i,r,n):e.removeListener.bind(e,r);a?e.addEventListener(i,r,n):e.addListener(r),t.push([e,i,s,r,o])})},unbind:function(i,s,r){e(i,s,function(e,i,s){t=t.filter(function(t){return!!(t[0]!==e||t[1]!==i||t[2]!==s||r&&t[3]!==r)||(t[4](),!1)})})},dispatch:function(t,e,i){var s,r=!0;return"function"==typeof CustomEvent?s=new CustomEvent(e,{bubbles:r,detail:i}):(s=document.createEvent("CustomEvent")).initCustomEvent(e,r,!1,i),t.dispatchEvent(s),s},destroy:function(){t.forEach(function(t){t[4]()}),Sl(t)}}}var Dd="mounted",Pd="ready",Cd="move",xd="moved",Md="click",Od="active",Fd="inactive",Nd="visible",Bd="hidden",Ud="refresh",$d="updated",Gd="resize",Kd="resized",Vd="scroll",Hd="scrolled",jd="destroy",qd="arrows:mounted",Yd="navigation:mounted",Wd="autoplay:play",zd="autoplay:pause",Xd="lazyload:loaded",Qd="sk",Zd="sh",Jd="ei";function th(t){var e=t?t.event.bus:document.createDocumentFragment(),i=wd();return t&&t.event.on(jd,i.destroy),Wl(i,{bus:e,on:function(t,s){i.bind(e,Ol(t).join(" "),function(t){s.apply(s,wl(t.detail)?t.detail:[])})},off:Al(i.unbind,e),emit:function(t){i.dispatch(e,t,bl(arguments,1))}})}function eh(t,e,i,s){var r,n,a=Date.now,o=0,l=!0,d=0;function h(){if(!l){if(o=t?vd((a()-r)/t,1):1,i&&i(o),o>=1&&(e(),r=a(),s&&++d>=s))return c();n=Rl(h)}}function c(){l=!0}function u(){n&&cancelAnimationFrame(n),o=0,n=0,l=!0}return{start:function(e){e||u(),r=a()-(e?o*t:0),l=!1,n=Rl(h)},rewind:function(){r=a(),o=0,i&&i(o)},pause:c,cancel:u,set:function(e){t=e},isPaused:function(){return l}}}var ih="Arrow",sh=ih+"Left",rh=ih+"Right",nh=ih+"Up",ah=ih+"Down",oh="ttb",lh={width:["height"],left:["top","right"],right:["bottom","left"],x:["y"],X:["Y"],Y:["X"],ArrowLeft:[nh,rh],ArrowRight:[ah,sh]};var dh="role",hh="tabindex",ch="aria-",uh=ch+"controls",fh=ch+"current",gh=ch+"selected",mh=ch+"label",ph=ch+"labelledby",vh=ch+"hidden",yh=ch+"orientation",Eh=ch+"roledescription",Th=ch+"live",Sh=ch+"busy",bh=ch+"atomic",Ah=[dh,hh,"disabled",uh,fh,mh,ph,vh,yh,Eh],Lh=gd+"__",Ih="is-",Rh=gd,kh=Lh+"track",_h=Lh+"list",wh=Lh+"slide",Dh=wh+"--clone",Ph=wh+"__container",Ch=Lh+"arrows",xh=Lh+"arrow",Mh=xh+"--prev",Oh=xh+"--next",Fh=Lh+"pagination",Nh=Fh+"__page",Bh=Lh+"progress"+"__bar",Uh=Lh+"toggle",$h=Lh+"sr",Gh=Ih+"initialized",Kh=Ih+"active",Vh=Ih+"prev",Hh=Ih+"next",jh=Ih+"visible",qh=Ih+"loading",Yh=Ih+"focus-in",Wh=Ih+"overflow",zh=[Kh,jh,Vh,Hh,qh,Yh,Wh],Xh={slide:wh,clone:Dh,arrows:Ch,arrow:xh,prev:Mh,next:Oh,pagination:Fh,page:Nh,spinner:Lh+"spinner"};var Qh="touchstart mousedown",Zh="touchmove mousemove",Jh="touchend touchcancel mouseup click";var tc="slide",ec="loop",ic="fade";function sc(t,e,i,s){var r,n=th(t),a=n.on,o=n.emit,l=n.bind,d=t.Components,h=t.root,c=t.options,u=c.isNavigation,f=c.updateOnMove,g=c.i18n,m=c.pagination,p=c.slideFocus,v=d.Direction.resolve,y=sd(s,"style"),E=sd(s,mh),T=i>-1,S=jl(s,"."+Ph);function b(){var r=t.splides.map(function(t){var i=t.splide.Components.Slides.getAt(e);return i?i.slide.id:""}).join(" ");Zl(s,mh,Rd(g.slideX,(T?i:e)+1)),Zl(s,uh,r),Zl(s,dh,p?"button":""),p&&Ql(s,Eh)}function A(){r||L()}function L(){if(!r){var i=t.index;(n=I())!==rd(s,Kh)&&(Ul(s,Kh,n),Zl(s,fh,u&&n||""),o(n?Od:Fd,R)),function(){var e=function(){if(t.is(ic))return I();var e=nd(d.Elements.track),i=nd(s),r=v("left",!0),n=v("right",!0);return Ed(e[r])<=Td(i[r])&&Ed(i[n])<=Td(e[n])}(),i=!e&&(!I()||T);t.state.is([4,5])||Zl(s,vh,i||"");Zl(hd(s,c.focusableNodes||""),hh,i?-1:""),p&&Zl(s,hh,i?-1:0);e!==rd(s,jh)&&(Ul(s,jh,e),o(e?Nd:Bd,R));if(!e&&document.activeElement===s){var r=d.Slides.getAt(t.index);r&&id(r.slide)}}(),Ul(s,Vh,e===i-1),Ul(s,Hh,e===i+1)}var n}function I(){var s=t.index;return s===e||c.cloneStatus&&s===i}var R={index:e,slideIndex:i,slide:s,container:S,isClone:T,mount:function(){T||(s.id=h.id+"-slide"+kd(e+1),Zl(s,dh,m?"tabpanel":"group"),Zl(s,Eh,g.slide),Zl(s,mh,E||Rd(g.slideLabel,[e+1,t.length]))),l(s,"click",Al(o,Md,R)),l(s,"keydown",Al(o,Qd,R)),a([xd,Zd,Hd],L),a(Yd,b),f&&a(Cd,A)},destroy:function(){r=!0,n.destroy(),cd(s,zh),Ql(s,Ah),Zl(s,"style",y),Zl(s,mh,E||"")},update:L,style:function(t,e,i){td(i&&S||s,t,e)},isWithin:function(i,s){var r=Sd(i-e);return T||!c.rewind&&!t.is(ec)||(r=vd(r,t.length-r)),r<=s}};return R}var rc=md+"-interval";var nc={passive:!1,capture:!0};var ac={Spacebar:" ",Right:rh,Left:sh,Up:nh,Down:ah};function oc(t){return t=Pl(t)?t:t.key,ac[t]||t}var lc="keydown";var dc=md+"-lazy",hc=dc+"-srcset",cc="["+dc+"], ["+hc+"]";var uc=[" ","Enter"];var fc=Object.freeze({__proto__:null,Media:function(t,e,i){var s=t.state,r=i.breakpoints||{},n=i.reducedMotion||{},a=wd(),o=[];function l(t){t&&a.destroy()}function d(t,e){var i=matchMedia(e);a.bind(i,"change",h),o.push([t,i])}function h(){var e=s.is(7),r=i.direction,n=o.reduce(function(t,e){return zl(t,e[1].matches?e[0]:{})},{});Xl(i),c(n),i.destroy?t.destroy("completely"===i.destroy):e?(l(!0),t.mount()):r!==i.direction&&t.refresh()}function c(e,r,n){zl(i,e),r&&zl(Object.getPrototypeOf(i),e),!n&&s.is(1)||t.emit($d,i)}return{setup:function(){var t="min"===i.mediaQuery;ql(r).sort(function(e,i){return t?+e-+i:+i-+e}).forEach(function(e){d(r[e],"("+(t?"min":"max")+"-width:"+e+"px)")}),d(n,El),h()},destroy:l,reduce:function(t){matchMedia(El).matches&&(t?zl(i,n):Xl(i,ql(n)))},set:c}},Direction:function(t,e,i){return{resolve:function(t,e,s){var r="rtl"!==(s=s||i.direction)||e?s===oh?0:-1:1;return lh[t]&&lh[t][r]||t.replace(/width|left|right/i,function(t,e){var i=lh[t.toLowerCase()][r]||t;return e>0?i.charAt(0).toUpperCase()+i.slice(1):i})},orient:function(t){return t*("rtl"===i.direction?1:-1)}}},Elements:function(t,e,i){var s,r,n,a=th(t),o=a.on,l=a.bind,d=t.root,h=i.i18n,c={},u=[],f=[],g=[];function m(){s=y("."+kh),r=jl(s,"."+_h),pd(s&&r,"A track/list element is missing."),Bl(u,Hl(r,"."+wh+":not(."+Dh+")")),Yl({arrows:Ch,pagination:Fh,prev:Mh,next:Oh,bar:Bh,toggle:Uh},function(t,e){c[e]=y("."+t)}),Wl(c,{root:d,track:s,list:r,slides:u}),function(){var t=d.id||(n=gd,""+n+kd(_d[n]=(_d[n]||0)+1)),e=i.role;var n;d.id=t,s.id=s.id||t+"-track",r.id=r.id||t+"-list",!sd(d,dh)&&"SECTION"!==d.tagName&&e&&Zl(d,dh,e);Zl(d,Eh,h.carousel),Zl(r,dh,"presentation")}(),v()}function p(t){var e=Ah.concat("style");Sl(u),cd(d,f),cd(s,g),Ql([s,r],e),Ql(d,t?e:["style",Eh])}function v(){cd(d,f),cd(s,g),f=E(Rh),g=E(kh),$l(d,f),$l(s,g),Zl(d,mh,i.label),Zl(d,ph,i.labelledby)}function y(t){var e=dd(d,t);return e&&function(t,e){if(Dl(t.closest))return t.closest(e);for(var i=t;i&&1===i.nodeType&&!Vl(i,e);)i=i.parentElement;return i}(e,"."+Rh)===d?e:void 0}function E(t){return[t+"--"+i.type,t+"--"+i.direction,i.drag&&t+"--draggable",i.isNavigation&&t+"--nav",t===Rh&&Kh]}return Wl(c,{setup:m,mount:function(){o(Ud,p),o(Ud,m),o($d,v),l(document,Qh+" keydown",function(t){n="keydown"===t.type},{capture:!0}),l(d,"focusin",function(){Ul(d,Yh,!!n)})},destroy:p})},Slides:function(t,e,i){var s=th(t),r=s.on,n=s.emit,a=s.bind,o=e.Elements,l=o.slides,d=o.list,h=[];function c(){l.forEach(function(t,e){f(t,e,-1)})}function u(){m(function(t){t.destroy()}),Sl(h)}function f(e,i,s){var r=sc(t,i,s,e);r.mount(),h.push(r),h.sort(function(t,e){return t.index-e.index})}function g(t){return t?p(function(t){return!t.isClone}):h}function m(t,e){g(e).forEach(t)}function p(t){return h.filter(Dl(t)?t:function(e){return Pl(t)?Vl(e.slide,t):Nl(Ol(t),e.index)})}return{mount:function(){c(),r(Ud,u),r(Ud,c)},destroy:u,update:function(){m(function(t){t.update()})},register:f,get:g,getIn:function(t){var s=e.Controller,r=s.toIndex(t),n=s.hasFocus()?1:i.perPage;return p(function(t){return Ad(t.index,r,r+n-1)})},getAt:function(t){return p(t)[0]},add:function(t,e){Fl(t,function(t){if(Pl(t)&&(t=od(t)),Ml(t)){var s=l[e];s?Kl(t,s):Gl(d,t),$l(t,i.classes.slide),r=t,o=Al(n,Gd),h=hd(r,"img"),(c=h.length)?h.forEach(function(t){a(t,"load error",function(){--c||o()})}):o()}var r,o,h,c}),n(Ud)},remove:function(t){ad(p(t).map(function(t){return t.slide})),n(Ud)},forEach:m,filter:p,style:function(t,e,i){m(function(s){s.style(t,e,i)})},getLength:function(t){return t?l.length:h.length},isEnough:function(){return h.length>i.perPage}}},Layout:function(t,e,i){var s,r,n,a=th(t),o=a.on,l=a.bind,d=a.emit,h=e.Slides,c=e.Direction.resolve,u=e.Elements,f=u.root,g=u.track,m=u.list,p=h.getAt,v=h.style;function y(){s=i.direction===oh,td(f,"maxWidth",fd(i.width)),td(g,c("paddingLeft"),T(!1)),td(g,c("paddingRight"),T(!0)),E(!0)}function E(t){var e=nd(f);(t||r.width!==e.width||r.height!==e.height)&&(td(g,"height",function(){var t="";s&&(pd(t=S(),"height or heightRatio is missing."),t="calc("+t+" - "+T(!1)+" - "+T(!0)+")");return t}()),v(c("marginRight"),fd(i.gap)),v("width",i.autoWidth?null:fd(i.fixedWidth)||(s?"":b())),v("height",fd(i.fixedHeight)||(s?i.autoHeight?null:b():S()),!0),r=e,d(Kd),n!==(n=_())&&(Ul(f,Wh,n),d("overflow",n)))}function T(t){var e=i.padding,s=c(t?"right":"left");return e&&fd(e[s]||(_l(e)?0:e))||"0px"}function S(){return fd(i.height||nd(m).width*i.heightRatio)}function b(){var t=fd(i.gap);return"calc((100%"+(t&&" + "+t)+")/"+(i.perPage||1)+(t&&" - "+t)+")"}function A(){return nd(m)[c("width")]}function L(t,e){var i=p(t||0);return i?nd(i.slide)[c("width")]+(e?0:k()):0}function I(t,e){var i=p(t);if(i){var s=nd(i.slide)[c("right")],r=nd(m)[c("left")];return Sd(s-r)+(e?0:k())}return 0}function R(e){return I(t.length-1)-I(0)+L(0,e)}function k(){var t=p(0);return t&&parseFloat(td(t.slide,c("marginRight")))||0}function _(){return t.is(ic)||R(!0)>A()}return{mount:function(){var t,e;y(),l(window,"resize load",(t=Al(d,Gd),e=eh(0,t,null,1),function(){e.isPaused()&&e.start()})),o([$d,Ud],y),o(Gd,E)},resize:E,listSize:A,slideSize:L,sliderSize:R,totalSize:I,getPadding:function(t){return parseFloat(td(g,c("padding"+(t?"Right":"Left"))))||0},isOverflow:_}},Clones:function(t,e,i){var s,r=th(t),n=r.on,a=e.Elements,o=e.Slides,l=e.Direction.resolve,d=[];function h(){n(Ud,c),n([$d,Gd],f),(s=g())&&(!function(e){var s=o.get().slice(),r=s.length;if(r){for(;s.length<e;)Bl(s,s);Bl(s.slice(-e),s.slice(0,e)).forEach(function(n,l){var h=l<e,c=function(e,s){var r=e.cloneNode(!0);return $l(r,i.classes.clone),r.id=t.root.id+"-clone"+kd(s+1),r}(n.slide,l);h?Kl(c,s[0].slide):Gl(a.list,c),Bl(d,c),o.register(c,l-e+(h?0:r),n.index)})}}(s),e.Layout.resize(!0))}function c(){u(),h()}function u(){ad(d),Sl(d),r.destroy()}function f(){var t=g();s!==t&&(s<t||!t)&&r.emit(Ud)}function g(){var s=i.clones;if(t.is(ec)){if(Cl(s)){var r=i[l("fixedWidth")]&&e.Layout.slideSize(0);s=r&&Td(nd(a.track)[l("width")]/r)||i[l("autoWidth")]&&t.length||2*i.perPage}}else s=0;return s}return{mount:h,destroy:u}},Move:function(t,e,i){var s,r=th(t),n=r.on,a=r.emit,o=t.state.set,l=e.Layout,d=l.slideSize,h=l.getPadding,c=l.totalSize,u=l.listSize,f=l.sliderSize,g=e.Direction,m=g.resolve,p=g.orient,v=e.Elements,y=v.list,E=v.track;function T(){e.Controller.isBusy()||(e.Scroll.cancel(),S(t.index),e.Slides.update())}function S(t){b(R(t,!0))}function b(i,s){if(!t.is(ic)){var r=s?i:function(i){if(t.is(ec)){var s=I(i),r=s>e.Controller.getEnd();(s<0||r)&&(i=A(i,r))}return i}(i);td(y,"transform","translate"+m("X")+"("+r+"px)"),i!==r&&a(Zd)}}function A(t,e){var i=t-_(e),s=f();return t-=p(s*(Td(Sd(i)/s)||1))*(e?1:-1)}function L(){b(k(),!0),s.cancel()}function I(t){for(var i=e.Slides.get(),s=0,r=1/0,n=0;n<i.length;n++){var a=i[n].index,o=Sd(R(a,!0)-t);if(!(o<=r))break;r=o,s=a}return s}function R(e,s){var r=p(c(e-1)-function(t){var e=i.focus;return"center"===e?(u()-d(t,!0))/2:+e*d(t)||0}(e));return s?function(e){i.trimSpace&&t.is(tc)&&(e=Ld(e,0,p(f(!0)-u())));return e}(r):r}function k(){var t=m("left");return nd(y)[t]-nd(E)[t]+p(h(!1))}function _(t){return R(t?e.Controller.getEnd():0,!!i.trimSpace)}return{mount:function(){s=e.Transition,n([Dd,Kd,$d,Ud],T)},move:function(t,e,i,r){var n,l;t!==e&&(n=t>i,l=p(A(k(),n)),n?l>=0:l<=y[m("scrollWidth")]-nd(E)[m("width")])&&(L(),b(A(k(),t>i),!0)),o(4),a(Cd,e,i,t),s.start(e,function(){o(3),a(xd,e,i,t),r&&r()})},jump:S,translate:b,shift:A,cancel:L,toIndex:I,toPosition:R,getPosition:k,getLimit:_,exceededLimit:function(t,e){e=Cl(e)?k():e;var i=!0!==t&&p(e)<p(_(!1)),s=!1!==t&&p(e)>p(_(!0));return i||s},reposition:T}},Controller:function(t,e,i){var s,r,n,a,o=th(t),l=o.on,d=o.emit,h=e.Move,c=h.getPosition,u=h.getLimit,f=h.toPosition,g=e.Slides,m=g.isEnough,p=g.getLength,v=i.omitEnd,y=t.is(ec),E=t.is(tc),T=Al(R,!1),S=Al(R,!0),b=i.start||0,A=b;function L(){r=p(!0),n=i.perMove,a=i.perPage,s=w();var t=Ld(b,0,v?s:r-1);t!==b&&(b=t,h.reposition())}function I(){s!==w()&&d(Jd)}function R(t,e){var i=n||(x()?1:a),r=k(b+i*(t?-1:1),b,!(n||x()));return-1===r&&E&&!bd(c(),u(!t),1)?t?0:s:e?r:_(r)}function k(e,o,l){if(m()||x()){var d=function(e){if(E&&"move"===i.trimSpace&&e!==b)for(var s=c();s===f(e,!0)&&Ad(e,0,t.length-1,!i.rewind);)e<b?--e:++e;return e}(e);d!==e&&(o=e,e=d,l=!1),e<0||e>s?e=n||!Ad(0,e,o,!0)&&!Ad(s,o,e,!0)?y?l?e<0?-(r%a||a):r:e:i.rewind?e<0?s:0:-1:D(P(e)):l&&e!==o&&(e=D(P(o)+(e<o?-1:1)))}else e=-1;return e}function _(t){return y?(t+r)%r||0:t}function w(){for(var t=r-(x()||y&&n?1:a);v&&t-- >0;)if(f(r-1,!0)!==f(t,!0)){t++;break}return Ld(t,0,r-1)}function D(t){return Ld(x()?t:a*t,0,s)}function P(t){return x()?vd(t,s):Ed((t>=s?r-1:t)/a)}function C(t){t!==b&&(A=b,b=t)}function x(){return!Cl(i.focus)||i.isNavigation}function M(){return t.state.is([4,5])&&!!i.waitForTransition}return{mount:function(){L(),l([$d,Ud,Jd],L),l(Kd,I)},go:function(t,e,i){if(!M()){var r=function(t){var e=b;if(Pl(t)){var i=t.match(/([+\-<>])(\d+)?/)||[],r=i[1],n=i[2];"+"===r||"-"===r?e=k(b+ +(""+r+(+n||1)),b):">"===r?e=n?D(+n):T(!0):"<"===r&&(e=S(!0))}else e=y?t:Ld(t,0,s);return e}(t),n=_(r);n>-1&&(e||n!==b)&&(C(n),h.move(r,n,A,i))}},scroll:function(t,i,r,n){e.Scroll.scroll(t,i,r,function(){var t=_(h.toIndex(c()));C(v?vd(t,s):t),n&&n()})},getNext:T,getPrev:S,getAdjacent:R,getEnd:w,setIndex:C,getIndex:function(t){return t?A:b},toIndex:D,toPage:P,toDest:function(t){var e=h.toIndex(t);return E?Ld(e,0,s):e},hasFocus:x,isBusy:M}},Arrows:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.bind,l=n.emit,d=i.classes,h=i.i18n,c=e.Elements,u=e.Controller,f=c.arrows,g=c.track,m=f,p=c.prev,v=c.next,y={};function E(){!function(){var t=i.arrows;!t||p&&v||(m=f||Jl("div",d.arrows),p=A(!0),v=A(!1),s=!0,Gl(m,[p,v]),!f&&Kl(m,g));p&&v&&(Wl(y,{prev:p,next:v}),ed(m,t?"":"none"),$l(m,r=Ch+"--"+i.direction),t&&(a([Dd,xd,Ud,Hd,Jd],L),o(v,"click",Al(b,">")),o(p,"click",Al(b,"<")),L(),Zl([p,v],uh,g.id),l(qd,p,v)))}(),a($d,T)}function T(){S(),E()}function S(){n.destroy(),cd(m,r),s?(ad(f?[p,v]:m),p=v=null):Ql([p,v],Ah)}function b(t){u.go(t,!0)}function A(t){return od('<button class="'+d.arrow+" "+(t?d.prev:d.next)+'" type="button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40" focusable="false"><path d="'+(i.arrowPath||"m15.5 0.932-4.3 4.38 14.5 14.6-14.5 14.5 4.3 4.4 14.6-14.6 4.4-4.3-4.4-4.4-14.6-14.6z")+'" />')}function L(){if(p&&v){var e=t.index,i=u.getPrev(),s=u.getNext(),r=i>-1&&e<i?h.last:h.prev,n=s>-1&&e>s?h.first:h.next;p.disabled=i<0,v.disabled=s<0,Zl(p,mh,r),Zl(v,mh,n),l("arrows:updated",p,v,i,s)}}return{arrows:y,mount:E,destroy:S,update:L}},Autoplay:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.bind,l=n.emit,d=eh(i.interval,t.go.bind(t,">"),function(t){var e=c.bar;e&&td(e,"width",100*t+"%"),l("autoplay:playing",t)}),h=d.isPaused,c=e.Elements,u=e.Elements,f=u.root,g=u.toggle,m=i.autoplay,p="pause"===m;function v(){h()&&e.Slides.isEnough()&&(d.start(!i.resetProgress),r=s=p=!1,T(),l(Wd))}function y(t){void 0===t&&(t=!0),p=!!t,T(),h()||(d.pause(),l(zd))}function E(){p||(s||r?y(!1):v())}function T(){g&&(Ul(g,Kh,!p),Zl(g,mh,i.i18n[p?"play":"pause"]))}function S(t){var s=e.Slides.getAt(t);d.set(s&&+sd(s.slide,rc)||i.interval)}return{mount:function(){m&&(!function(){i.pauseOnHover&&o(f,"mouseenter mouseleave",function(t){s="mouseenter"===t.type,E()});i.pauseOnFocus&&o(f,"focusin focusout",function(t){r="focusin"===t.type,E()});g&&o(g,"click",function(){p?v():y(!0)});a([Cd,Vd,Ud],d.rewind),a(Cd,S)}(),g&&Zl(g,uh,c.track.id),p||v(),T())},destroy:d.cancel,play:v,pause:y,isPaused:h}},Cover:function(t,e,i){var s=th(t).on;function r(t){e.Slides.forEach(function(e){var i=jl(e.container||e.slide,"img");i&&i.src&&n(t,i,e)})}function n(t,e,i){i.style("background",t?'center/cover no-repeat url("'+e.src+'")':"",!0),ed(e,t?"none":"")}return{mount:function(){i.cover&&(s(Xd,Al(n,!0)),s([Dd,$d,Ud],Al(r,!0)))},destroy:Al(r,!1)}},Scroll:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.emit,l=t.state.set,d=e.Move,h=d.getPosition,c=d.getLimit,u=d.exceededLimit,f=d.translate,g=t.is(tc),m=1;function p(t,i,n,a,c){var f=h();if(E(),n&&(!g||!u())){var p=e.Layout.sliderSize(),T=Id(t)*p*Ed(Sd(t)/p)||0;t=d.toPosition(e.Controller.toDest(t%p))+T}var S=bd(f,t,1);m=1,i=S?0:i||yd(Sd(t-f)/1.5,800),r=a,s=eh(i,v,Al(y,f,t,c),1),l(5),o(Vd),s.start()}function v(){l(3),r&&r(),o(Hd)}function y(t,e,s,n){var a,o,l=h(),d=(t+(e-t)*(a=n,(o=i.easingFunc)?o(a):1-Math.pow(1-a,4))-l)*m;f(l+d),g&&!s&&u()&&(m*=.6,Sd(d)<10&&p(c(u(!0)),600,!1,r,!0))}function E(){s&&s.cancel()}function T(){s&&!s.isPaused()&&(E(),v())}return{mount:function(){a(Cd,E),a([$d,Ud],T)},destroy:E,scroll:p,cancel:T}},Drag:function(t,e,i){var s,r,n,a,o,l,d,h,c=th(t),u=c.on,f=c.emit,g=c.bind,m=c.unbind,p=t.state,v=e.Move,y=e.Scroll,E=e.Controller,T=e.Elements.track,S=e.Media.reduce,b=e.Direction,A=b.resolve,L=b.orient,I=v.getPosition,R=v.exceededLimit,k=!1;function _(){var t=i.drag;U(!t),a="free"===t}function w(t){if(l=!1,!d){var e=B(t);s=t.target,r=i.noDrag,Vl(s,"."+Nh+", ."+xh)||r&&Vl(s,r)||!e&&t.button||(E.isBusy()?ld(t,!0):(h=e?T:window,o=p.is([4,5]),n=null,g(h,Zh,D,nc),g(h,Jh,P,nc),v.cancel(),y.cancel(),x(t)))}var s,r}function D(e){if(p.is(6)||(p.set(6),f("drag")),e.cancelable)if(o){v.translate(s+M(e)/(k&&t.is(tc)?5:1));var r=O(e)>200,n=k!==(k=R());(r||n)&&x(e),l=!0,f("dragging"),ld(e)}else(function(t){return Sd(M(t))>Sd(M(t,!0))})(e)&&(o=function(t){var e=i.dragMinThreshold,s=_l(e),r=s&&e.mouse||0,n=(s?e.touch:+e)||10;return Sd(M(t))>(B(t)?n:r)}(e),ld(e))}function P(s){p.is(6)&&(p.set(3),f("dragged")),o&&(!function(s){var r=function(e){if(t.is(ec)||!k){var i=O(e);if(i&&i<200)return M(e)/i}return 0}(s),n=function(t){return I()+Id(t)*vd(Sd(t)*(i.flickPower||600),a?1/0:e.Layout.listSize()*(i.flickMaxPages||1))}(r),o=i.rewind&&i.rewindByDrag;S(!1),a?E.scroll(n,0,i.snap):t.is(ic)?E.go(L(Id(r))<0?o?"<":"-":o?">":"+"):t.is(tc)&&k&&o?E.go(R(!0)?">":"<"):E.go(E.toDest(n),!0);S(!0)}(s),ld(s)),m(h,Zh,D),m(h,Jh,P),o=!1}function C(t){!d&&l&&ld(t,!0)}function x(t){n=r,r=t,s=I()}function M(t,e){return N(t,e)-N(F(t),e)}function O(t){return ud(t)-ud(F(t))}function F(t){return r===t&&n||r}function N(t,e){return(B(t)?t.changedTouches[0]:t)["page"+A(e?"Y":"X")]}function B(t){return"undefined"!=typeof TouchEvent&&t instanceof TouchEvent}function U(t){d=t}return{mount:function(){g(T,Zh,Il,nc),g(T,Jh,Il,nc),g(T,Qh,w,nc),g(T,"click",C,{capture:!0}),g(T,"dragstart",ld),u([Dd,$d],_)},disable:U,isDragging:function(){return o}}},Keyboard:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.bind,l=n.unbind,d=t.root,h=e.Direction.resolve;function c(){var t=i.keyboard;t&&(s="global"===t?window:d,o(s,lc,g))}function u(){l(s,lc)}function f(){var t=r;r=!0,Ll(function(){r=t})}function g(e){if(!r){var i=oc(e);i===h(sh)?t.go("<"):i===h(rh)&&t.go(">")}}return{mount:function(){c(),a($d,u),a($d,c),a(Cd,f)},destroy:u,disable:function(t){r=t}}},LazyLoad:function(t,e,i){var s=th(t),r=s.on,n=s.off,a=s.bind,o=s.emit,l="sequential"===i.lazyLoad,d=[xd,Hd],h=[];function c(){Sl(h),e.Slides.forEach(function(t){hd(t.slide,cc).forEach(function(e){var s=sd(e,dc),r=sd(e,hc);if(s!==e.src||r!==e.srcset){var n=i.classes.spinner,a=e.parentElement,o=jl(a,"."+n)||Jl("span",n,a);h.push([e,t,o]),e.src||ed(e,"none")}})}),l?m():(n(d),r(d,u),u())}function u(){(h=h.filter(function(e){var s=i.perPage*((i.preloadPages||1)+1)-1;return!e[1].isWithin(t.index,s)||f(e)})).length||n(d)}function f(t){var e=t[0];$l(t[1].slide,qh),a(e,"load error",Al(g,t)),Zl(e,"src",sd(e,dc)),Zl(e,"srcset",sd(e,hc)),Ql(e,dc),Ql(e,hc)}function g(t,e){var i=t[0],s=t[1];cd(s.slide,qh),"error"!==e.type&&(ad(t[2]),ed(i,""),o(Xd,i,s),o(Gd)),l&&m()}function m(){h.length&&f(h.shift())}return{mount:function(){i.lazyLoad&&(c(),r(Ud,c))},destroy:Al(Sl,h),check:u}},Pagination:function(t,e,i){var s,r,n=th(t),a=n.on,o=n.emit,l=n.bind,d=e.Slides,h=e.Elements,c=e.Controller,u=c.hasFocus,f=c.getIndex,g=c.go,m=e.Direction.resolve,p=h.pagination,v=[];function y(){s&&(ad(p?bl(s.children):s),cd(s,r),Sl(v),s=null),n.destroy()}function E(t){g(">"+t,!0)}function T(t,e){var i=v.length,s=oc(e),r=S(),n=-1;s===m(rh,!1,r)?n=++t%i:s===m(sh,!1,r)?n=(--t+i)%i:"Home"===s?n=0:"End"===s&&(n=i-1);var a=v[n];a&&(id(a.button),g(">"+n),ld(e,!0))}function S(){return i.paginationDirection||i.direction}function b(t){return v[c.toPage(t)]}function A(){var t=b(f(!0)),e=b(f());if(t){var i=t.button;cd(i,Kh),Ql(i,gh),Zl(i,hh,-1)}if(e){var r=e.button;$l(r,Kh),Zl(r,gh,!0),Zl(r,hh,"")}o("pagination:updated",{list:s,items:v},t,e)}return{items:v,mount:function e(){y(),a([$d,Ud,Jd],e);var n=i.pagination;p&&ed(p,n?"":"none"),n&&(a([Cd,Vd,Hd],A),function(){var e=t.length,n=i.classes,a=i.i18n,o=i.perPage,f=u()?c.getEnd()+1:Td(e/o);$l(s=p||Jl("ul",n.pagination,h.track.parentElement),r=Fh+"--"+S()),Zl(s,dh,"tablist"),Zl(s,mh,a.select),Zl(s,yh,S()===oh?"vertical":"");for(var g=0;g<f;g++){var m=Jl("li",null,s),y=Jl("button",{class:n.page,type:"button"},m),b=d.getIn(g).map(function(t){return t.slide.id}),A=!u()&&o>1?a.pageX:a.slideX;l(y,"click",Al(E,g)),i.paginationKeyboard&&l(y,"keydown",Al(T,g)),Zl(m,dh,"presentation"),Zl(y,dh,"tab"),Zl(y,uh,b.join(" ")),Zl(y,mh,Rd(A,g+1)),Zl(y,hh,-1),v.push({li:m,button:y,page:g})}}(),A(),o("pagination:mounted",{list:s,items:v},b(t.index)))},destroy:y,getAt:b,update:A}},Sync:function(t,e,i){var s=i.isNavigation,r=i.slideFocus,n=[];function a(){var e,i;t.splides.forEach(function(e){e.isParent||(l(t,e.splide),l(e.splide,t))}),s&&(e=th(t),(i=e.on)(Md,h),i(Qd,c),i([Dd,$d],d),n.push(e),e.emit(Yd,t.splides))}function o(){n.forEach(function(t){t.destroy()}),Sl(n)}function l(t,e){var i=th(t);i.on(Cd,function(t,i,s){e.go(e.is(ec)?s:t)}),n.push(i)}function d(){Zl(e.Elements.list,yh,i.direction===oh?"vertical":"")}function h(e){t.go(e.index)}function c(t,e){Nl(uc,oc(e))&&(h(t),ld(e))}return{setup:Al(e.Media.set,{slideFocus:Cl(r)?s:r},!0),mount:a,destroy:o,remount:function(){o(),a()}}},Wheel:function(t,e,i){var s=th(t).bind,r=0;function n(s){if(s.cancelable){var n=s.deltaY,a=n<0,o=ud(s),l=i.wheelMinThreshold||0,d=i.wheelSleep||0;Sd(n)>l&&o-r>d&&(t.go(a?"<":">"),r=o),function(s){return!i.releaseWheel||t.state.is(4)||-1!==e.Controller.getAdjacent(s)}(a)&&ld(s)}}return{mount:function(){i.wheel&&s(e.Elements.track,"wheel",n,nc)}}},Live:function(t,e,i){var s=th(t).on,r=e.Elements.track,n=i.live&&!i.isNavigation,a=Jl("span",$h),o=eh(90,Al(l,!1));function l(t){Zl(r,Sh,t),t?(Gl(r,a),o.start()):(ad(a),o.cancel())}function d(t){n&&Zl(r,Th,t?"off":"polite")}return{mount:function(){n&&(d(!e.Autoplay.isPaused()),Zl(r,bh,!0),a.textContent="…",s(Wd,Al(d,!0)),s(zd,Al(d,!1)),s([xd,Hd],Al(l,!0)))},disable:d,destroy:function(){Ql(r,[Th,bh,Sh]),ad(a)}}}}),gc={type:"slide",role:"region",speed:400,perPage:1,cloneStatus:!0,arrows:!0,pagination:!0,paginationKeyboard:!0,interval:5e3,pauseOnHover:!0,pauseOnFocus:!0,resetProgress:!0,easing:"cubic-bezier(0.25, 1, 0.5, 1)",drag:!0,direction:"ltr",trimSpace:!0,focusableNodes:"a, button, textarea, input, select, iframe",live:!0,classes:Xh,i18n:{prev:"Previous slide",next:"Next slide",first:"Go to first slide",last:"Go to last slide",slideX:"Go to slide %s",pageX:"Go to page %s",play:"Start autoplay",pause:"Pause autoplay",carousel:"carousel",slide:"slide",select:"Select a slide to show",slideLabel:"%s of %s"},reducedMotion:{speed:0,rewindSpeed:0,autoplay:"pause"}};function mc(t,e,i){var s=e.Slides;function r(){s.forEach(function(t){t.style("transform","translateX(-"+100*t.index+"%)")})}return{mount:function(){th(t).on([Dd,Ud],r)},start:function(t,e){s.style("transition","opacity "+i.speed+"ms "+i.easing),Ll(e)},cancel:Il}}function pc(t,e,i){var s,r=e.Move,n=e.Controller,a=e.Scroll,o=e.Elements.list,l=Al(td,o,"transition");function d(){l(""),a.cancel()}return{mount:function(){th(t).bind(o,"transitionend",function(t){t.target===o&&s&&(d(),s())})},start:function(e,o){var d=r.toPosition(e,!0),h=r.getPosition(),c=function(e){var s=i.rewindSpeed;if(t.is(tc)&&s){var r=n.getIndex(!0),a=n.getEnd();if(0===r&&e>=a||r>=a&&0===e)return s}return i.speed}(e);Sd(d-h)>=1&&c>=1?i.useScroll?a.scroll(d,c,!1,o):(l("transform "+c+"ms "+i.easing),r.translate(d,!0),s=o):(r.jump(e),o())},cancel:d}}var vc=function(){function t(e,i){var s;this.event=th(),this.Components={},this.state=(s=1,{set:function(t){s=t},is:function(t){return Nl(Ol(t),s)}}),this.splides=[],this._o={},this._E={};var r=Pl(e)?dd(document,e):e;pd(r,r+" is invalid."),this.root=r,i=zl({label:sd(r,mh)||"",labelledby:sd(r,ph)||""},gc,t.defaults,i||{});try{zl(i,JSON.parse(sd(r,md)))}catch(t){pd(!1,"Invalid JSON")}this._o=Object.create(zl({},i))}var e=t.prototype;return e.mount=function(t,e){var i=this,s=this.state,r=this.Components;return pd(s.is([1,7]),"Already mounted!"),s.set(1),this._C=r,this._T=e||this._T||(this.is(ic)?mc:pc),this._E=t||this._E,Yl(Wl({},fc,this._E,{Transition:this._T}),function(t,e){var s=t(i,r,i._o);r[e]=s,s.setup&&s.setup()}),Yl(r,function(t){t.mount&&t.mount()}),this.emit(Dd),$l(this.root,Gh),s.set(3),this.emit(Pd),this},e.sync=function(t){return this.splides.push({splide:t}),t.splides.push({splide:this,isParent:!0}),this.state.is(3)&&(this._C.Sync.remount(),t.Components.Sync.remount()),this},e.go=function(t){return this._C.Controller.go(t),this},e.on=function(t,e){return this.event.on(t,e),this},e.off=function(t){return this.event.off(t),this},e.emit=function(t){var e;return(e=this.event).emit.apply(e,[t].concat(bl(arguments,1))),this},e.add=function(t,e){return this._C.Slides.add(t,e),this},e.remove=function(t){return this._C.Slides.remove(t),this},e.is=function(t){return this._o.type===t},e.refresh=function(){return this.emit(Ud),this},e.destroy=function(t){void 0===t&&(t=!0);var e=this.event,i=this.state;return i.is(1)?th(this).on(Pd,this.destroy.bind(this,t)):(Yl(this._C,function(e){e.destroy&&e.destroy(t)},!0),e.emit(jd),e.destroy(),t&&Sl(this.splides),i.set(7)),this},yl(t,[{key:"options",get:function(){return this._o},set:function(t){this._C.Media.set(t,!0,!0)}},{key:"length",get:function(){return this._C.Slides.getLength(!0)}},{key:"index",get:function(){return this._C.Controller.getIndex()}}]),t}(),yc=vc;yc.defaults={},yc.STATES=Tl;class Ec extends HTMLElement{static get observedAttributes(){return["collection-id","api-key","client-id","subscription-id","base-url","autoplay","show-arrows","show-dots","video-settings"]}constructor(){super(),this.splide=null,this.container=null,this.carouselElement=null,this.clientInstance=null,this.connected=!1,this.collectionData=null,this.autoplayTimeoutId=null,this.attachShadow({mode:"open"})}connectedCallback(){this.connected=!0,this.render(),this.initCarousel()}disconnectedCallback(){this.connected=!1,this.destroyCarousel()}attributeChangedCallback(t,e,i){this.connected&&e!==i&&("collection-id"!==t&&"video-settings"!==t||(this.destroyCarousel(),this.initCarousel()),"show-arrows"!==t&&"show-dots"!==t||(this.destroyCarousel(),this.initCarousel()))}getBooleanAttr(t,e){const i=this.getAttribute(t);return null===i?e:"false"!==i}getVideosFromCollection(t){if(t.videos&&t.videos.length>0)return t.videos;if(t.videoGroups&&t.videoGroups.length>0){const e=[];return t.videoGroups.forEach(t=>{t.videos&&t.videos.length>0&&e.push(...t.videos)}),e}return[]}render(){if(!this.shadowRoot)return;const t=document.createElement("style");t.textContent=`\n ${ml}\n .jaaq-collection-player {\n width: 100%;\n max-width: 1400px;\n margin: 0 auto;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n}\n\n.jaaq-collection-loading {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 400px;\n}\n\n.jaaq-collection-spinner {\n width: 50px;\n height: 50px;\n border: 4px solid rgba(0, 123, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-collection-spin 1s linear infinite;\n}\n\n@keyframes jaaq-collection-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n.jaaq-collection-error {\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n text-align: center;\n font-size: 14px;\n margin: 20px;\n}\n\n.jaaq-collection-carousel .splide__track {\n padding: 40px 0;\n}\n\n.jaaq-collection-carousel .splide__slide {\n opacity: 0.7;\n transition: all 0.3s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active {\n opacity: 1;\n}\n\n.jaaq-collection-carousel .splide__slide jaaq-video-player {\n width: 100%;\n max-width: 600px;\n transition: all 0.3s ease;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 800px;\n}\n\n.jaaq-collection-carousel .splide__arrow {\n background: rgba(0, 0, 0, 0.5);\n border: none;\n width: 48px;\n height: 48px;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n transition: all 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 20px;\n}\n\n.jaaq-collection-carousel .splide__arrow:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n}\n\n.jaaq-collection-carousel .splide__arrow:disabled {\n opacity: 0.3;\n cursor: not-allowed;\n}\n\n.jaaq-collection-carousel .splide__arrow svg {\n fill: white;\n width: 20px;\n height: 20px;\n}\n\n.jaaq-collection-carousel .splide__pagination {\n bottom: -30px;\n}\n\n.jaaq-collection-carousel .splide__pagination__page {\n background: #ccc;\n border: none;\n width: 10px;\n height: 10px;\n margin: 0 4px;\n border-radius: 50%;\n transition: all 0.2s;\n cursor: pointer;\n}\n\n.jaaq-collection-carousel .splide__pagination__page.is-active {\n background: white;\n transform: scale(1.3);\n}\n\n@media (max-width: 1024px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 650px;\n }\n}\n\n@media (max-width: 768px) {\n .jaaq-collection-carousel .splide__track {\n padding: 20px 0;\n }\n\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 400px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__arrow {\n width: 40px;\n height: 40px;\n }\n}\n\n@media (max-width: 480px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 100%;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 100%;\n }\n}\n\n .splide__container{box-sizing:border-box;position:relative}.splide__list{backface-visibility:hidden;display:-ms-flexbox;display:flex;height:100%;margin:0!important;padding:0!important}.splide.is-initialized:not(.is-active) .splide__list{display:block}.splide__pagination{-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:center;justify-content:center;margin:0;pointer-events:none}.splide__pagination li{display:inline-block;line-height:1;list-style-type:none;margin:0;pointer-events:auto}.splide:not(.is-overflow) .splide__pagination{display:none}.splide__progress__bar{width:0}.splide{position:relative;visibility:hidden}.splide.is-initialized,.splide.is-rendered{visibility:visible}.splide__slide{backface-visibility:hidden;box-sizing:border-box;-ms-flex-negative:0;flex-shrink:0;list-style-type:none!important;margin:0;position:relative}.splide__slide img{vertical-align:bottom}.splide__spinner{animation:splide-loading 1s linear infinite;border:2px solid #999;border-left-color:transparent;border-radius:50%;bottom:0;contain:strict;display:inline-block;height:20px;left:0;margin:auto;position:absolute;right:0;top:0;width:20px}.splide__sr{clip:rect(0 0 0 0);border:0;height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.splide__toggle.is-active .splide__toggle__play,.splide__toggle__pause{display:none}.splide__toggle.is-active .splide__toggle__pause{display:inline}.splide__track{overflow:hidden;position:relative;z-index:0}@keyframes splide-loading{0%{transform:rotate(0)}to{transform:rotate(1turn)}}.splide__track--draggable{-webkit-touch-callout:none;-webkit-user-select:none;-ms-user-select:none;user-select:none}.splide__track--fade>.splide__list>.splide__slide{margin:0!important;opacity:0;z-index:0}.splide__track--fade>.splide__list>.splide__slide.is-active{opacity:1;z-index:1}.splide--rtl{direction:rtl}.splide__track--ttb>.splide__list{display:block}.splide__arrow{-ms-flex-align:center;align-items:center;background:#ccc;border:0;border-radius:50%;cursor:pointer;display:-ms-flexbox;display:flex;height:2em;-ms-flex-pack:center;justify-content:center;opacity:.7;padding:0;position:absolute;top:50%;transform:translateY(-50%);width:2em;z-index:1}.splide__arrow svg{fill:#000;height:1.2em;width:1.2em}.splide__arrow:hover:not(:disabled){opacity:.9}.splide__arrow:disabled{opacity:.3}.splide__arrow:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide__arrow--prev{left:1em}.splide__arrow--prev svg{transform:scaleX(-1)}.splide__arrow--next{right:1em}.splide.is-focus-in .splide__arrow:focus{outline:3px solid #0bf;outline-offset:3px}.splide__pagination{bottom:.5em;left:0;padding:0 1em;position:absolute;right:0;z-index:1}.splide__pagination__page{background:#ccc;border:0;border-radius:50%;display:inline-block;height:8px;margin:3px;opacity:.7;padding:0;position:relative;transition:transform .2s linear;width:8px}.splide__pagination__page.is-active{background:#fff;transform:scale(1.4);z-index:1}.splide__pagination__page:hover{cursor:pointer;opacity:.9}.splide__pagination__page:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide.is-focus-in .splide__pagination__page:focus{outline:3px solid #0bf;outline-offset:3px}.splide__progress__bar{background:#ccc;height:3px}.splide__slide{-webkit-tap-highlight-color:rgba(0,0,0,0)}.splide__slide:focus{outline:0}@supports(outline-offset:-3px){.splide__slide:focus-visible{outline:3px solid #0bf;outline-offset:-3px}}@media screen and (-ms-high-contrast:none){.splide__slide:focus-visible{border:3px solid #0bf}}@supports(outline-offset:-3px){.splide.is-focus-in .splide__slide:focus{outline:3px solid #0bf;outline-offset:-3px}}@media screen and (-ms-high-contrast:none){.splide.is-focus-in .splide__slide:focus{border:3px solid #0bf}.splide.is-focus-in .splide__track>.splide__list>.splide__slide:focus{border-color:#0bf}}.splide__toggle{cursor:pointer}.splide__toggle:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide.is-focus-in .splide__toggle:focus{outline:3px solid #0bf;outline-offset:3px}.splide__track--nav>.splide__list>.splide__slide{border:3px solid transparent;cursor:pointer}.splide__track--nav>.splide__list>.splide__slide.is-active{border:3px solid #000}.splide__arrows--rtl .splide__arrow--prev{left:auto;right:1em}.splide__arrows--rtl .splide__arrow--prev svg{transform:scaleX(1)}.splide__arrows--rtl .splide__arrow--next{left:1em;right:auto}.splide__arrows--rtl .splide__arrow--next svg{transform:scaleX(-1)}.splide__arrows--ttb .splide__arrow{left:50%;transform:translate(-50%)}.splide__arrows--ttb .splide__arrow--prev{top:1em}.splide__arrows--ttb .splide__arrow--prev svg{transform:rotate(-90deg)}.splide__arrows--ttb .splide__arrow--next{bottom:1em;top:auto}.splide__arrows--ttb .splide__arrow--next svg{transform:rotate(90deg)}.splide__pagination--ttb{bottom:0;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;left:auto;padding:1em 0;right:.5em;top:0}\n \n:host {\n display: block;\n width: 100%;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n `,this.container=document.createElement("div"),this.container.className="jaaq-collection-player",this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(this.container)}async initCarousel(){if(!this.container)return;const t=this.getAttribute("collection-id");if(!t)return void this.emitError(new Error("collection-id attribute is required"));const e=this.getAttribute("api-key"),i=this.getAttribute("client-id"),s=this.getAttribute("base-url")||void 0,r=this.getAttribute("api-version")||void 0;if(this.clientInstance||e||i){this.showLoading();try{const n=this.clientInstance||ul.init({apiKey:e,clientId:i,baseUrl:s||cl,apiVersion:r});this.collectionData=await n.collections.getById(t);if(0===this.getVideosFromCollection(this.collectionData).length)return void this.emitError(new Error("No videos found in collection"));this.renderCarousel(),this.initSplide(),this.dispatchEvent(new CustomEvent("jaaq:collection:loaded",{detail:this.collectionData,bubbles:!0,composed:!0}))}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to load collection"))}}else this.emitError(new Error("Either client property or api-key and client-id attributes are required"))}showLoading(){this.container&&(this.container.innerHTML='\n <div class="jaaq-collection-loading">\n <div class="jaaq-collection-spinner"></div>\n </div>\n ')}renderCarousel(){if(!this.container||!this.collectionData)return;this.container.innerHTML="",this.carouselElement=document.createElement("div"),this.carouselElement.className="splide jaaq-collection-carousel";const t=document.createElement("div");t.className="splide__track";const e=document.createElement("ul");e.className="splide__list";const i=this.getAttribute("api-key"),s=this.getAttribute("client-id"),r=this.getAttribute("base-url"),n=this.getAttribute("video-settings");let a=null;if(n)try{a=JSON.parse(n)}catch(t){console.warn("[CollectionPlayer] Failed to parse video-settings attribute",t)}this.getVideosFromCollection(this.collectionData).forEach(t=>{const n=document.createElement("li");n.className="splide__slide";const o=document.createElement("jaaq-video-player");o.setAttribute("video-id",t.videoId),i&&o.setAttribute("api-key",i),s&&o.setAttribute("client-id",s),r&&o.setAttribute("base-url",r),o.setAttribute("autoplay","false"),o.setAttribute("width","100%"),a&&(void 0!==a.controls&&o.setAttribute("controls",String(a.controls)),void 0!==a.showLogo&&o.setAttribute("show-logo",String(a.showLogo)),void 0!==a.showTitle&&o.setAttribute("show-title",String(a.showTitle)),void 0!==a.showAuthor&&o.setAttribute("show-author",String(a.showAuthor)),void 0!==a.showDescription&&o.setAttribute("show-description",String(a.showDescription)),void 0!==a.showCaptions&&o.setAttribute("show-captions",String(a.showCaptions)),void 0!==a.startMuted&&o.setAttribute("start-muted",String(a.startMuted)),void 0!==a.width&&o.setAttribute("width",String(a.width)),void 0!==a.height&&o.setAttribute("height",String(a.height))),n.appendChild(o),e.appendChild(n)}),t.appendChild(e),this.carouselElement.appendChild(t),this.container.appendChild(this.carouselElement)}initSplide(){if(!this.carouselElement)return;const t=this.getBooleanAttr("show-arrows",!0),e=this.getBooleanAttr("show-dots",!0);this.splide=new yc(this.carouselElement,{type:"loop",perPage:3,focus:"center",gap:"0.5rem",perMove:1,autoHeight:!0,updateOnMove:!0,padding:"5 rem",breakpoints:{768:{perPage:1},1024:{perPage:2}},arrows:t,pagination:e,autoplay:!1}),this.splide.on("moved",t=>{console.log("[CollectionPlayer] Splide moved event",{newIndex:t,splideIndex:this.splide?.index,Components:this.splide?.Components}),this.handleSlideChange(t);const e=this.collectionData?this.getVideosFromCollection(this.collectionData):[];this.dispatchEvent(new CustomEvent("jaaq:collection:slidechange",{detail:{index:t,video:e[t]},bubbles:!0,composed:!0}))}),this.splide.mount(),console.log("[CollectionPlayer] After mount",{splideIndex:this.splide.index,length:this.splide.length}),setTimeout(()=>{this.splide&&(console.log("[CollectionPlayer] Initial handleSlideChange after DOM update"),this.handleSlideChange(this.splide.index))},100)}handleSlideChange(t){if(!this.carouselElement)return;const e=this.hasAttribute("autoplay")&&"false"!==this.getAttribute("autoplay");console.log("[CollectionPlayer] handleSlideChange called",{activeIndex:t,isAutoplayEnabled:e}),null!==this.autoplayTimeoutId&&(console.log("[CollectionPlayer] Clearing existing autoplay timeout",{timeoutId:this.autoplayTimeoutId}),clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null);const i=this.carouselElement.querySelector(".splide__slide.is-active:not(.splide__slide--clone)"),s=i?.querySelector("jaaq-video-player"),r=s?.getAttribute("video-id");console.log("[CollectionPlayer] Active slide from DOM:",{activeIndex:t,activeVideoId:r,foundActiveSlide:!!i});const n=this.carouselElement.querySelectorAll(".splide__slide:not(.splide__slide--clone)");Array.from(n).map((t,e)=>{const i=t.querySelector("jaaq-video-player");return{index:e,videoId:i?.getAttribute("video-id")||"unknown",isActive:t.classList.contains("is-active")}}),n.forEach((t,i)=>{const s=t.querySelector("jaaq-video-player");if(!s)return;const r=s.getAttribute("video-id");t.classList.contains("is-active")?e&&(this.autoplayTimeoutId=window.setTimeout(()=>{console.log("[CollectionPlayer] 1s delay complete, playing video",{index:i,videoId:r}),s.play?.()},1e3)):s.pause?.()})}destroyCarousel(){null!==this.autoplayTimeoutId&&(clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null),this.splide&&(this.splide.destroy(),this.splide=null),this.container&&(this.container.innerHTML=""),this.collectionData=null}emitError(t){this.container&&(this.container.innerHTML=`\n <div class="jaaq-collection-error">\n ${t.message}\n </div>\n `),this.dispatchEvent(new CustomEvent("jaaq:collection:error",{detail:t,bubbles:!0,composed:!0}))}get client(){return this.clientInstance}set client(t){this.clientInstance=t,this.connected&&(this.destroyCarousel(),this.initCarousel())}get collectionId(){return this.getAttribute("collection-id")}set collectionId(t){t?this.setAttribute("collection-id",t):this.removeAttribute("collection-id")}refresh(){this.destroyCarousel(),this.initCarousel()}next(){this.splide?.go("+1")}prev(){this.splide?.go("-1")}go(t){this.splide?.go(t)}destroy(){this.destroyCarousel()}getCollection(){return this.collectionData}}const Tc="jaaq-video-player",Sc="jaaq-collection-player";function bc(){"undefined"!=typeof window&&"undefined"!=typeof customElements?(customElements.get(Tc)||customElements.define(Tc,vl),customElements.get(Sc)||customElements.define(Sc,Ec)):console.warn("Custom Elements API is not available. Web components cannot be registered.")}"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{bc()}):bc()),t.JaaqCollectionPlayerElement=Ec,t.JaaqVideoPlayerElement=vl,t.isRegistered=function(){return"undefined"!=typeof window&&"undefined"!=typeof customElements&&(!!customElements.get(Tc)&&!!customElements.get(Sc))},t.registerJaaqComponents=bc});
|
|
8
8
|
//# sourceMappingURL=jaaq-webcomponents-bundled.min.js.map
|