@clappr/hlsjs-playback 1.8.2 → 1.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- var HlsjsPlayback=function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var s=0,i=Array(e);s<e;s++)i[s]=t[s];return i}function s(t,e,s){return e=a(e),function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,o()?Reflect.construct(e,s||[],a(t).constructor):e.apply(t,s))}function i(t,e){for(var s=0;s<e.length;s++){var i=e[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,f(i.key),i)}}function r(t,e,s){return(e=f(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function n(){return n="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,s){var i=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=a(t)););return t}(t,e);if(i){var r=Object.getOwnPropertyDescriptor(i,e);return r.get?r.get.call(arguments.length<3?t:s):r.value}},n.apply(null,arguments)}function a(t){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},a(t)}function o(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(o=function(){return!!t})()}function l(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),s.push.apply(s,i)}return s}function h(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?l(Object(s),!0).forEach((function(e){r(t,e,s[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):l(Object(s)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))}))}return t}function d(t,e){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},d(t,e)}function c(t,e,s,i){var r=n(a(1&i?t.prototype:t),e,s);return 2&i&&"function"==typeof r?function(t){return r.apply(s,t)}:r}function u(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,s){if(t){if("string"==typeof t)return e(t,s);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?e(t,s):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function f(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}const g=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},m=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=p},p=Number.MAX_SAFE_INTEGER||9007199254740991;let v=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}({}),y=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}({}),E=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 T="manifest",S="level",L="audioTrack",A="subtitleTrack",R="main",b="audio",I="subtitle";class _{constructor(t,e=0,s=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_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*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 k{constructor(t,e,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new _(t),this.fast_=new _(e),this.defaultTTFB_=i,this.ttfb_=new _(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new _(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new _(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new _(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,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 D(t,e,s){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e);if("object"!=typeof i)return i;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:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function P(){return P=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var i in s)({}).hasOwnProperty.call(s,i)&&(t[i]=s[i])}return t},P.apply(null,arguments)}function C(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),s.push.apply(s,i)}return s}function w(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?C(Object(s),!0).forEach((function(e){D(t,e,s[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):C(Object(s)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))}))}return t}class x{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 s=`[${t}]:`;this.trace=O,this.debug=e.debug.bind(null,s),this.log=e.log.bind(null,s),this.warn=e.warn.bind(null,s),this.info=e.info.bind(null,s),this.error=e.error.bind(null,s)}}const O=function(){},M={trace:O,debug:O,log:O,warn:O,info:O,error:O};function F(){return P({},M)}function N(t,e,s){return e[t]?e[t].bind(e):function(t,e){const s=self.console[t];return s?s.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):O}(t,s)}const U=F();const B=U;function $(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function G(t,e){const s=Object.keys(t),i=Object.keys(e),r=s.length,n=i.length;return!r||!n||r===n&&!s.some((t=>-1===i.indexOf(t)))}function K(t,e=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(t);if(e){const t=s.indexOf("\0");return-1!==t?s.substring(0,t):s}return s.replace(/\0/g,"")}const s=t.length;let i,r,n,a="",o=0;for(;o<s;){if(i=t[o++],0===i&&e)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=t[o++],a+=String.fromCharCode((31&i)<<6|63&r);break;case 14:r=t[o++],n=t[o++],a+=String.fromCharCode((15&i)<<12|(63&r)<<6|63&n)}}return a}const H=function(t){let e="";for(let s=0;s<t.length;s++){let i=t[s].toString(16);i.length<2&&(i="0"+i),e+=i}return e};function V(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Y,j={exports:{}};var W,q,X,z,Q,J=(Y||(Y=1,W=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,q=/^(?=([^\/?#]*))\1([^]*)$/,X=/(?:\/|^)\.(?=\/)/g,z=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,j.exports=Q={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var i=Q.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=Q.normalizePath(i.path),Q.buildURLFromParts(i)}var r=Q.parseURL(e);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return s.alwaysNormalize?(r.path=Q.normalizePath(r.path),Q.buildURLFromParts(r)):e;var n=Q.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=q.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(o.netLoc=n.netLoc,"/"!==r.path[0]))if(r.path){var l=n.path,h=l.substring(0,l.lastIndexOf("/")+1)+r.path;o.path=Q.normalizePath(h)}else o.path=n.path,r.params||(o.params=n.params,r.query||(o.query=n.query));return null===o.path&&(o.path=s.alwaysNormalize?Q.normalizePath(r.path):r.path),Q.buildURLFromParts(o)},parseURL:function(t){var e=W.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(X,"");t.length!==(t=t.replace(z,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}}),j.exports);class Z{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 tt="audio",et="video",st="audiovideo";class it{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 s=ot(t,e);s&&(s.enumerable=!0,Object.defineProperty(t,e,s))}(this,"stats")}setByteRange(t,e){const s=t.split("@",2);let i;i=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}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={[tt]:null,[et]:null,[st]: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 Z),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=J.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[tt]=null,t[et]=null,t[st]=null}}function rt(t){return"initSegment"!==t.sn}class nt extends it{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){const t=this.byteRange[0],e=this.byteRange[1];if(g(t)&&g(e))return e-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(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=g(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){const t=Object.keys(this.levelkeys),e=t.length;if(e>1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){g(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return rt(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){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:n}}}class at extends it{constructor(t,e,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;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 ot(t,e){const s=Object.getPrototypeOf(t);if(s){const t=Object.getOwnPropertyDescriptor(s,e);return t||ot(s,e)}}const lt=Math.pow(2,32)-1,ht=[].push,dt={video:1,audio:2,id3:3,text:4};function ct(t){return String.fromCharCode.apply(null,t)}function ut(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function ft(t,e){const s=mt(t,e);return s<0?4294967296+s:s}function gt(t,e){let s=ft(t,e);return s*=Math.pow(2,32),s+=ft(t,e+4),s}function mt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function pt(t,e,s){t[e]=s>>24,t[e+1]=s>>16&255,t[e+2]=s>>8&255,t[e+3]=255&s}function vt(t,e){const s=[];if(!e.length)return s;const i=t.byteLength;for(let r=0;r<i;){const n=ft(t,r),a=n>1?r+n:i;if(ct(t.subarray(r+4,r+8))===e[0])if(1===e.length)s.push(t.subarray(r+8,a));else{const i=vt(t.subarray(r+8,a),e.slice(1));i.length&&ht.apply(s,i)}r=a}return s}function yt(t){const e=[],s=t[0];let i=8;const r=ft(t,i);i+=4;let n=0,a=0;0===s?(n=ft(t,i),a=ft(t,i+4),i+=8):(n=gt(t,i),a=gt(t,i+8),i+=16),i+=2;let o=t.length+a;const l=ut(t,i);i+=2;for(let s=0;s<l;s++){let s=i;const n=ft(t,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return B.warn("SIDX has hierarchical references (not supported)"),null;const l=ft(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:e}}function Et(t){const e=[],s=vt(t,["moov","trak"]);for(let t=0;t<s.length;t++){const i=s[t],r=vt(i,["tkhd"])[0];if(r){let t=r[0];const s=ft(r,0===t?12:20),n=vt(i,["mdia","mdhd"])[0];if(n){t=n[0];const r=ft(n,0===t?12:20),a=vt(i,["mdia","hdlr"])[0];if(a){const t=ct(a.subarray(8,12)),n={soun:tt,vide:et}[t],o=Tt(vt(i,["mdia","minf","stbl","stsd"])[0]);n?(e[s]={timescale:r,type:n,stsd:o},e[n]=w({timescale:r,id:s},o)):e[s]={timescale:r,type:t,stsd:o}}}}}return vt(t,["moov","mvex","trex"]).forEach((t=>{const s=ft(t,4),i=e[s];i&&(i.default={duration:ft(t,12),flags:ft(t,20)})})),e}function Tt(t){const e=t.subarray(8),s=e.subarray(86),i=ct(e.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const t=vt(e,[i])[0];vt(t.subarray("enca"===i?28:78),["sinf"]).forEach((t=>{const e=vt(t,["schm"])[0];if(e){const s=ct(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=vt(t,["frma"])[0];e&&(n=ct(e))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=vt(s,["avcC"])[0];t&&t.length>3&&(n+="."+At(t[1])+At(t[2])+At(t[3]),r=St("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const t=vt(e,[i])[0],s=vt(t.subarray(28),["esds"])[0];if(s&&s.length>7){let t=4;if(3!==s[t++])break;t=Lt(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=Lt(s,t);const i=s[t++];if(64!==i)break;if(n+="."+At(i),t+=12,5!==s[t++])break;t=Lt(s,t);const r=s[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=vt(s,["hvcC"])[0];if(t&&t.length>12){const e=t[1],s=["","A","B","C"][e>>6],i=31&e,r=ft(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+s+i,n+="."+r.toString(16).toUpperCase(),n+="."+a+o;let h="";for(let t=l.length;t--;){const e=l[t];if(e||h){h="."+e.toString(16).toUpperCase()+h}}n+=h}r=St("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=St(n,s)||n;break;case"vp09":{const t=vt(s,["vpcC"])[0];if(t&&t.length>6){const e=t[4],s=t[5],i=t[6]>>4&15;n+="."+Rt(e)+"."+Rt(s)+"."+Rt(i)}break}case"av01":{const t=vt(s,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,i=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,h=2===e&&o?l?12:10:o?10:8,d=(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+"."+Rt(i)+a+"."+Rt(h)+"."+d+"."+c+u+f+"."+Rt(g)+"."+Rt(m)+"."+Rt(p)+"."+v,r=St("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function St(t,e){const s=vt(e,["dvvC"]),i=s.length?s[0]:vt(e,["dvcC"])[0];if(i){const e=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return t+"."+Rt(e)+"."+Rt(s)}}function Lt(t,e){const s=e+5;for(;128&t[e++]&&e<s;);return e}function At(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Rt(t){return(t<10?"0":"")+t}function bt(t){const e=vt(t,["schm"])[0];if(e){const s=ct(e.subarray(4,8));if("cbcs"===s||"cenc"===s)return vt(t,["schi","tenc"])[0]}return null}function It(t){const e=ft(t,0);let s=8;1&e&&(s+=4),4&e&&(s+=4);let i=0;const r=ft(t,4);for(let n=0;n<r;n++){if(256&e){i+=ft(t,s),s+=4}512&e&&(s+=4),1024&e&&(s+=4),2048&e&&(s+=4)}return i}function _t(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function kt(t,e){const s=[],i=e.samples,r=e.timescale,n=e.id;let a=!1;return vt(i,["moof"]).map((o=>{const l=o.byteOffset-8;vt(o,["traf"]).map((o=>{const h=vt(o,["tfdt"]).map((t=>{const e=t[0];let s=ft(t,4);return 1===e&&(s*=Math.pow(2,32),s+=ft(t,8)),s/r}))[0];return void 0!==h&&(t=h),vt(o,["tfhd"]).map((h=>{const d=ft(h,4),c=16777215&ft(h,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;d===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=ft(h,p),p+=4),f&&(g=ft(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=Dt(e.codec)),vt(o,["trun"]).map((n=>{const o=n[0],h=16777215&ft(n,0),d=!!(1&h);let c=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const L=ft(n,4);let A=8;d&&(c=ft(n,A),A+=4),f&&(A+=4);let R=c+l;for(let l=0;l<L;l++){if(m?(p=ft(n,A),A+=4):p=u,v?(y=ft(n,A),A+=4):y=g,E&&(A+=4),T&&(S=0===o?ft(n,A):mt(n,A),A+=4),e.type===et){let e=0;for(;e<y;){const n=ft(i,R);if(R+=4,Pt(a,i[R])){Ct(i.subarray(R,R+n),a?2:1,t+S/r,s)}R+=n,e+=n+4}}t+=p/r}})))}))}))})),s}function Dt(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function Pt(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Ct(t,e,s,i){const r=wt(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){B.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=ut(r,e);if(e+=2,49===t){const t=ft(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,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t<l;t++)h[t]=r[e++]}i.push({type:t,payloadType:a,pts:s,bytes:h})}}}}}else if(5===a&&o>16){const t=[];for(let s=0;s<16;s++){const i=r[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=r[e++];i.push({payloadType:a,pts:s,uuid:t.join(""),userData:K(l),userDataBytes:l})}}}function wt(t){const e=t.byteLength,s=[];let i=1;for(;i<e-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(s.push(i+2),i+=2):i++;if(0===s.length)return t;const r=e-s.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===s[0]&&(a++,s.shift()),n[i]=t[a];return n}function xt(t,e,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let i,r,n;i=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let i=8,r=s;for(;r--;)i+=e[r].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),r=0,i=8;r<s;r++)n.set(e[r],i),i+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,s||new Uint8Array)}function Ot(t){const e=t.getUint32(0),s=t.byteOffset,i=t.byteLength;if(i<e)return{offset:s,size:i};if(1886614376!==t.getUint32(4))return{offset:s,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:s,size:e};const n=t.buffer,a=H(new Uint8Array(n,s+12,16)),o=t.getUint32(28);let l=null,h=null;if(0===r){if(e-32<o||o<22)return{offset:s,size:e};h=new Uint8Array(n,s+32,o)}else if(1===r){if(!o||i<s+32+16*o+16)return{offset:s,size:e};l=[];for(let t=0;t<o;t++)l.push(new Uint8Array(n,s+32+16*t,16))}return{version:r,systemId:a,kids:l,data:h,offset:s,size:e}}const Mt=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ft={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 Nt(t,e){const s=Ft[e];return!!s&&!!s[t.slice(0,4)]}function Ut(t,e,s=!0){return!t.split(",").some((t=>!Bt(t,e,s)))}function Bt(t,e,s=!0){var i;const r=$(s);return null!=(i=null==r?void 0:r.isTypeSupported($t(t,e)))&&i}function $t(t,e){return`${e}/mp4;codecs=${t}`}function Gt(t){if(t){const e=t.substring(0,4);return Ft.video[e]}return 2}function Kt(t){const e=Mt();return t.split(",").reduce(((t,s)=>{const i=e&&Dt(s)?9:Ft.video[s];return i?(2*i+t)/(t?3:2):(Ft.audio[s]+t)/(t?2:1)}),0)}const Ht={};const Vt=/flac|opus|mp4a\.40\.34/i;function Yt(t,e=!0){return t.replace(Vt,(t=>function(t,e=!0){if(Ht[t])return Ht[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<s.length;r++){var i;if(Bt(s[r],"audio",e))return Ht[t]=s[r],s[r];if("mp3"===s[r]&&null!=(i=$(e))&&i.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e)))}function jt(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t)))return t;if(e){const s=e.split(",");if(s.length>1){if(t)for(let e=s.length;e--;)if(s[e].substring(0,4)===t.substring(0,4))return s[e];return s[0]}}return e||t}function Wt(t){if(t.startsWith("av01.")){const e=t.split("."),s=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=s[t-4];return e.join(".")}return t}function qt(t){const e=$(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 Xt(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const zt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Qt(t,e){return{supported:!1,configurations:e,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:t}}const Jt={};function Zt(t,e,s,i,r,n){const a=t.audioCodec?t.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let d=null;if(null!=a&&a.length)try{d=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce(((t,s)=>{if(s){const i=e.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach((e=>{t[e]=(t[e]||0)+i.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(i,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!d&&g(h)&&Object.keys(d).some((t=>parseInt(t)>h))}function te(t,e,s){const i=t.videoCodec,r=t.audioCodec;if(!i&&!r||!s)return Promise.resolve(zt);const n=[];if(i){const e={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},s=t.videoRange;"SDR"!==s&&(e.transferFunction=s.toLowerCase());const r=i.split(","),a=navigator.userAgent;if(r.some((t=>Dt(t)))&&Mt())return Promise.resolve(Qt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${a})`),n));n.push.apply(n,r.map((t=>({type:"media-source",video:w(w({},e),{},{contentType:$t(Wt(t),"video")})}))))}return r&&t.audioGroups&&t.audioGroups.forEach((t=>{var s;t&&(null==(s=e.groups[t])||s.tracks.forEach((e=>{if(e.groupId===t){const t=e.channels||"",s=parseFloat(t);g(s)&&s>2&&n.push.apply(n,r.split(",").map((t=>({type:"media-source",audio:{contentType:$t(t,"audio"),channels:""+s}}))))}})))})),Promise.all(n.map((t=>{const e=function(t){const{audio:e,video:s}=t,i=s||e;if(i){const t=Xt(i.contentType);if(s)return`r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${t}_${Math.ceil(s.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return Jt[e]||(Jt[e]=s.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:n,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t})))}const ee=["NONE","TYPE-0","TYPE-1",null];const se=["SDR","PQ","HLG"];var ie="",re="YES",ne="v2";function ae(t){const{canSkipUntil:e,canSkipDateRanges:s,age:i}=t;return e&&i<e/2?s?ne:re:ie}class oe{constructor(t,e,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=s}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 le{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 s=null==(e=t.supplemental)?void 0:e.videoCodec;s&&s!==t.videoCodec&&(this.codecSet+=`,${s.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 he(this._audioGroups,t)}hasSubtitleGroup(t){return he(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 he(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function de(t,e){let s=!1,i=[];if(t&&(s="SDR"!==t,i=[t]),e){i=e.allowedVideoRanges||se.slice(0);const t="SDR"!==i.join("")&&!e.videoCodec;s=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}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}const ce=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(s,i)=>{if(t&&(i=t(s,i)),"object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}})(e));function ue(t,e){B.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function fe(t){return t.reduce(((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ge(t){if(!t)return t;const{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}=t;return{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function me(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let i=0;i<e.length;i++){if(pe(t,e[i],s))return i}return-1}function pe(t,e,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===i||e.groupId===i)&&(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 s=t.split(","),i=e.split(",");return s.length===i.length&&!s.some((t=>-1===i.indexOf(t)))}(t.characteristics||"",e.characteristics))&&(void 0===s||s(t,e))}function ve(t,e){const{audioCodec:s,channels:i}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(e.channels||"2"))}function ye(t,e,s){for(let i=e;i>-1;i--)if(s(t[i]))return i;for(let i=e+1;i<t.length;i++)if(s(t[i]))return i;return-1}function Ee(t,e){var s;return!!t&&t!==(null==(s=e.loadLevelObj)?void 0:s.uri)}const Te=function(t,e){let s=0,i=t.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=t[r];const a=e(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function Se(t,e,s=0,i=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const i=t.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===s&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Le(s,i,n)||function(t,e,s){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const i=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),s);return t.start<=i}return!1}(n,t,Math.min(r,i))))return n;const a=Te(e,Le.bind(null,s,i));return!a||a===t&&n?n:a}function Le(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const i=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=t?1:s.start-i>t&&s.start?-1:0}function Ae(t,e,s){const i=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>t}function Re(t,e){return Te(t,(t=>t.cc<e?1:t.cc>e?-1:0))}function be(t){switch(t.details){case y.FRAG_LOAD_TIMEOUT:case y.KEY_LOAD_TIMEOUT:case y.LEVEL_LOAD_TIMEOUT:case y.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ie(t,e){const s=be(e);return t.default[(s?"timeout":"error")+"Retry"]}function _e(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function ke(t){return w(w({},t),{errorRetry:null,timeoutRetry:null})}function De(t,e,s,i){if(!t)return!1;const r=null==i?void 0:i.code,n=e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(r)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,i,n):n}var Pe=0,Ce=2,we=3,xe=5,Oe=0,Me=1,Fe=2;function Ne(t){const e={action:Pe,flags:Oe};return t&&(e.resolved=!0),e}var Ue="NOT_LOADED",Be="APPENDING",$e="PARTIAL",Ge="OK";class Ke{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.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.BUFFER_APPENDED,this.onBufferAppended,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this),t.on(E.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.BUFFER_APPENDED,this.onBufferAppended,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this),t.off(E.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let e=s.length;e--;){const i=s[e];if(!i)break;const r=i.end;if(i.start<=t&&null!==r&&t<=r)return i}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===e&&(!s||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s,i,r){this.timeRanges&&(this.timeRanges[t]=e);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[t];o&&(0!==o.time.length?o.time.some((t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(a.body),s})):this.removeFragment(a.body))}))}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const s=t.frag,i=Ve(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;if(Object.keys(e).forEach((i=>{const a=s.elementaryStreams[i];if(!a)return;const o=e[i],l=n||!0===a.partial;r.range[i]=this.getBufferedTimes(s,t.part,l,o)})),r.loaded=null,Object.keys(r.range).length){r.buffered=!0;(r.body.endList=s.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),He(r)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(r.body)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=Ye(s,(e=>e.fragment.sn>=t)))}fragBuffered(t,e){const s=Ve(t);let i=this.fragments[s];!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<i.length;t++){const e=i.start(t)-this.bufferPadding,s=i.end(t)+this.bufferPadding;if(l>=e&&o<=s){r.time.push({startPTS:Math.max(n,i.start(t)),endPTS:Math.min(a,i.end(t))});break}if(n<s&&a>e){const e=Math.max(n,i.start(t)),s=Math.min(a,i.end(t));s>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:s}))}else if(a<=e)break}return r}getPartialFragment(t){let e,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&He(h)&&(s=h.body.start-a,i=h.body.end+a,t>=s&&t<=i&&(e=Math.min(t-s,i-t),n<=e&&(r=h.body,n=e)))})),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||He(e))}getState(t){const e=Ve(t),s=this.fragments[e];return s?s.buffered?He(s)?$e:Ge:Be:Ue}isTimeBuffered(t,e,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,t>=i&&e<=r)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const s=e.frag,i=e.part?null:e,r=Ve(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r,type:n}=e;if("initSegment"===s.sn)return;const a=s.type;if(i){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(i)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Ve(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,s=Object.keys(e);if(!t)return s.length>0;for(let i=s.length;i--;){const r=e[s[i]];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,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)}))}removeFragment(t){const e=Ve(t);t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=Ye(s,(t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t,e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const s=null==(t=this.hls)||null==(e=t.latestLevelDetails)?void 0:e.partList;s&&s.forEach((t=>t.clearElementaryStreamInfo()))}}function He(t){var e,s,i;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial)||(null==(i=t.range.audiovideo)?void 0:i.partial))}function Ve(t){return`${t.type}_${t.level}_${t.sn}`}function Ye(t,e){return t.filter((t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s}))}var je=0,We=1;class qe{constructor(t,e,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=s}decrypt(t,e){switch(this.aesMode){case je:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case We: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 Xe{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),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=e.getUint32(4*t);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=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 s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[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[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i<e.length&&s;)s=e[i]===this.key[i],i++;if(s)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),h=this.invKeySchedule=new Uint32Array(n),d=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=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=c[a/r|0]<<24):r>6&&a%r==4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[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],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);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,L,A,R,b,I,_,k,D,P,C;const w=this.networkToHostOrderSwap;for(;e<p.length;){for(I=w(p[e]),_=w(p[e+1]),k=w(p[e+2]),D=w(p[e+3]),L=I^r[0],A=D^r[1],R=k^r[2],b=_^r[3],P=4,C=1;C<i;C++)y=o[L>>>24]^l[A>>16&255]^h[R>>8&255]^d[255&b]^r[P],E=o[A>>>24]^l[R>>16&255]^h[b>>8&255]^d[255&L]^r[P+1],T=o[R>>>24]^l[b>>16&255]^h[L>>8&255]^d[255&A]^r[P+2],S=o[b>>>24]^l[L>>16&255]^h[A>>8&255]^d[255&R]^r[P+3],L=y,A=E,R=T,b=S,P+=4;y=n[L>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&b]^r[P],E=n[A>>>24]<<24^n[R>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^r[P+1],T=n[R>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&A]^r[P+2],S=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[255&R]^r[P+3],v[e]=w(y^u),v[e+1]=w(S^f),v[e+2]=w(T^g),v[e+3]=w(E^m),u=I,f=_,g=k,m=D,e+=4}return v.buffer}}class ze{constructor(t,e,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=s}expandKey(){const t=function(t){switch(t){case je:return"AES-CBC";case We: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 Qe{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 s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?t.slice(0,e-s):t}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s,i){return this.useSoftware?new Promise(((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,s,i)}softwareDecrypt(t,e,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==je||16!==e.byteLength)return B.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=_t(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Xe),l.expandKey(e);const h=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(t,e,s,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,s,i));this.key=e,this.fastAesKey=new ze(this.subtle,e,i)}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 qe(this.subtle,new Uint8Array(s),i).decrypt(t.buffer,e)})).catch((r=>(B.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s,i))))}onWebCryptoError(t,e,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s,i);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 s=t.length-t.length%16;return s!==t.length&&(e=t.slice(0,s),this.remainderData=t.slice(s)),e}logOnce(t){this.logEnabled&&(B.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Je=Math.pow(2,17);class Ze{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 s=t.url;if(!s)return Promise.reject(new ss({type:v.NETWORK_ERROR,details:y.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(es(t));t.gap=!1}const l=this.loader=r?new r(i):new n(i),h=ts(t);t.loader=l;const d=ke(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Je};t.stats=l.stats;const u={onSuccess:(e,s,i,r)=>{this.resetLoader(t,l);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,i,r,n)=>{this.resetLoader(t,l),o(new ss({type:v.NETWORK_ERROR,details:y.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:w({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:n}))},onAbort:(e,s,i)=>{this.resetLoader(t,l),o(new ss({type:v.NETWORK_ERROR,details:y.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,s,i)=>{this.resetLoader(t,l),o(new ss({type:v.NETWORK_ERROR,details:y.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:e}))}};e&&(u.onProgress=(s,i,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})),l.load(h,c,u)}))}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(es(t,e));const l=this.loader=r?new r(i):new n(i),h=ts(t,e);t.loader=l;const d=ke(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Je};e.stats=l.stats,l.load(h,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const h={frag:t,part:e,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(t,l),o(new ss({type:v.NETWORK_ERROR,details:y.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:w({url:h.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new ss({type:v.NETWORK_ERROR,details:y.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(t,l),o(new ss({type:v.NETWORK_ERROR,details:y.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})}))}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.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 ts(t,e=null){const s=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(g(r)&&g(n)){var a;let e=r,s=n;if("initSegment"===t.sn&&("AES-128"===(o=null==(a=t.decryptdata)?void 0:a.method)||"AES-256"===o)){const t=n-r;t%16&&(s=n+(16-t%16)),0!==r&&(i.resetIV=!0,e=r-16)}i.rangeStart=e,i.rangeEnd=s}var o;return i}function es(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:v.MEDIA_ERROR,details:y.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new ss(i)}class ss extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class is extends x{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 rs{constructor(t,e,s,i=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=s,this.size=i,this.part=r,this.partial=n}}const ns={length:0,start:()=>0,end:()=>0};class as{static isBuffered(t,e){if(t){const s=as.getBuffered(t);for(let t=s.length;t--;)if(e>=s.start(t)&&e<=s.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=as.getBuffered(t);return as.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let s=0;s<t.length;s++)e.push({start:t.start(s),end:t.end(s)});return e}static bufferInfo(t,e,s){if(t){const i=as.bufferedRanges(t);if(i.length)return as.bufferedInfo(i,e,s)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.length>1&&t.sort(((t,e)=>t.start-e.start||e.end-t.end));let i=-1,r=[];if(s)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(i=n);const a=r.length;if(a){const e=r[a-1].end;t[n].start-e<s?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 h=r[t].start,d=r[t].end;if(-1===i&&e>=h&&e<=d&&(i=t),e+s>=h&&e<d)o=h,l=d,a=l-e;else if(e+s<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:i}}static getBuffered(t){try{return t.buffered||ns}catch(t){return B.log("failed to get media.buffered",t),ns}}}const os=/\{\$([a-zA-Z0-9-_]+)\}/g;function ls(t){return os.test(t)}function hs(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(os,(e=>{const i=e.substring(2,e.length-1),r=null==s?void 0:s[i];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),e):r}))}return e}function ds(t,e,s){let i,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=t.get(i)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function cs(t,e,s){const i=e.IMPORT;if(s&&i in s){let e=t.variableList;e||(t.variableList=e={}),e[i]=s[i]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const us=/^(\d+)x(\d+)$/,fs=/(.+?)=(".*?"|.*?)(?:,|$)/g;class gs{constructor(t,e){"string"==typeof t&&(t=gs.parseAttrList(t,e)),P(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 s=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)s[t]=parseInt(e.slice(2*t,2*t+2),16);return s}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 s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce(((t,e)=>(t[e.toLowerCase()]=!0,t)),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=us.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let s;const i={};for(fs.lastIndex=0;null!==(s=fs.exec(t));){const r=s[1].trim();let n=s[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=hs(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":B.warn(`${t}: attribute ${r} is missing quotes`)}i[r]=n}return i}}function ms(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class ps{constructor(t,e,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(i=null==e?void 0:e.tagOrder)?i:s,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){B.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=P(new gs({}),s,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);g(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?(B.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(g(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&&g(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 vs{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,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}get hasProgramDateTime(){return!!this.fragments.length&&g(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(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var t;return null!=(t=this.fragments)&&t.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 s=t.length;s--;)if(t[s].index>e)return t[s].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 ys(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function Es(t){switch(t){case"AES-128":case"AES-256":return je;case"AES-256-CTR":return We;default:throw new Error(`invalid full segment method ${t}`)}}function Ts(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function Ss(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}function Ls(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),i=t[t.length-1].split(",");if(2===i.length){const e="base64"===i[0],r=i[1];e?(t.splice(-1,1),s=Ts(r)):s=function(t){const e=Ss(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(r)}}return s}const As="undefined"!=typeof self?self:void 0;var Rs={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},bs="org.w3.clearkey",Is="com.apple.streamingkeydelivery",_s="com.microsoft.playready",ks="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Ds(t){switch(t){case Is:return Rs.FAIRPLAY;case _s:return Rs.PLAYREADY;case ks:return Rs.WIDEVINE;case bs:return Rs.CLEARKEY}}var Ps="1077efecc0b24d02ace33c1e52e2fb4b",Cs="e2719d58a985b3c9781ab030af78d30e",ws="9a04f07998404286ab92e65be0885f95",xs="edef8ba979d64acea3c827dcd51d21ed";function Os(t){return t===xs?Rs.WIDEVINE:t===ws?Rs.PLAYREADY:t===Ps||t===Cs?Rs.CLEARKEY:void 0}function Ms(t){switch(t){case Rs.FAIRPLAY:return Is;case Rs.PLAYREADY:return _s;case Rs.WIDEVINE:return ks;case Rs.CLEARKEY:return bs}}function Fs(t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?[Rs.FAIRPLAY,Rs.WIDEVINE,Rs.PLAYREADY,Rs.CLEARKEY].filter((t=>!!e[t])):[];return!i[Rs.WIDEVINE]&&s&&i.push(Rs.WIDEVINE),i}const Ns=null!=As&&null!=(Us=As.navigator)&&Us.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Us;function Bs(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),s=String.fromCharCode.apply(null,Array.from(e)),i=s.substring(s.indexOf("<"),s.length),r=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(r){const t=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(t){const e=Ts(t).subarray(0,16);return function(t){const e=function(t,e,s){const i=t[e];t[e]=t[s],t[s]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),e}}return null}let $s={};class Gs{static clearKeyUriToKeyIdMap(){$s={}}constructor(t,e,s,i=[1],r=null){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=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ys(t)}isSupported(){if(this.method){if(ys(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Is:case ks:case _s:case bs:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if(ys(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&(B.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const e=function(t){const e=new Uint8Array(16);for(let s=12;s<16;s++)e[s]=t>>8*(15-s)&255;return e}(t);return new Gs(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=Ls(this.uri);if(e)switch(this.keyFormat){case ks:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case _s:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=xt(t,0,e),this.keyId=Bs(e);break}default:{let t=e.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=$s[this.uri];if(!t){const e=Object.keys($s).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),$s[this.uri]=t}this.keyId=t}return this}}const Ks=/#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,Hs=/#EXT-X-MEDIA:(.*)/g,Vs=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ys=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),js=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 Ws{static findGroup(t,e){for(let s=0;s<t.length;s++){const i=t[s];if(i.id===e)return i}}static resolve(t,e){return J.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Vs.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:ls(t)},i=[];let r;for(Ks.lastIndex=0;null!=(r=Ks.exec(t));)if(r[1]){var n;const t=new gs(r[1],s),a=hs(s,r[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Ws.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Js(t.CODECS,o);const h=t["SUPPLEMENTAL-CODECS"];h&&(o.supplemental={},Js(h,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||i.push(o),s.levels.push(o)}else if(r[3]){const t=r[3],i=r[4];switch(t){case"SESSION-DATA":{const t=new gs(i,s),e=t["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=t);break}case"SESSION-KEY":{const t=zs(i,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):B.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":ds(s,new gs(i,s),e);break;case"CONTENT-STEERING":{const t=new gs(i,s);s.contentSteering={uri:Ws.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Qs(i)}}const a=i.length>0&&i.length<s.levels.length;return s.levels=a?i:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,s){let i;const r={},n=s.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(Hs.lastIndex=0;null!==(i=Hs.exec(t));){const t=new gs(i[1],s),n=t.TYPE;if(n){const s=a[n],i=r[n]||[];r[n]=i;const l=t.LANGUAGE,h=t["ASSOC-LANGUAGE"],d=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?Ws.resolve(t.URI,e):""};if(h&&(f.assocLang=h),d&&(f.channels=d),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=s&&s.length){const t=Ws.findGroup(s,f.groupId)||s[0];Zs(f,t,"audioCodec"),Zs(f,t,"textCodec")}i.push(f)}}return r}static parseLevelPlaylist(t,e,s,i,r,n){var a;const o={url:e},l=new vs(e),h=l.fragments,d=[];let c,u,f,m,p=null,v=0,y=0,E=0,T=0,S=0,L=null,A=new nt(i,o),R=-1,b=!1,I=null;if(Ys.lastIndex=0,l.m3u8=t,l.hasVariableRefs=ls(t),"#EXTM3U"!==(null==(a=Ys.exec(t))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=Ys.exec(t));){b&&(b=!1,A=new nt(i,o),A.playlistOffset=E,A.start=E,A.sn=v,A.cc=T,S&&(A.bitrate=S),A.level=s,p&&(A.initSegment=p,p.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),I&&(A.setByteRange(I),I=null)));const t=c[1];if(t){A.duration=parseFloat(t);const e=(" "+c[2]).slice(1);A.title=e||null,A.tagList.push(e?["INF",t,e]:["INF",t])}else if(c[3]){if(g(A.duration)){A.playlistOffset=E,A.start=E,f&&si(A,f,l),A.sn=v,A.level=s,A.cc=T,h.push(A);const t=(" "+c[3]).slice(1);A.relurl=hs(l,t),ti(A,L,d),L=A,E+=A.duration,v++,y=0,b=!0}}else{if(c=c[0].match(js),!c){B.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const t=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(t){case"BYTERANGE":L?A.setByteRange(r,L):A.setByteRange(r);break;case"PROGRAM-DATE-TIME":A.rawProgramDateTime=r,A.tagList.push(["PROGRAM-DATE-TIME",r]),-1===R&&(R=h.length);break;case"PLAYLIST-TYPE":l.type&&ii(l,t,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?ii(l,t,c):h.length>0&&ri(l,t,c),v=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&ii(l,t,c);const e=new gs(r,l),s=e.decimalInteger("SKIPPED-SEGMENTS");if(g(s)){l.skippedSegments+=s;for(let t=s;t--;)h.push(null);v+=s}const i=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&ii(l,t,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&ii(l,t,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||ii(l,t,c),l.live=!1;break;case"#":(r||a)&&A.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":T++,A.tagList.push(["DIS"]);break;case"GAP":A.gap=!0,A.tagList.push([t]);break;case"BITRATE":A.tagList.push([t,r]),S=1e3*parseInt(r),g(S)?A.bitrate=S:S=0;break;case"DATERANGE":{const t=new gs(r,l),e=new ps(t,l.dateRanges[t.ID],l.dateRangeTagCount);l.dateRangeTagCount++,e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:B.warn(`Ignoring invalid DATERANGE tag: "${r}"`),A.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new gs(r,l);"IMPORT"in t?cs(l,t,n):ds(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?ii(l,t,c):h.length>0&&ri(l,t,c),l.startCC=T=parseInt(r);break;case"KEY":{const t=zs(r,e,l);if(t.isSupported()){if("NONE"===t.method){f=void 0;break}f||(f={}),f[t.keyFormat]&&(f=P({},f)),f[t.keyFormat]=t}else B.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=Qs(r);break;case"MAP":{const t=new gs(r,l);if(A.duration){const e=new nt(i,o);ei(e,t,s,f),p=e,A.initSegment=p,p.rawProgramDateTime&&!A.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime)}else{const e=A.byteRangeEndOffset;if(e){const t=A.byteRangeStartOffset;I=`${e-t}@${t}`}else I=null;ei(A,t,s,f),p=A,b=!0}p.cc=T;break}case"SERVER-CONTROL":m&&ii(l,t,c),m=new gs(r),l.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),l.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&ii(l,t,c);const e=new gs(r);l.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=l.partList;t||(t=l.partList=[]);const e=y>0?t[t.length-1]:void 0,s=y++,i=new gs(r,l),n=new at(i,A,o,s,e);t.push(n),A.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new gs(r,l);l.preloadHint=t;break}case"RENDITION-REPORT":{const t=new gs(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:B.warn(`line parsed but not handled: ${c}`)}}}L&&!L.relurl?(h.pop(),E-=L.duration,l.partList&&(l.fragmentHint=L)):l.partList&&(ti(A,L,d),A.cc=T,l.fragmentHint=A,f&&si(A,f,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const _=h.length,k=h[0],D=h[_-1];if(E+=l.skippedSegments*l.targetduration,E>0&&_&&D){l.averagetargetduration=E/_;const t=D.sn;l.endSN="initSegment"!==t?t:0,l.live||(D.endList=!0),k&&void 0===l.startCC&&(l.startCC=k.cc),R>0&&(!function(t,e){let s=t[e];for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(h,R),k&&d.unshift(k))}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(E+=l.fragmentHint.duration),l.totalduration=E,d.length&&l.dateRangeTagCount&&k&&qs(d,l),l.endCC=T,l}}function qs(t,e){const s=t.length,i=t[s-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let a=n.length;a--;){const o=e.dateRanges[n[a]],l=o.startDate.getTime();o.tagAnchor=i.ref;for(let i=s;i--;){const s=Xs(e,l,t,i,r);if(-1!==s){o.tagAnchor=e.fragments[s].ref;break}}}}function Xs(t,e,s,i,r){const n=s[i];if(n){const o=n.programDateTime;if(e>=o||0===i){var a;if(e<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-t.startSN,n=t.fragments;if(n.length>s.length){for(let a=(s[i+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 zs(t,e,s){var i,r;const n=new gs(t,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&B.error(`Invalid IV: ${n.IV}`);const c=o?Ws.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Gs(a,c,d,u,l)}function Qs(t){const e=new gs(t).decimalFloatingPoint("TIME-OFFSET");return g(e)?e:null}function Js(t,e){let s=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const i=s.filter((e=>Nt(e,t)));i.length&&(e[`${t}Codec`]=i.map((t=>t.split("/")[0])).join(","),s=s.filter((t=>-1===i.indexOf(t))))})),e.unknownCodecs=s}function Zs(t,e,s){const i=e[s];i&&(t[s]=i)}function ti(t,e,s){t.rawProgramDateTime?s.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function ei(t,e,s,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function si(t,e,s){t.levelkeys=e;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||i.push(t)}function ii(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${s[0]})`)}function ri(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${s[0]})`)}function ni(t,e){const s=e.startPTS;if(g(s)){let i,r=0;e.sn>t.sn?(r=s-t.start,i=t):(r=t.start-s,i=e),i.duration!==r&&i.setDuration(r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function ai(t,e,s,i,r,n){i-s<=0&&(B.warn("Fragment should have a positive duration",e),i=s+e.duration,n=r+e.duration);let a=s,o=i;const l=e.startPTS,h=e.endPTS;if(g(l)){const t=Math.abs(l-s);g(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(s,l),s=Math.min(s,l),r=Math.min(r,e.startDTS),o=Math.min(i,h),i=Math.max(i,h),n=Math.max(n,e.endDTS)}const d=s-e.start;0!==e.start&&e.setStart(s),e.setDuration(i-e.start),e.startPTS=s,e.maxStartPTS=a,e.startDTS=r,e.endPTS=i,e.minEndPTS=o,e.endDTS=n;const c=e.sn;if(!t||c<t.startSN||c>t.endSN)return 0;let u;const f=c-t.startSN,m=t.fragments;for(m[f]=e,u=f;u>0;u--)ni(m[u],m[u-1]);for(u=f;u<m.length-1;u++)ni(m[u],m[u+1]);return t.fragmentHint&&ni(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,d}function oi(t,e){if(t===e)return;let s=null;const i=t.fragments;for(let t=i.length-1;t>=0;t--){const e=i[t].initSegment;if(e){s=e;break}}let r;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,s){const i=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?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 h=r;h<=n;h++){const r=l[a+h];let n=o[h];if(i&&!n&&r&&(n=e.fragments[h]=r),r&&n){if(s(r,n,h,o),r.url&&r.url!==n.url)return void(e.playlistParsingError=li(`media sequence mismatch ${n.sn}:`,t,e,r,n));if(r.cc!==n.cc)return void(e.playlistParsingError=li(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,t,e,r,n))}}}(t,e,((i,n,a,o)=>{if(!e.startCC&&n.cc!==i.cc){var l,h;const s=i.cc-n.cc;for(let t=a;t<o.length;t++)o[t].cc+=s;e.startCC=null!=(l=null==(h=ui(t,e.startSN-1))?void 0:h.cc)?l:o[0].cc,e.endCC=o[o.length-1].cc}g(i.startPTS)&&g(i.endPTS)&&(n.setStart(n.startPTS=i.startPTS),n.startDTS=i.startDTS,n.maxStartPTS=i.maxStartPTS,n.endPTS=i.endPTS,n.endDTS=i.endDTS,n.minEndPTS=i.minEndPTS,n.setDuration(i.endPTS-i.startPTS),n.duration&&(r=n),e.PTSKnown=e.alignedSliding=!0),i.hasStreams&&(n.elementaryStreams=i.elementaryStreams),n.loader=i.loader,i.hasStats&&(n.stats=i.stats),i.initSegment&&(n.initSegment=i.initSegment,s=i.initSegment)}));const n=e.fragments,a=e.fragmentHint?n.concat(e.fragmentHint):n;if(s&&a.forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)})),e.skippedSegments)if(e.deltaUpdateFailed=n.some((t=>!t)),e.deltaUpdateFailed){B.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)n.shift();e.startSN=n[0].sn}else{e.endCC=n[n.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=function(t,e){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=P({},t);i&&i.forEach((t=>{delete r[t]}));const n=Object.keys(r).length;n&&Object.keys(s).forEach((t=>{const e=r[t],i=new ps(s[t].attr,e);i.isValid?(r[t]=i,e||(i.tagOrder+=n)):B.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ce(s[t].attr)}"`)}));return r}(t.dateRanges,e));const s=t.fragments.filter((t=>t.rawProgramDateTime));if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<a.length;t++)null===a[t].programDateTime&&ti(a[t],a[t-1],s);qs(s,e)}!function(t,e,s){if(t&&e){let i=0;for(let r=0,n=t.length;r<=n;r++){const n=t[r],a=e[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(t.partList,e.partList,((t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),r?ai(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):hi(t,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const t=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=t),e.driftEndTime=o,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function li(t,e,s,i,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function hi(t,e,s=!0){const i=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,n=i>=0;let a=0;if(n&&i<r.length)a=r[i].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&s)a=t.fragmentStart+i*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}di(e,a)}function di(t,e){if(e){const s=t.fragments;for(let i=t.skippedSegments;i<s.length;i++)s[i].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function ci(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const i=t.fragments,r=4;if(i.length&&s*r>e){const t=1e3*i[i.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}function ui(t,e,s){if(!t)return null;let i=t.fragments[e-t.startSN];return i||(i=t.fragmentHint,i&&i.sn===e?i:e<t.startSN&&s&&s.sn===e?s:null)}function fi(t,e,s){return t?gi(t.partList,e,s):null}function gi(t,e,s){if(t)for(let i=t.length;i--;){const r=t[i];if(r.index===s&&r.fragment.sn===e)return r}return null}function mi(t){t.forEach(((t,e)=>{var s;null==(s=t.details)||s.fragments.forEach((t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)}))}))}function pi(t,e){for(let i=0,r=t.length;i<r;i++){var s;if((null==(s=t[i])?void 0:s.cc)===e)return t[i]}return null}function vi(t,e){if(t){const s=t.start+e;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function yi(t,e){const s=e.fragments;for(let e=0,i=s.length;e<i;e++)vi(s[e],t);e.fragmentHint&&vi(e.fragmentHint,t),e.alignedSliding=!0}function Ei(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const s=Math.min(e.endCC,t.endCC),i=pi(e.fragments,s),r=pi(t.fragments,s);if(!i||!r)return;B.log(`Aligning playlist at start of dicontinuity sequence ${s}`);yi(i.start-r.start,t)}function Ti(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,i=e.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(r=pi(i,a),n=pi(s,a)),r&&n||(r=i[Math.floor(i.length/2)],n=pi(s,r.cc)||s[Math.floor(s.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;yi((l-o)/1e3-(n.start-r.start),t)}const Si=function(t){let e="";const s=t.length;for(let i=0;i<s;i++)e+=`[${t.start(i).toFixed(3)}-${t.end(i).toFixed(3)}]`;return e},Li="STOPPED",Ai="IDLE",Ri="KEY_LOADING",bi="FRAG_LOADING",Ii="FRAG_LOADING_WAITING_RETRY",_i="WAITING_TRACK",ki="PARSING",Di="PARSED",Pi="ENDED",Ci="ERROR",wi="WAITING_INIT_PTS",xi="WAITING_LEVEL";class Oi extends is{constructor(t,e,s,i,r){super(i,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Li,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:e,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=as.bufferInfo(i||s,n,t.maxBufferHole);if(this.log(`media seeking to ${g(n)?n.toFixed(3):n}, state: ${r}`),this.state===Pi)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,i=e.start-s,r=e.start+e.duration+s;if(!a.len||r<a.start||i>a.end){const t=n>r;(n<i||t)&&(t&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}}this.hls.hasEnoughToStart||a.len||(this.log(`setting startPosition to ${n} because of seek before start`),this.nextLoadPosition=this.startPosition=n),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Ze(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Qe(t.config)}registerListeners(){const{hls:t}=this;t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Li)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=Li}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 s=t.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=t.nextStart;if(r&&r>i&&r<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const n=e.partList;if(null!=n&&n.length){const t=n[n.length-1];return as.isBuffered(this.media,t.start+t.duration/2)}const a=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(a)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.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 s=this.media=this.mediaBuffer=e.media;s.removeEventListener("seeking",this.onMediaSeeking),s.removeEventListener("ended",this.onMediaEnded),s.addEventListener("seeking",this.onMediaSeeking),s.addEventListener("ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Li&&this.startLoad(i.startPosition)}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)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=Li,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,s){this.startFragRequested=!0,this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){this._doFragLoad(t,e,s,(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,s=t.frag;this.fragContextChanged(s)?(e===bi||!this.fragCurrent&&e===ki)&&(this.fragmentTracker.removeFragment(s),this.state=Ai):("payload"in t&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(E.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((e=>{this.state!==Li&&this.state!==Ci&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===Be){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===$e&&s.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,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger(E.BUFFER_FLUSHING,i)}_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:s,payload:i}=t,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&ys(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,Es(r.method)).catch((t=>{throw e.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:s}),t})).then((i=>{const r=self.performance.now();return e.trigger(E.FRAG_DECRYPTED,{frag:s,payload:i,stats:{tstart:n,tdecrypt:r}}),t.payload=i,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((e=>{this.state!==Li&&this.state!==Ci&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state!==Li&&(this.state=Ai),t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const s=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:${s?Si(as.getBuffered(s)):"(detached)"})`),rt(t)){var i;if(t.type!==I){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=Ai)}const e=null==(i=this.levels)?void 0:i[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=Ai}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:s,part:i,partsLoaded:r}=t,n=!r||0===r.length||r.some((t=>!t)),a=new rs(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,i){var r;this.fragCurrent=t;const n=null==e?void 0:e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;!t.encrypted||null!=(r=t.decryptdata)&&r.key?!t.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(t,n.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=Ri,this.fragCurrent=t,a=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(E.KEY_LOADED,t),this.state===Ri&&(this.state=Ai),t})),this.hls.trigger(E.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));const o=this.fragPrevious;if(rt(t)&&(!o||t.sn!==o.sn)){const s=this.shouldLoadParts(e.details,t.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=s)}if(s=Math.max(t.start,s||0),this.loadingParts&&rt(t)){const r=n.partList;if(r&&i){s>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(r,t,s);if(o>-1){const l=r[o];let h;return t=this.fragCurrent=l.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(t,!1,l)}) cc: ${t.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=bi,h=a?a.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,l,e,i))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,l,e,i).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(E.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}if(rt(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)}`),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} ${n?"["+n.startSN+"-"+n.endSN+"]":""}, target: ${parseFloat(s.toFixed(3))}`),g(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=bi;const l=this.config.progressive;let h;return h=l&&a?a.then((e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,i))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,l?i:void 0),a]).then((([t])=>(!l&&t&&i&&i(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(E.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,s,i){return new Promise(((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,i).then((i=>{o[e.index]=i;const n=i.part;this.hls.trigger(E.FRAG_LOADED,i);const a=fi(s.details,t.sn,e.index+1)||gi(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});h(a)})).catch(n)};h(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===y.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(E.ERROR,e)}else this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:y.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==ki)return void(this.fragCurrent||this.state===Li||this.state===Ci||(this.state=Ai));const{frag:s,part:i,level:r}=e,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(null!=t&&t.partList){var s;const r=t.partList[0];if(e>=r.end+((null==(s=t.fragmentHint)?void 0:s.duration)||0)){var i;if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=a.details,l=n>-1?fi(o,r,n):null,h=l?l.fragment:ui(o,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(t,e,s,i,r){var n;if(!t||this.state!==ki)return;const{data1:a,data2:o}=t;let l=a;if(a&&o&&(l=_t(a,o)),null==(n=l)||!n.length)return;const h={type:t.type,frag:e,part:s,chunkMeta:i,parent:e.type,data:l};if(this.hls.trigger(E.BUFFER_APPENDING,h),t.dropped&&t.independent&&!s){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!as.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const s=e.currentTime,i=as.bufferInfo(e,s,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,i.end-n),s+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var s;const i=this.getLoadPosition();if(!g(i))return null;const r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,i,e,r)}getFwdBufferInfoAtPos(t,e,s,i){const r=as.bufferInfo(t,e,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-e,i);return as.bufferInfo(t,e,s)}}return r}getMaxBufferLength(t){const{config:e}=this;let s;return s=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const s=this.config,i=Math.max(Math.min(t-e,s.maxBufferLength),e),r=Math.max(t-3*e,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=R){var s;const i=null==(s=this.fragmentTracker)?void 0:s.getAppendedFrag(t,e);return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const h=r.initialLiveManifestSize;if(i<h)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${h})`),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,s);const i=this.hls.startPosition,r=this.hls.liveSyncPosition,h=o?(-1!==i&&i>=n?i:r)||o.start:t;this.log(`Setting startPosition to ${h} to match start frag at live edge. mainStart: ${i} liveSyncPosition: ${r} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=h}}else t<=n&&(o=s[0]);if(!o){const s=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,s,e)}let h=this.filterReplacedPrimary(o,e);if(!h&&o){const t=o.sn-e.startSN;h=this.filterReplacedPrimary(s[t+1]||null,e)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(t,e){const s=this.fragmentTracker.getState(t);return(s===Ge||s===$e&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,s,i,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&s.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==t&&s.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Mi(this.hls.config)){var t,e;if(null==(t=this.hls.interstitialsManager)||null==(e=t.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(Mi(this.hls.config)&&t.type!==I){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(s.appendInPlace||Math.abs(t.start-i.start)>1||0===i.start)return null}else{if(t.end<=i.start&&!1===(null==e?void 0:e.live))return null;if(t.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||t.start-i.end>1))return null}}const r=null==s?void 0:s.playerQueue;if(r)for(let e=r.length;e--;){const s=r[e].interstitial;if(s.appendInPlace&&t.start>=s.startTime&&t.end<=s.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,s){let i=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded;l?i=-1:(r||o.independent||n)&&o.fragment===e&&(i=a),r=l}return i}loadedEndOfParts(t,e){const s=t[t.length-1];return s&&e>s.start&&s.loaded}getInitialLiveFragment(t,e){const s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!g(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let i=0;i<t.length;++i){const r=t[i];if(Ae(e,s,r))return r}return null}(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Re(e,s.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(i=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;if(d&&o&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),t<e){var u;c=Se(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-s.startSN,e=this.fragmentTracker.getState(c);if((e===Ge||e===$e&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn||!s.live&&!d)){if(r&&c.level===r.level){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==Ge?e:null}}}return c}alignPlaylists(t,e,s){const i=t.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,n=!e,a=t.alignedSliding&&g(r);if(n||!a&&!r){!function(t,e){t&&(Ei(e,t),!e.alignedSliding&&t&&Ti(e,t),e.alignedSliding||!t||e.skippedSegments||hi(t,e,!1))}(s,t);const r=t.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${i}`),r}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let s=this.startPosition;s<e&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:t.startTimeOffset;null!==n&&g(n)?(s=e+n,n<0&&(s+=t.edge),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):t.live?(s=this.hls.liveSyncPosition||e,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var t;const{media:e}=this;let s=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?s=e.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&rt(t)&&t.stats.aborted&&(this.warn(`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===Ii)||(this.state=Ai)}onFragmentOrKeyLoadError(t,e){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 i;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);const r=e.details===y.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,flags:o,retryCount:l=0,retryConfig:h}=n||{},d=!!n&&!!h,c=d&&a===xe,u=d&&!n.resolved&&o===Me;if(!c&&u&&rt(s)&&!s.endList)this.resetFragmentErrors(t),this.treatAsGap(s),n.resolved=!0;else if((c||u)&&l<h.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const i=_e(h,l);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${l+1}/${h.maxNumRetry} in ${i}ms`),n.resolved=!0,this.retryDate=self.performance.now()+i,this.state=Ii}else if(h&&n){if(this.resetFragmentErrors(t),!(l<h.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${l})`);r||a===we||(n.resolved=!0)}else this.state=a===Ce?xi:Ci;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===ki||this.state===Di){const e=t.frag,s=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===b&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Li&&(this.state=Ai)}afterBufferFlushed(t,e,s){if(!t)return;const i=as.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,s),this.state===Pi&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Li&&(this.state=Ai)}resetStartWhenNotLoaded(t){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const 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.warn(`The loading context changed while buffering fragment ${t.sn} of ${this.playlistLabel()} ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){const r=s.details;if(!r)return void this.warn("level.details undefined");var n;if(!Object.keys(t.elementaryStreams).reduce(((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const l=i?0:ai(r,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&(0===s.fragmentError&&this.treatAsGap(t,s),null===(null==(n=this.transmuxer)?void 0:n.error))){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(E.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Di,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(E.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===R?"level":"track"}fragInfo(t,e=!0,s){var i,r;return`${this.playlistLabel()} ${t.level} (${s?"part":"frag"}:[${(null!=(i=e&&!s?t.startPTS:(s||t).start)?i:NaN).toFixed(3)}-${(null!=(r=e&&!s?t.endPTS:(s||t).end)?r:NaN).toFixed(3)}]${s&&"main"===t.type?"INDEPENDENT="+(s.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.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function Mi(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Fi{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let i=0;for(let e=0;e<t.length;e++){const r=t[e];s.set(r,i),i+=r.length}return s}(t,e),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Ni,Ui={exports:{}};var Bi=(Ni||(Ni=1,function(t){var e=Object.prototype.hasOwnProperty,s="~";function i(){}function r(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||t,a),l=s?s+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 i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,i,r=[];if(0===this._eventsCount)return r;for(i in t=this._events)e.call(t,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=s?s+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,r,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,i),!0;case 4:return d.fn.call(d.context,e,i,r),!0;case 5:return d.fn.call(d.context,e,i,r,n),!0;case 6:return d.fn.call(d.context,e,i,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,e);break;case 3:d[h].fn.call(d[h].context,e,i);break;case 4:d[h].fn.call(d[h].context,e,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(t,e,s){return n(this,t,e,s,!1)},o.prototype.once=function(t,e,s){return n(this,t,e,s,!0)},o.prototype.removeListener=function(t,e,i,r){var n=s?s+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||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==e||r&&!o[l].once||i&&o[l].context!==i)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=s?s+t:t,this._events[e]&&a(this,e)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}(Ui)),Ui.exports),$i=V(Bi);const Gi="1.6.2",Ki={};function Hi(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 Vi(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 Yi(t,e){let s=0;return s=(127&t[e])<<21,s|=(127&t[e+1])<<14,s|=(127&t[e+2])<<7,s|=127&t[e+3],s}function ji(t,e){const s=e;let i=0;for(;Vi(t,e);){i+=10;i+=Yi(t,e+6),Hi(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(s,s+i)}function Wi(t,e){return 255===t[e]&&240==(246&t[e+1])}function qi(t,e){return 1&t[e+1]?7:9}function Xi(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function zi(t,e){return e+1<t.length&&Wi(t,e)}function Qi(t,e){if(zi(t,e)){const s=qi(t,e);if(e+s>=t.length)return!1;const i=Xi(t,e);if(i<=s)return!1;const r=e+i;return r===t.length||zi(t,r)}return!1}function Ji(t,e,s,i,r){if(!t.samplerate){const n=function(t,e,s,i){const r=e[s+2],n=r>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit(E.ERROR,E.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(r>>6&3),o=e[s+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d=n;5!==a&&29!==a||(d-=3);const c=[a<<3|(14&d)>>1,(1&d)<<7|o<<3];return B.log(`manifest codec:${i}, parsed codec:${l}, channels:${o}, rate:${h} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}(e,s,i,r);if(!n)return;P(t,n)}}function Zi(t){return 9216e4/t}function tr(t,e,s,i,r){const n=i+r*Zi(t.samplerate),a=function(t,e){const s=qi(t,e);if(e+s<=t.length){const i=Xi(t,e)-s;if(i>0)return{headerLength:s,frameLength:i}}}(e,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(s+r,e.length),0)):o=e.subarray(s+r,s+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-s;o=new Uint8Array(l),o.set(e.subarray(s,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function er(t,e){return Vi(t,e)&&Yi(t,e+6)+10<=t.length-e}function sr(t,e){if(t<0)return-sr(-t,e);const s=Math.pow(10,e);if(Math.abs(t*s%1-.5)<Number.EPSILON){const e=Math.floor(t*s);return(e%2==0?e:e+1)/s}return Math.round(t*s)/s}function ir(t,e=0,s=1/0){return function(t,e,s,i){const r=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.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,h=Math.floor(Math.max(0,Math.min(l,o))),d=Math.floor(Math.min(h+Math.max(s,0),o));var c;return new i(r,h,d-h)}(t,e,s,Uint8Array)}function rr(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 s=t.data.subarray(1).indexOf(0);if(-1===s)return;const i=K(ir(t.data,1,s)),r=t.data[2+s],n=t.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=K(ir(t.data,3+s,n));let o;return o="--\x3e"===i?K(ir(t.data,4+s+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+s+n)),e.mimeType=i,e.pictureType=r,e.description=a,e.data=o,e}function nr(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=K(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=K(t.data.subarray(e),!0);e+=s.length+1;const i=K(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=K(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?rr(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=K(t.data.subarray(e),!0);e+=s.length+1;const i=K(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=K(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function ar(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=Yi(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}}function or(t){let e=0;const s=[];for(;Vi(t,e);){const i=Yi(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+i;for(;e+10<r;){const i=ar(t.subarray(e)),r=nr(i);r&&s.push(r),e+=i.size+10}Hi(t,e)&&(e+=10)}return s}function lr(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function hr(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function dr(t){const e=or(t);for(let t=0;t<e.length;t++){const s=e[t];if(lr(s))return hr(s)}}let cr=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 ur(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class fr{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,s,i){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,s){}demux(t,e){this.cachedData&&(t=_t(this.cachedData,t),this.cachedData=null);let s,i=ji(t,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?dr(i):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&g(o))&&(this.basePTS=gr(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:cr.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(t,r)){const e=this.appendFrame(n,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,s=r):r=l}else er(t,r)?(i=ji(t,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:cr.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const e=t.slice(s);this.cachedData?this.cachedData=_t(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:ur(),id3Track:a,textTrack:ur()}}demuxSampleAes(t,e,s){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:ur(),id3Track:this._id3Track,textTrack:ur()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const gr=(t,e,s)=>{if(g(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};let mr=null;const pr=[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],vr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],yr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Er=[0,1,1,4];function Tr(t,e,s,i,r){if(s+24>e.length)return;const n=Sr(e,s);if(n&&s+n.frameLength<=e.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+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 Sr(t,e){const s=t[e+1]>>3&3,i=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*pr[14*(3===s?3-i:3===i?3:4)+r-1],h=vr[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=yr[s][i],u=Er[i],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===mr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);mr=t?parseInt(t[1]):0}return!!mr&&mr<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function Lr(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Ar(t,e){return e+1<t.length&&Lr(t,e)}function Rr(t,e){if(e+1<t.length&&Lr(t,e)){const s=4,i=Sr(t,e);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=e+r;return n===t.length||Ar(t,n)}return!1}const br=(t,e)=>{let s=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],e+=1,i-=o}return s};class Ir extends fr{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const i=_r(t,e,s,this.basePTS,this.frameIndex);if(-1!==i){return{sample:t.samples[t.samples.length-1],length:i,missing:0}}}static probe(t){if(!t)return!1;const e=ji(t,0);if(!e)return!1;const s=e.length;return 11===t[s]&&119===t[s+1]&&void 0!==dr(e)&&br(t,s)<16}}function _r(t,e,s,i,r){if(s+8>e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+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(s+l>e.length)return-1;const h=e[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[s+6]<<8|e[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[s+5]>>3,g=7&e[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=e.subarray(s,s+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}const kr=/\/emsg[-/]ID3/i;function Dr(t,e){return g(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class Pr{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Qe(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,je)}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}))}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)s.set(t.subarray(e,e+16),i);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)t.set(s.subarray(i,i+16),e);return t}decryptAvcSample(t,e,s,i,r){const n=wt(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,s+1,i)}))}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void i();const r=t[e].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,i,n),this.decrypter.isSync())))return}}}}class Cr{constructor(){this.VideoSample=null}createVideoSample(t,e,s){return{key:t,frame:!1,pts:e,dts:s,units:[],length:0}}getLastNalUnit(t){var e;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,i=s.length;if(!i)return void e.dropped++;{const e=s[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,s){const i=e.byteLength;let r=t.naluState||0;const n=r,a=[];let o,l,h,d=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(e,0),r=0,d=1);d<i;)if(o=e[d++],r)if(1!==r)if(o)if(1===o){if(l=d-r-1,c>=0){const t={data:e.subarray(c,l),type:u};a.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(n&&d<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=_t(s.data,e.subarray(0,l)),s.state=0))}d<i?(h=this.getNALuType(e,d),c=d,u=h,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,i),type:u,state:r};a.push(t)}if(0===a.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=_t(s.data,e))}return t.naluState=r,a}}class wr{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,s=t.byteLength-e,i=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.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 s=this.word>>>32-e;if(t>32&&B.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?s<<e|this.readBits(e):s}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 xr extends Cr{parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach((i=>{var r,l;switch(i.type){case 1:{let e=!1;n=!0;const r=i.data;if(o&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.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,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Ct(i.data,1,s.pts,e.samples);break;case 7:{var d,c;n=!0,o=!0;const e=i.data,s=this.readSPS(e);if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(d=t.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e];const i=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:n=!0,t.pps=[i.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,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(i)}})),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new wr(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let s,i=8,r=8;for(let n=0;n<t;n++)0!==r&&(s=e.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(t){const e=new wr(t);let s,i,r,n=0,a=0,o=0,l=0;const h=e.readUByte.bind(e),d=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);h();const v=h();if(d(5),f(3),h(),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(i=3!==t?8:12,r=0;r<i;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(),s=c(),r=0;r<s;r++)g();m(),f(1);const E=c(),T=c(),S=d(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let L=[1,1];if(u()&&u()){switch(h()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:L=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:L}}}class Or extends Cr{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach((i=>{var r,l;switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var h;if(n=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,Ct(i.data,2,s.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=P(t.params,this.readVPS(i.data)),this.initVPS=i.data),t.vps=[i.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],i.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(i.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 s in e.params)t.params[s]=e.params[s]}this.pushParameterSet(t.sps,i.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(i.data);for(const s in e)t.params[s]=e[s]}this.pushParameterSet(t.pps,i.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,s.pts,s.dts));break;default:n=!1}if(a&&n){a.units.push(i)}})),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,s){(s&&s[0]===this.initVPS||!s&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let s=0;for(let i=0;i<t.byteLength;i++)i>=2&&3===t[i]&&0===t[i-1]&&0===t[i-2]||(e[s]=t[i],s++);return new Uint8Array(e.buffer,0,s)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new wr(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 wr(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const s=e.readBits(3);e.readBoolean();const i=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),d=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<s;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(s>0)for(let t=s;t<8;t++)e.readBits(2);for(let t=0;t<s;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(),L=e.readBoolean();let A=0,R=0,b=0,I=0;L&&(A+=e.readUEG(),R+=e.readUEG(),b+=e.readUEG(),I+=e.readUEG());const _=e.readUEG(),k=e.readUEG(),D=e.readUEG();for(let t=e.readBoolean()?0:s;t<=s;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 s=0;s<(3===t?2:6);s++){if(e.readBoolean()){const s=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<s;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const P=e.readUEG();let C=0;for(let t=0;t<P;t++){let s=!1;if(0!==t&&(s=e.readBoolean()),s){t===P&&e.readUEG(),e.readBoolean(),e.readUEG();let s=0;for(let t=0;t<=C;t++){const t=e.readBoolean();let i=!1;t||(i=e.readBoolean()),(t||i)&&s++}C=s}else{const t=e.readUEG(),s=e.readUEG();C=t+s;for(let s=0;s<t;s++)e.readUEG(),e.readBoolean();for(let t=0;t<s;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let s=0;s<t;s++){for(let t=0;t<D+4;t++)e.readBits(1);e.readBits(1)}}let w=0,x=1,O=1,M=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let U=!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],O=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(x=e.readBits(16),O=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(),U=e.readBoolean(),U&&(A+=e.readUEG(),R+=e.readUEG(),b+=e.readUEG(),I+=e.readUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),i=e.readBoolean();let r=!1;(t||i)&&(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<=s;n++){M=e.readBoolean();let s=!1;M||e.readBoolean()?e.readEG():s=e.readBoolean();const n=s?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(i)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(),w=e.readUEG())}let B=T,$=S;if(L||U){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),B=T-t*R-t*A,$=S-e*I-e*b}const G=i?["A","B","C"][i]:"",K=a<<24|o<<16|l<<8|h;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:i,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,c,u,f,g,m],general_level_idc:p,bit_depth:_+8,bit_depth_luma_minus8:_,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:w,chroma_format_idc:E,frame_rate:{fixed:M,fps:N/F}},width:B,height:$,pixelRatio:[x,O]}}readPPS(t){const e=new wr(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 s=e.readBoolean(),i=e.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}}const Mr=188;class Fr{constructor(t,e,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(t,e){const s=Fr.syncOffset(t);return s>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(t){const e=t.length;let s=Math.min(940,e-Mr)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<e;o+=Mr){if(71!==t[o]||e-o!==Mr&&71!==t[o+Mr]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,t.length-Mr)+1)),r||(r=0===Nr(t,o)),r&&a>1&&(0===n&&a>2||o+Mr>s))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:dt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Fr.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Fr.createTrack("audio",i),this._id3Track=Fr.createTrack("id3"),this._txtTrack=Fr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,s=!1,i=!1){let r;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=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=_t(this.remainderData,t)).length,this.remainderData=null),y<Mr&&!i)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,Fr.syncOffset(t));y-=(y-E)%Mr,y<t.byteLength&&!i&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let e=E;e<y;e+=Mr)if(71===t[e]){const i=!!(64&t[e+1]),y=Nr(t,e);let T;if((48&t[e+3])>>4>1){if(T=e+5+t[e+4],T===e+Mr)continue}else T=e+4;switch(y){case h:if(i){if(d&&(r=Kr(d,this.logger))){if(null===this.videoParser)switch(n.segmentCodec){case"avc":this.videoParser=new xr;break;case"hevc":this.videoParser=new Or}null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)}d={data:[],size:0}}d&&(d.data.push(t.subarray(T,e+Mr)),d.size+=e+Mr-T);break;case c:if(i){if(f&&(r=Kr(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+Mr)),f.size+=e+Mr-T);break;case u:i&&(g&&(r=Kr(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+Mr)),g.size+=e+Mr-T);break;case 0:i&&(T+=t[T]+1),v=this._pmtId=Ur(t,T);break;case v:{i&&(T+=t[T]+1);const r=Br(t,T,this.typeSupported,s,this.observer,this.logger);h=r.videoPid,h>0&&(n.pid=h,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&&$r(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&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:s,id3Track:i,textTrack:r}=t,n=s.pesData,a=e.pesData,o=i.pesData;let l;if(n&&(l=Kr(n,this.logger))){if(null===this.videoParser)switch(s.segmentCodec){case"avc":this.videoParser=new xr;break;case"hevc":this.videoParser=new Or}null!==this.videoParser&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)}else s.pesData=n;if(a&&(l=Kr(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=Kr(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(t,e,s){const i=this.demux(t,s,!0,!this.config.progressive),r=this.sampleAes=new Pr(this.observer,this.config,e);return this.decrypt(i,r)}decrypt(t,e){return new Promise((s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,(()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,(()=>{s(t)})):s(t)})):r.samples&&e.decryptAvcSamples(r.samples,0,0,(()=>{s(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 s=0;const i=this.aacOverFlow;let r,n,a,o=e.data;if(i){this.aacOverFlow=null;const e=i.missing,r=i.sample.unit.byteLength;if(-1===e)o=_t(i.sample.unit,o);else{const n=r-e;i.sample.unit.set(o.subarray(0,e),n),t.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r<n-1&&!zi(o,r);r++);if(r!==s){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",$r(this.observer,new Error(t),e,this.logger),!e)return}if(Ji(t,this.observer,o,r,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Zi(t.samplerate);a=i.sample.pts+e}}let l,h=0;for(;r<n;){if(l=tr(t,o,r,a,h),r+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;r<n-1&&!zi(o,r);r++);}}parseMPEGPES(t,e){const s=e.data,i=s.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<i;)if(Ar(s,n)){const e=Tr(t,s,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 s=e.data,i=e.pts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=_r(t,s,o,i,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=P({},e,{type:this._videoTrack?cr.emsg:cr.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function Nr(t,e){return((31&t[e+1])<<8)+t[e+2]}function Ur(t,e){return(31&t[e+10])<<8|t[e+11]}function Br(t,e,s,i,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=Nr(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!i){Gr("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(!i){Gr("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:s.mpeg||s.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){Gr("AC-3",n);break}case 129:s.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 i=e+5,r=l;for(;r>2;){if(106===t[i])!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const e=t[i+1]+2;i+=e,r-=e}}break;case 194:case 135:return $r(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 $r(t,e,s,i){i.warn(`parsing error: ${e.message}`),t.emit(E.ERROR,E.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:e,reason:e.message})}function Gr(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Kr(t,e){let s,i,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]=_t(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>t.size-6)return null;const h=s[7];192&h&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&h?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[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=s[8];let d=r+9;if(t.size<=d)return null;t.size-=d;const c=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){s=l[t];let e=s.byteLength;if(d){if(d>e){d-=e;continue}s=s.subarray(d),e-=d,d=0}c.set(s,o),o+=e}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}class Hr{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 Vr=Math.pow(2,32)-1;class Yr{static init(){let t;for(t in Yr.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:[]},Yr.types)Yr.types.hasOwnProperty(t)&&(Yr.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]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Yr.HDLR_TYPES={video:e,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Yr.STTS=Yr.STSC=Yr.STCO=r,Yr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Yr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Yr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Yr.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]);Yr.FTYP=Yr.box(Yr.types.ftyp,n,o,n,a),Yr.DINF=Yr.box(Yr.types.dinf,Yr.box(Yr.types.dref,i))}static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].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),i=0,s=8;i<r;i++)n.set(e[i],s),s+=e[i].byteLength;return n}static hdlr(t){return Yr.box(Yr.types.hdlr,Yr.HDLR_TYPES[t])}static mdat(t){return Yr.box(Yr.types.mdat,t)}static mdhd(t,e){e*=t;const s=Math.floor(e/(Vr+1)),i=Math.floor(e%(Vr+1));return Yr.box(Yr.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,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(t){return Yr.box(Yr.types.mdia,Yr.mdhd(t.timescale||0,t.duration||0),Yr.hdlr(t.type),Yr.minf(t))}static mfhd(t){return Yr.box(Yr.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?Yr.box(Yr.types.minf,Yr.box(Yr.types.smhd,Yr.SMHD),Yr.DINF,Yr.stbl(t)):Yr.box(Yr.types.minf,Yr.box(Yr.types.vmhd,Yr.VMHD),Yr.DINF,Yr.stbl(t))}static moof(t,e,s){return Yr.box(Yr.types.moof,Yr.mfhd(t),Yr.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=Yr.trak(t[e]);return Yr.box.apply(null,[Yr.types.moov,Yr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(s).concat(Yr.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=Yr.trex(t[e]);return Yr.box.apply(null,[Yr.types.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(Vr+1)),i=Math.floor(e%(Vr+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,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Yr.box(Yr.types.mvhd,r)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let i,r;for(i=0;i<e.length;i++)r=e[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Yr.box(Yr.types.sdtp,s)}static stbl(t){return Yr.box(Yr.types.stbl,Yr.stsd(t),Yr.box(Yr.types.stts,Yr.STTS),Yr.box(Yr.types.stsc,Yr.STSC),Yr.box(Yr.types.stsz,Yr.STSZ),Yr.box(Yr.types.stco,Yr.STCO))}static avc1(t){let e,s,i,r=[],n=[];for(e=0;e<t.sps.length;e++)s=t.sps[e],i=s.byteLength,r.push(i>>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(e=0;e<t.pps.length;e++)s=t.pps[e],i=s.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=Yr.box(Yr.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,h=t.pixelRatio[0],d=t.pixelRatio[1];return Yr.box(Yr.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,Yr.box(Yr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Yr.box(Yr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}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 Yr.box(Yr.types.mp4a,Yr.audioStsd(t),Yr.box(Yr.types.esds,Yr.esds(t)))}static mp3(t){return Yr.box(Yr.types[".mp3"],Yr.audioStsd(t))}static ac3(t){return Yr.box(Yr.types["ac-3"],Yr.audioStsd(t),Yr.box(Yr.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Yr.box(Yr.types.stsd,Yr.STSD,Yr.mp4a(t));if("ac3"===e&&t.config)return Yr.box(Yr.types.stsd,Yr.STSD,Yr.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Yr.box(Yr.types.stsd,Yr.STSD,Yr.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Yr.box(Yr.types.stsd,Yr.STSD,Yr.avc1(t));if("hevc"===e&&t.vps)return Yr.box(Yr.types.stsd,Yr.STSD,Yr.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,s=(t.duration||0)*(t.timescale||0),i=t.width||0,r=t.height||0,n=Math.floor(s/(Vr+1)),a=Math.floor(s%(Vr+1));return Yr.box(Yr.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,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const s=Yr.sdtp(t),i=t.id,r=Math.floor(e/(Vr+1)),n=Math.floor(e%(Vr+1));return Yr.box(Yr.types.traf,Yr.box(Yr.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),Yr.box(Yr.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])),Yr.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,Yr.box(Yr.types.trak,Yr.tkhd(t),Yr.mdia(t))}static trex(t){const e=t.id;return Yr.box(Yr.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 s=t.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,h,d,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<i;a++)o=s[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Yr.box(Yr.types.trun,n)}static initSegment(t){Yr.types||Yr.init();const e=Yr.moov(t);return _t(Yr.FTYP,e)}static hvc1(t){const e=t.params,s=[t.vps,t.sps,t.pps],i=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),s.length]);let r=i.length;for(let t=0;t<s.length;t+=1){r+=3;for(let e=0;e<s[t].length;e+=1)r+=2+s[t][e].length}const n=new Uint8Array(r);n.set(i,0),r=i.length;const a=s.length-1;for(let t=0;t<s.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,s[t].length]),r),r+=3;for(let e=0;e<s[t].length;e+=1)n.set(new Uint8Array([s[t][e].length>>8,255&s[t][e].length]),r),r+=2,n.set(s[t][e],r),r+=s[t][e].length}const o=Yr.box(Yr.types.hvcC,n),l=t.width,h=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return Yr.box(Yr.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,h>>8&255,255&h,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,Yr.box(Yr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Yr.box(Yr.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}}Yr.types=void 0,Yr.HDLR_TYPES=void 0,Yr.STTS=void 0,Yr.STSC=void 0,Yr.STCO=void 0,Yr.STSZ=void 0,Yr.VMHD=void 0,Yr.SMHD=void 0,Yr.STSD=void 0,Yr.FTYP=void 0,Yr.DINF=void 0;function jr(t,e,s=1,i=!1){const r=t*e*s;return i?Math.round(r):r}function Wr(t,e=!1){return jr(t,1e3,1/9e4,e)}let qr,Xr=null,zr=null;function Qr(t,e,s,i){return{duration:e,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class Jr{constructor(t,e,s,i){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.logger=i,this.ISGenerated=!1,null===Xr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Xr=t?parseInt(t[1]):0}if(null===zr){const t=navigator.userAgent.match(/Safari\/(\d+)/i);zr=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t[0].pts,i=t.reduce(((t,i)=>{let r=i.pts,n=r-t;return n<-4294967296&&(e=!0,r=Zr(r,s),n=r-t),n>0?t:r}),s);return e&&this.logger.debug("PTS rollover detected"),i}remux(t,e,s,i,r,n,a,o){let l,h,d,c,u,f,g=r,m=r;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,L,A,R;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(S=e.pixelRatio)?void 0:S[0])!==(null==(L=t.pixelRatio)?void 0:L[0])||(null==(A=e.pixelRatio)?void 0:A[1])!==(null==(R=t.pixelRatio)?void 0:R[1]))||!t&&T||null===this.nextAudioPts&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(t,e,r,n));const s=this.isVideoContiguous;let i,a=-1;if(T&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.logger.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}else-1===a&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const s=this.getVideoStartPts(e.samples),i=(Zr(t.samples[0].pts,s)-s)/e.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(E){if(t.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,r,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===b?m:void 0),T){const i=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,m,s,i)}}else T&&(l=this.remuxVideo(e,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=tn(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=en(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}generateIS(t,e,s,i){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||i,f="audio/mp4";if(u&&(h=d=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):Yr.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(c=t.inputTimeScale,l&&c===l.timescale?u=!1:h=d=r[0].pts-Math.round(c*s))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Yr.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=Math.round(c*s);d=Math.min(d,Zr(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:c},this._initDTS={baseTime:d,timescale:c}):h=c=void 0,{tracks:o,initPTS:h,timescale:c}}remuxVideo(t,e,s,i){const r=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS;let h,d,c=this.nextAvcDts,u=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!s||null===c){const t=e*r,i=n[0].pts-Zr(n[0].dts,n[0].pts);Xr&&null!==c&&Math.abs(t-i-c)<15e3?s=!0:c=t-i}const T=l.baseTime*r/l.timescale;for(let t=0;t<o;t++){const e=n[t];e.pts=Zr(e.pts-T,c),e.dts=Zr(e.dts-T,c),e.dts<n[t>0?t-1:t].dts&&(p=!0)}p&&n.sort((function(t,e){const s=t.dts-e.dts,i=t.pts-e.pts;return s||i})),h=n[0].dts,d=n[n.length-1].dts;const S=d-h,L=S?Math.round(S/(o-1)):f||t.inputTimeScale/30;if(s){const s=h-c,i=s>L,r=s<-1;if((i||r)&&(i?this.logger.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Wr(s,!0)} ms (${s}dts) hole between fragments detected at ${e.toFixed(3)}`):this.logger.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Wr(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||c>=n[0].pts||Xr)){h=c;const t=n[0].pts-s;if(i)n[0].dts=h,n[0].pts=t;else{let e=!0;for(let i=0;i<n.length&&!(n[i].dts>t&&e);i++){const t=n[i].pts;if(n[i].dts-=s,n[i].pts-=s,i<n.length-1){const s=n[i+1].pts;e=s<=n[i].pts==s<=t}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${Wr(t,!0)}/${Wr(h,!0)}, delta: ${Wr(s,!0)} ms`)}}h=Math.max(0,h);let A=0,R=0,b=h;for(let t=0;t<o;t++){const e=n[t],s=e.units,i=s.length;let r=0;for(let t=0;t<i;t++)r+=s[t].data.length;R+=r,A+=i,e.length=r,e.dts<b?(e.dts=b,b+=L/4|0||1):b=e.dts,g=Math.min(e.pts,g),m=Math.max(e.pts,m)}d=n[o-1].dts;const I=R+4*A+8;let _;try{_=new Uint8Array(I)}catch(t){return void this.observer.emit(E.ERROR,E.ERROR,{type:v.MUX_ERROR,details:y.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:I,reason:`fail allocating video mdat ${I}`})}const k=new DataView(_.buffer);k.setUint32(0,I),_.set(Yr.types.mdat,4);let D=!1,C=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const e=n[t],s=e.units;let l,h=0;for(let t=0,e=s.length;t<e;t++){const e=s[t],i=e.data,r=e.data.byteLength;k.setUint32(u,r),u+=4,_.set(i,u),u+=r,h+=4+r}if(t<o-1)f=n[t+1].dts-e.dts,l=n[t+1].pts-e.pts;else{const s=this.config,a=t>0?e.dts-n[t-1].dts:L;if(l=t>0?e.pts-n[t-1].pts:L,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*r),n=(i?g+i*r:this.nextAudioPts)-e.pts;n>t?(f=n-a,f<0?f=a:D=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(e.pts-e.dts);C=Math.min(C,f),x=Math.max(x,f),w=Math.min(w,l),O=Math.max(O,l),a.push(Qr(e.key,f,h,d))}if(a.length)if(Xr){if(Xr<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(zr&&O-w<x-C&&L/x<.025&&0===a[0].cts){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=h;for(let e=0,s=a.length;e<s;e++){const i=t+a[e].duration,r=t+a[e].cts;if(e<s-1){const t=i+a[e+1].cts;a[e].duration=t-r}else a[e].duration=e?a[e-1].duration:L;a[e].cts=0,t=i}}f=D||!f?L:f,this.nextAvcDts=c=d+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const M={data1:Yr.moof(t.sequenceNumber++,h,P(t,{samples:a})),data2:_,startPTS:g/r,endPTS:(m+f)/r,startDTS:h/r,endDTS:c/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,M}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,s,i,r){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,h=this._initPTS,d="mp3"===t.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=t.samples,g=d?0:8,m=this.nextAudioPts||-1;const p=e*n,T=h.baseTime*n/h.timescale;if(this.isAudioContiguous=s=s||f.length&&m>0&&(i&&Math.abs(p-m)<9e3||Math.abs(Zr(f[0].pts-T,p)-m)<20*l),f.forEach((function(t){t.pts=Zr(t.pts-T,p)})),!s||m<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;m=0===r?0:i&&!u?Math.max(0,p):f[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,i=m;s<f.length;s++){const r=f[s],a=r.pts,o=a-i,h=Math.abs(1e3*o/n);if(o<=-e*l&&u)0===s&&(this.logger.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=m=i=a);else if(o>=e*l&&h<1e4&&u){let e=Math.round(o/l);i=a-e*l,i<0&&(e--,i+=l),0===s&&(this.nextAudioPts=m=i),this.logger.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(i/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){const e=Math.max(i,0);let n=Hr.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);n||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=r.unit.subarray()),f.splice(s,0,{unit:n,pts:e}),i+=l,s++}}r.pts=i,i+=l}}let S,L=null,A=null,R=0,b=f.length;for(;b--;)R+=f[b].unit.byteLength;for(let e=0,i=f.length;e<i;e++){const i=f[e],r=i.unit;let n=i.pts;if(null!==A){c[e-1].duration=Math.round((n-A)/a)}else{if(s&&"aac"===t.segmentCodec&&(n=m),L=n,!(R>0))return;R+=g;try{S=new Uint8Array(R)}catch(t){return void this.observer.emit(E.ERROR,E.ERROR,{type:v.MUX_ERROR,details:y.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:R,reason:`fail allocating audio mdat ${R}`})}if(!d){new DataView(S.buffer).setUint32(0,R),S.set(Yr.types.mdat,4)}}S.set(r,g);const l=r.byteLength;g+=l,c.push(Qr(!0,o,l,0)),A=n}const I=c.length;if(!I)return;const _=c[c.length-1];this.nextAudioPts=m=A+a*_.duration;const k=d?new Uint8Array(0):Yr.moof(t.sequenceNumber++,L/a,P({},t,{samples:c}));t.samples=[];const D=L/n,C=m/n,w={data1:k,data2:S,startPTS:D,endPTS:C,startDTS:D,endDTS:C,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,w}}function Zr(t,e){let s;if(null===e)return t;for(s=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=s;return t}function tn(t,e,s,i){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=Zr(r.pts-s.baseTime*n/s.timescale,e*n)/n,r.dts=Zr(r.dts-i.baseTime*n/i.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function en(t,e,s){const i=t.samples.length;if(!i)return;const r=t.inputTimeScale;for(let n=0;n<i;n++){const i=t.samples[n];i.pts=Zr(i.pts-s.baseTime*r/s.timescale,e*r)/r}t.samples.sort(((t,e)=>t.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}function sn(t,e){const s=null==t?void 0:t.codec;if(s&&s.length>4)return s;if(e===tt){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return Yt(s,!1)}return B.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}return B.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}try{qr=self.performance.now.bind(self.performance)}catch(t){qr=Date.now}const rn=[{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,s,i){const r=this.videoTrack=ur("video",1),n=this.audioTrack=ur("audio",1),a=this.txtTrack=ur("text",1);if(this.id3Track=ur("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Et(t);if(o.video){const{id:t,timescale:e,codec:s,supplemental:i}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=s,r.supplemental=i}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=dt.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let s=0;s<e;){const i=ft(t,s);if(i>8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=i>1?s+i:e}return!1}(t)}demux(t,e){this.timeOffset=e;let s=t;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=_t(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=vt(t,["moof"]);if(s.length<2)return e.remainder=t,e;const i=s[s.length-1];return e.valid=t.slice(0,i.byteOffset-8),e.remainder=t.slice(i.byteOffset-8),e}(s);this.remainderData=e.remainder,i.samples=e.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,e);return r.samples=kt(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return s.samples=kt(t,e),{videoTrack:e,audioTrack:ur(),id3Track:i,textTrack:ur()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=vt(t.samples,["emsg"]);i&&i.forEach((t=>{const i=function(t){const e=t[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===e){for(;"\0"!==ct(t.subarray(h,h+1));)s+=ct(t.subarray(h,h+1)),h+=1;for(s+=ct(t.subarray(h,h+1)),h+=1;"\0"!==ct(t.subarray(h,h+1));)i+=ct(t.subarray(h,h+1)),h+=1;i+=ct(t.subarray(h,h+1)),h+=1,r=ft(t,12),n=ft(t,16),o=ft(t,20),l=ft(t,24),h=28}else if(1===e){h+=4,r=ft(t,h),h+=4;const e=ft(t,h);h+=4;const n=ft(t,h);for(h+=4,a=2**32*e+n,m(a)||(a=Number.MAX_SAFE_INTEGER,B.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=ft(t,h),h+=4,l=ft(t,h),h+=4;"\0"!==ct(t.subarray(h,h+1));)s+=ct(t.subarray(h,h+1)),h+=1;for(s+=ct(t.subarray(h,h+1)),h+=1;"\0"!==ct(t.subarray(h,h+1));)i+=ct(t.subarray(h,h+1)),h+=1;i+=ct(t.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(kr.test(i.schemeIdUri)){const t=Dr(i,e);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:cr.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=Dr(i,e);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:t,pts:t,type:cr.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class{constructor(t,e,s,i){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.logger=i}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(function(t,e){if(!t||!e)return t;const s=e.keyId;s&&e.isCommonEncryption&&vt(t,["moov","trak"]).forEach((t=>{const e=vt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let i=vt(e,["enca"]);const r=i.length>0;r||(i=vt(e,["encv"])),i.forEach((t=>{vt(r?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=bt(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(B.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${H(t)} -> ${H(s)}`),e.set(s,8))}}))}))}));return t}(t,i)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const i=this.initData=Et(t);i.audio&&(e=sn(i.audio,tt)),i.video&&(s=sn(i.video,et));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:e+","+s,supplemental:i.video.supplemental,initSegment:t,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,supplemental:i.video.supplemental,initSegment:t,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(t,e,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};g(h)||(h=this.lastEndTime=r||0);const c=e.samples;if(null==c||!c.length)return d;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,e){let s=0,i=0,r=0;const n=vt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=vt(a,["tfhd"])[0],l=e[ft(o,4)];if(!l)continue;const h=l.default,d=ft(o,0)|(null==h?void 0:h.flags);let c=null==h?void 0:h.duration;8&d&&(c=ft(o,2&d?12:8));const u=l.timescale||9e4,f=vt(a,["trun"]);for(let t=0;t<f.length;t++)s=It(f[t]),!s&&c&&(s=c*ft(f[t],4)),l.type===et?i+=s/u:l.type===tt&&(r+=s/u)}if(0===i&&0===r){let e=1/0,s=0,i=0;const r=vt(t,["sidx"]);for(let t=0;t<r.length;t++){const n=yt(r[t]);if(null!=n&&n.references){e=Math.min(e,n.earliestPresentationTime/n.timescale);const t=n.references.reduce(((t,e)=>t+e.info.duration||0),0);s=Math.max(s,t+n.earliestPresentationTime/n.timescale),i=s-e}}if(i&&g(i))return i}return i||r}(c,f),p=function(t,e){return vt(e,["moof","traf"]).reduce(((e,s)=>{const i=vt(s,["tfdt"])[0],r=i[0],n=vt(s,["tfhd"]).reduce(((e,s)=>{const n=ft(s,4),a=t[n];if(a){let t=ft(i,4);if(1===r){if(t===lt)return B.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=lt+1,t+=ft(i,8)}const s=t/(a.timescale||9e4);if(g(s)&&(null===e||s<e))return s}return e}),null);return null!==n&&g(n)&&(null===e||n<e)?n:e}),null)}(f,c),v=null===p?r:p;!n&&l||!function(t,e,s,i){if(null===t)return!0;const r=Math.max(i,1),n=e-t.baseTime/t.timescale;return Math.abs(n-s)>r}(l,v,r,m)&&u.timescale===l.timescale||(u.initPTS=v-r,l&&1===l.timescale&&this.logger.warn(`Adjusting initPTS @${r} from ${l.baseTime/l.timescale} to ${u.initPTS}`),this.initPTS=l={baseTime:u.initPTS,timescale:1});const y=t?v-l.baseTime/l.timescale:h,E=y+m;!function(t,e,s){vt(e,["moof","traf"]).forEach((e=>{vt(e,["tfhd"]).forEach((i=>{const r=ft(i,4),n=t[r];if(!n)return;const a=n.timescale||9e4;vt(e,["tfdt"]).forEach((t=>{const e=t[0],i=s*a;if(i){let s=ft(t,4);if(0===e)s-=i,s=Math.max(s,0),pt(t,4,s);else{s*=Math.pow(2,32),s+=ft(t,8),s-=i,s=Math.max(s,0);const e=Math.floor(s/(lt+1)),r=Math.floor(s%(lt+1));pt(t,4,e),pt(t,8,r)}}}))}))}))}(f,c,l.baseTime/l.timescale),m>0?this.lastEndTime=E:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const T=!!f.audio,S=!!f.video;let L="";T&&(L+="audio"),S&&(L+="video");const A={data1:c,startPTS:y,startDTS:y,endPTS:E,endDTS:E,type:L,hasAudio:T,hasVideo:S,nb:1,dropped:0};return d.audio="audio"===A.type?A:void 0,d.video="audio"!==A.type?A:void 0,d.initSegment=u,d.id3=tn(s,r,l,l),i.samples.length&&(d.text=en(i,r,l)),d}}},{demux:Fr,remux:Jr},{demux:class extends fr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const s=ji(t,0);let i=(null==s?void 0:s.length)||0;if(Rr(t,i))return!1;for(let s=t.length;i<s;i++)if(Qi(t,i))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)&&Wi(t,e)&&Xi(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){Ji(t,this.observer,e,s,t.manifestCodec);const i=tr(t,e,s,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},remux:Jr},{demux:class extends fr{resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=ji(t,0);let s=(null==e?void 0:e.length)||0;if(e&&11===t[s]&&119===t[s+1]&&void 0!==dr(e)&&br(t,s)<=16)return!1;for(let e=t.length;s<e;s++)if(Rr(t,s))return B.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Lr(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return Tr(t,e,s,this.basePTS,this.frameIndex)}},remux:Jr}];rn.splice(2,0,{demux:Ir,remux:Jr});class nn{constructor(t,e,s,i,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=s,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,i){const r=s.transmuxing;r.executeStart=qr();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:T,initSegmentData:S}=o,L=function(t,e){let s=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(L&&ys(L.method)){const t=this.getDecrypter(),e=Es(L.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(n,L.key.buffer,L.iv.buffer,e).then((t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e})),this.decryptionPromise;{let i=t.softwareDecrypt(n,L.key.buffer,L.iv.buffer,e);if(s.part>-1){const e=t.flush();i=e?e.buffer:e}if(!i)return r.executeEnd=qr(),an(s);n=new Uint8Array(i)}}const A=this.needsProbing(h,d);if(A){const t=this.configureTransmuxer(n);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=qr(),an(s)}(h||d||f||A)&&this.resetInitSegment(S,g,m,T,e),(h||f||A)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const R=this.transmux(n,L,u,c,s);this.asyncResult=on(R);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,r.executeEnd=qr(),R}flush(t){const e=t.transmuxing;e.executeStart=qr();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then((()=>this.flush(t)));const n=[],{timeOffset:a}=i;if(s){const e=s.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=qr();const s=[an(t)];return this.asyncResult?Promise.resolve(s):s}const h=o.flush(a);return on(h)?(this.asyncResult=!0,h.then((e=>(this.flushRemux(n,e,t),n)))):(this.flushRemux(n,h,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===R?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=qr()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,i),a.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,i,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,i,r):this.transmuxUnencrypted(t,s,i,r),n}transmuxUnencrypted(t,e,s,i){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,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer.demuxSampleAes(t,e,s).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,i,!1,this.id),chunkMeta:r})))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i}=this;let r;for(let e=0,s=rn.length;e<s;e++){var n;if(null!=(n=rn[e].demux)&&n.probe(t,this.logger)){r=rn[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,h=r.demux;o&&o instanceof l||(this.remuxer=new l(s,e,i,this.logger)),a&&a instanceof h||(this.demuxer=new h(s,e,i,this.logger),this.probe=h.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Qe(this.config)),t}}const an=t=>({remuxResult:{},chunkMeta:t});function on(t){return"then"in t&&t.then instanceof Function}class ln{constructor(t,e,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class hn{constructor(t,e,s,i,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=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let dn=0;class cn{constructor(t,e,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=dn++,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,s=this.hls;if(s&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":s.logger[e.data.logType]&&s.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,s.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(E.ERROR,{type:v.OTHER_ERROR,details:y.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===E.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new $i,this.observer.on(E.FRAG_DECRYPTED,n),this.observer.on(E.ERROR,n);const a=qt(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=Ki[t];if(e)return e.clientCount++,e;const s=new self.URL(t,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return Ki[t]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Ki[Gi];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"}),s=self.URL.createObjectURL(e),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return Ki[Gi]=i,i}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:ce(r)})}catch(i){s.warn(`Error setting up "${e}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new nn(this.observer,a,r,"",e,t.logger)}return}}this.transmuxer=new nn(this.observer,a,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=dn++;const e=this.hls.config,s=qt(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:s,id:this.id,config:ce(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=Ki[t||Gi];if(e&&1==e.clientCount--){const{worker:s,objectURL:i}=e;delete Ki[t||Gi],i&&self.URL.revokeObjectURL(i),s.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,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!(p&&r.cc===p.cc),y=!(p&&l.level===p.level),E=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),L=!y&&(1===E||0===E&&(1===T||S&&T<=0)),A=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=A),!n||!T&&L||(n.stats.parsing.start=A);const b=!(p&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),I=new hn(v,L,o,y,g,b);if(!L||v||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===R?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${L}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${b}`);const t=new ln(s,i,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:I},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,m,l,I);on(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:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(s){const e=s.flush(t);on(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,s){this.hls&&(this.error=t,this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):s&&s.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class un extends x{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,s){const i=null==e?void 0:e.renditionReports;if(i){let r=-1;for(let s=0;s<i.length;s++){const n=i[s];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=s;break}a===t.substring(0,a.length)&&(r=s)}if(-1!==r){const t=i[r],n=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let a=parseInt(t["LAST-PART"])||(null==e?void 0: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=s&&ae(s);return new oe(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,s){const{details:i,stats:r}=e,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){const t=Math.max(o||0,0);i.appliedTimelineOffset=t,i.fragments.forEach((e=>{e.start=e.playlistOffset+t}))}if(i.live||null!=s&&s.live){const o="levelInfo"in e?e.levelInfo:e.track;if(i.reloaded(s),s&&i.fragments.length>0){oi(s,i);const t=i.playlistParsingError;if(t){this.warn(t);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=e;return void s.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:y.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(l=i.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=ci(i,1e3*(i.edge-d));if(i.requestScheduled+c<n?i.requestScheduled=n:i.requestScheduled+=c,this.log(`live playlist ${t} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let u,f,g;if(i.canBlockReload&&i.endSN&&i.advanced){const t=this.hls.config.lowLatencyMode,r=i.lastPartSn,a=i.endSN,l=i.lastPartIndex,h=r===a;-1!==l?h?(f=a+1,g=t?0:l):(f=r,g=t?l+1:i.maxPartIndex):f=a+1;const d=i.age,c=d+i.ageHeader;let m=Math.min(c-i.partTarget,1.5*i.targetduration);if(m>0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${m} with playlist age: ${i.age}`),m=0;else{const t=Math.floor(m/i.targetduration);if(f+=t,void 0!==g){g+=Math.round(m%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${m} skip sn ${t} to part ${g}`)}i.tuneInGoal=m}if(u=this.getDeliveryDirectives(i,e.deliveryDirectives,f,g),t||!h)return i.requestScheduled=n,void this.loadingPlaylist(o,u)}else(i.canBlockReload||i.canSkipUntil)&&(u=this.getDeliveryDirectives(i,e.deliveryDirectives,f,g));u&&void 0!==f&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,i)}else this.clearTimer()}scheduleLoading(t,e,s){const i=s||t.details;if(!i)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=i.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,s,i){let r=ae(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=ie),new oe(s,i,r)}checkRetry(t){const e=t.details,s=be(t),i=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===xe||!i.resolved&&r===Ce);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&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=_e(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,i.resolved=!0}return o}}function fn(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!gn(t[s].attrs,e[s].attrs))return!1;return!0}function gn(t,e,s){const i=t["STABLE-RENDITION-ID"];return i&&!s?i===e["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((s=>t[s]!==e[s]))}function mn(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class pn{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[e];i.push(t),1!==i.length||s||this.executeNext(e)}appendBlocker(t){return new Promise((e=>{const s={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,t)}))}prependBlocker(t){return new Promise((e=>{if(this.queues){const s={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(s)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((t=>{var e;const s=null==(e=t[0])?void 0:e.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(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 i=e[0];try{i.execute()}catch(e){var s;if(i.onError(e),null===this.queues||null===this.tracks)return;const r=null==(s=this.tracks[t])?void 0:s.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,s;return null!=(e=this.queues)&&e[t]||null!=(s=this.tracks)&&s[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const s=null==(e=this.tracks)?void 0:e[t],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map((t=>t.label)).join(", "))||""}}const vn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,yn="HlsJsTrackRemovedError";class En extends Error{constructor(t){super(t),this.name=yn}}function Tn(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}function Sn(t){return"audio"===t?1:0}class Ln{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(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.BUFFER_CODECS,this.onBufferCodecs,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.BUFFER_CODECS,this.onBufferCodecs,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&g(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,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,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 s=e.filter(((e,s)=>this.isLevelAllowed(e)&&s<=t));return this.clientRect=null,Ln.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.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,s){if(null==t||!t.length)return-1;let i=t.length-1;const r=Math.max(e,s);for(let e=0;e<t.length;e+=1){const s=t[e];if((s.width>=r||s.height>=r)&&(n=s,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){i=e;break}}var n,a;return i}}const An={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Rn={HLS:"h"},bn="CMCD-Object",In="CMCD-Request",_n="CMCD-Session",kn="CMCD-Status",Dn={[bn]:["br","d","ot","tb"],[In]:["bl","dl","mtp","nor","nrr","su"],[_n]:["cid","pr","sf","sid","st","v"],[kn]:["bs","rtp"]};class Pn{constructor(t,e){Array.isArray(t)&&(t=t.map((t=>t instanceof Pn?t:new Pn(t)))),this.value=t,this.params=e}}function Cn(t,e,s,i){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 ${s}`,{cause:i});var r}function wn(t,e,s){return Cn("serialize",t,e,s)}class xn{constructor(t){this.description=t}}const On="Bare Item";function Mn(t){if(!1===ArrayBuffer.isView(t))throw wn(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Fn(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw wn(t,"Integer");return t.toString()}function Nn(t){const e=sr(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw wn(t,"Decimal");const s=e.toString();return s.includes(".")?s:`${s}.0`}const Un=/[\x00-\x1f\x7f]+/;function Bn(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw wn(e,"Token");return e}function $n(t){switch(typeof t){case"number":if(!g(t))throw wn(t,On);return Number.isInteger(t)?Fn(t):Nn(t);case"string":return function(t){if(Un.test(t))throw wn(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Bn(t);case"boolean":return function(t){if("boolean"!=typeof t)throw wn(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${Fn(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return Mn(t);if(t instanceof xn)return Bn(t);default:throw wn(t,On)}}function Gn(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw wn(t,"Key");return t}function Kn(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${Gn(t)}`:`;${Gn(t)}=${$n(e)}`)).join("")}function Hn(t){return t instanceof Pn?`${$n(t.value)}${Kn(t.params)}`:$n(t)}function Vn(t,e={whitespace:!0}){if("object"!=typeof t)throw wn(t,"Dict");const s=t instanceof Map?t.entries():Object.entries(t),i=(null==e?void 0:e.whitespace)?" ":"";return Array.from(s).map((([t,e])=>{e instanceof Pn==!1&&(e=new Pn(e));let s=Gn(t);var i;return!0===e.value?s+=Kn(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(i=e).value.map(Hn).join(" ")})${Kn(i.params)}`:s+=Hn(e)),s})).join(`,${i}`)}const Yn=t=>Math.round(t),jn=t=>100*Yn(t/100),Wn={br:Yn,d:Yn,bl:jn,dl:jn,mtp:jn,nor:(t,e)=>((null==e?void 0:e.baseUrl)&&(t=function(t,e){const s=new URL(t),i=new URL(e);if(s.origin!==i.origin)return t;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:jn,tb:Yn};function qn(t,e){const s={};if(null==t||"object"!=typeof t)return s;const i=Object.keys(t).sort(),r=P({},Wn,null==e?void 0:e.formatters),n=null==e?void 0:e.filter;return i.forEach((i=>{if(null==n?void 0:n(i))return;let a=t[i];const o=r[i];o&&(a=o(a,e)),"v"===i&&1===a||"pr"==i&&1===a||function(t){return"number"==typeof t?g(t):null!=t&&""!==t&&!1!==t}(a)&&(function(t){return"ot"===t||"sf"===t||"st"===t}(i)&&"string"==typeof a&&(a=new xn(a)),s[i]=a)})),s}function Xn(t,e={}){return t?function(t,e){return Vn(t,e)}(qn(t,e),P({whitespace:!1},e)):""}function zn(t,e,s){return P(t,function(t,e={}){const s={};if(!t)return s;const i=Object.entries(t),r=Object.entries(Dn).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),n=i.reduce(((t,e)=>{var s,i;const[n,a]=e,o=(null===(s=r.find((t=>t[1].includes(n))))||void 0===s?void 0:s[0])||In;return null!==(i=t[o])&&void 0!==i||(t[o]={}),t[o][n]=a,t}),{});return Object.entries(n).reduce(((t,[s,i])=>(t[s]=Xn(i,e),t)),s)}(e,s))}const Qn=/CMCD=[^&#]+/;function Jn(t,e,s){const i=function(t,e={}){if(!t)return"";const s=Xn(t,e);return`CMCD=${encodeURIComponent(s)}`}(e,s);if(!i)return t;if(Qn.test(t))return t.replace(Qn,i);const r=t.includes("?")?"&":"?";return`${t}${r}${i}`}function Zn(t,e,s,i){t&&Object.keys(e).forEach((r=>{const n=t.filter((t=>t.groupId===r)).map((t=>{const n=P({},t);return n.details=void 0,n.attrs=new gs(n.attrs),n.url=n.attrs.URI=ta(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=i,n}));t.push(...n)}))}function ta(t,e,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;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 ea extends x{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=ea.CDMCleanupPromise?[ea.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:e,initData:s}=t,i=`"${t.type}" event: init data type: "${e}"`;if(this.debug(i),null!==s){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Fs(this.config));const e=t.map(Ms).filter((t=>!!t));this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then((r=>{const n=Ds(r);let a,o;if("sinf"===e){if(n!==Rs.FAIRPLAY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);const r=ct(new Uint8Array(s));try{const t=bt(Ts(JSON.parse(r).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24)),o=Rs.FAIRPLAY}catch(t){return void this.warn(`${i} Failed to parse sinf: ${t}`)}}else{if(n!==Rs.WIDEVINE&&n!==Rs.PLAYREADY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);const r=function(t){const e=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let i=0;for(;i+32<s;){const s=Ot(new DataView(t,i));e.push(s),i+=s.size}}return e}(s),l=r.filter((t=>!!t.systemId&&Os(t.systemId)===n));l.length>1&&this.warn(`${i} Using first of ${l.length} pssh found for selected key-system ${n}`);const h=l[0];if(!h)return void(0===r.length||r.some((t=>!t.systemId))?this.warn(`${i} contains incomplete or invalid pssh data`):this.log(`ignoring ${i} for ${r.map((t=>Os(t.systemId))).join(",")} pssh data in favor of playlist keys`));if(o=Os(h.systemId),0===h.version&&h.data)if(o===Rs.WIDEVINE){const t=h.data.length-22;a=new Uint8Array(h.data.subarray(t,t+16))}else o===Rs.PLAYREADY&&(a=Bs(h.data))}if(!o||!a)return;const l=H(a),{keyIdToKeySessionPromise:h,mediaKeySessions:d}=this;let c=h[l];for(let t=0;t<d.length;t++){const i=d[t],r=i.decryptdata;if(!r.keyId)continue;const n=H(r.keyId);if(l===n||-1!==r.uri.replace(/-/g,"").indexOf(l)){if(c=h[n],r.pssh)break;delete h[n],r.pssh=new Uint8Array(s),r.keyId=a,c=h[l]=c.then((()=>this.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-key-match"))),c.catch((t=>this.handleError(t)));break}}if(!c){if(o!==n)return void this.log(`Ignoring "${t.type}" event with ${o} init data for selected key-system ${n}`);c=h[l]=this.getKeySystemSelectionPromise([o]).then((({keySystem:t,mediaKeys:i})=>{var r;this.throwIfDestroyed();const n=new Gs("ISO-23001-7",l,null!=(r=Ms(t))?r:"");return n.pssh=new Uint8Array(s),n.keyId=a,this.attemptSetMediaKeys(t,i).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:n,keySystem:t,mediaKeys:i});return this.generateRequestWithPreferredKeySession(r,e,s,"encrypted-event-no-match")}))})),c.catch((t=>this.handleError(t)))}}))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){const t=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(t);const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,i=e[t];return i?i.licenseUrl:t===Rs.WIDEVINE&&s?s: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,s=e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,i=e.map((t=>t.audioCodec)).filter(s),r=e.map((t=>t.videoCodec)).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise(((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,i,r).then((t=>e({keySystem:a,mediaKeys:t}))).catch((e=>{t.length?n(t):s(e instanceof sa?e:new sa({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};n(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===Ns&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){const i=function(t,e,s,i){let r;switch(t){case Rs.FAIRPLAY:r=["cenc","sinf"];break;case Rs.WIDEVINE:case Rs.PLAYREADY:r=["cenc"];break;case Rs.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs=${t}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}))),videoCapabilities:s.map((t=>({contentType:`video/mp4; codecs=${t}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null})))}]}(r,e,s,i)}(t,e,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[t];let n=null==r?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${ce(i)}`),n=this.requestMediaKeySystemAccess(t,i);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),n.then((s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=s.createMediaKeys().then((e=>(this.log(`Media-keys created for "${t}"`),i.then((s=>s?this.setMediaKeysServerCertificate(e,t,s):e))))),e.mediaKeys.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),e.mediaKeys}))}return n.then((()=>r.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${H(t.keyId||[])}`);const i=s.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),i=this.getKeyIdString(e),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return H(t.keyId)}updateKeySession(t,e){var s;const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${H((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),i.update(e)}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){return new Promise(((e,s)=>{const i=Fs(this.config),r=t.map(Ds).filter((t=>!!t&&-1!==i.indexOf(t)));return this.getKeySystemSelectionPromise(r).then((({keySystem:t})=>{const i=Ms(t);i?e(i):s(new Error(`Unable to find format for key-system "${t}"`))})).catch(s)}))}loadKey(t){const e=t.keyInfo.decryptdata,s=this.getKeyIdString(e),i=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];if(!r){r=this.getKeySystemForKeyPromise(e).then((({keySystem:s,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(s,r).then((()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:r,decryptdata:e})))))));(this.keyIdToKeySessionPromise[s]=r.then((t=>{const s=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",s,"playlist-key")}))).catch((t=>this.handleError(t)))}return r}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof sa?this.hls.trigger(E.ERROR,t.data):this.hls.trigger(E.ERROR,{type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=Ds(t.keyFormat),s=e?[e]:Fs(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=Fs(this.config)),0===t.length)throw new sa({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ce({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)}));return this.setMediaKeysQueue.push(i),i.then((()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===s.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,s,i){var r,n;const a=null==(r=this.config.drmSystems)||null==(n=r[t.keySystem])?void 0:n.generateRequest;if(a)try{const i=a.call(this.hls,e,s,t);if(!i)throw new Error("Invalid response from configured generateRequest filter");e=i.initDataType,s=i.initData?i.initData:null,t.decryptdata.pssh=s?new Uint8Array(s):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${i}": ${l} (init data type: ${e} length: ${s?s.byteLength:null})`);const h=new $i,d=t._onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void h.emit("error",new Error("invalid state"));const{messageType:i,message:r}=e;this.log(`"${i}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(t,r).catch((t=>{h.eventNames().length?h.emit("error",t):this.handleError(t)})):"license-release"===i?t.keySystem===Rs.FAIRPLAY&&(this.updateKeySession(t,Ss("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${i}"`)},c=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;h.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",d),t.mediaKeysSession.addEventListener("keystatuseschange",c);const u=new Promise(((t,e)=>{h.on("error",e),h.on("keyStatus",(s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new sa({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new sa({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)}))}));return t.mediaKeysSession.generateRequest(e,s).then((()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)})).catch((t=>{throw new sa({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>u)).catch((e=>{throw h.removeAllListeners(),this.removeSession(t),e})).then((()=>(h.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((e,s)=>{if("string"==typeof s&&"object"==typeof e){const t=s;s=e,e=t}this.log(`key status change "${e}" for keyStatuses keyId: ${H("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${H(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e}))}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise(((r,n)=>{const a={responseType:"arraybuffer",url:i},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,s,i)=>{r(t.data)},onError:(e,s,r,o)=>{n(new sa({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:w({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{n(new sa({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}};s.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise(((i,r)=>{t.setServerCertificate(s).then((r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${e}"`),i(t)})).catch((t=>{r(new sa({type:v.KEY_SYSTEM_ERROR,details:y.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((t=>{throw new sa({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let s=0,i=r.length;s<i;s++){var n,a;e=r[s];const i=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;i&&o&&t.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Ss(atob(l))}setupLicenseXHR(t,e,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then((()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,s,i)})).catch((n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,s,i)})).then((s=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:s||i}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:i}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise(((i,r)=>{const n=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,a,n,t)}catch(t){this.error(t)}i(e)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new sa({type:v.KEY_SYSTEM_ERROR,details:y.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(i,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then((({xhr:e,licenseChallenge:s})=>{t.keySystem==Rs.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)}))}))}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,s.removeEventListener("encrypted",this.onMediaEncrypted),s.removeEventListener("waitingforkey",this.onWaitingForKey),s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(t){var e;const s=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Gs.clearKeyUriToKeyIdMap();const i=s.length;ea.CDMCleanupPromise=Promise.all(s.map((t=>this.removeSession(t))).concat(null==t||null==(e=t.setMediaKeys(null))?void 0:e.catch((t=>{var e;this.log(`Could not clear media keys: ${t}`),null==(e=this.hls)||e.trigger(E.ERROR,{type:v.OTHER_ERROR,details:y.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})})))).then((()=>{i&&(this.log("finished closing key sessions and clearing media keys"),s.length=0)})).catch((t=>{var e;this.log(`Could not close sessions and clear media keys: ${t}`),null==(e=this.hls)||e.trigger(E.ERROR,{type:v.OTHER_ERROR,details:y.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}))}onManifestLoading(){this.keyFormatPromise=null}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:s}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{drmSystemOptions:r}=this.config,n=function(t){var e;return"persistent-license"===t.sessionType||!(null==(e=t.sessionTypes)||!e.some((t=>"persistent-license"===t)))}(r)?new Promise(((t,s)=>{self.setTimeout((()=>s(new Error("MediaKeySession.remove() timeout"))),8e3),e.remove().then(t)})):Promise.resolve();return n.catch((t=>{var e;this.log(`Could not remove session: ${t}`),null==(e=this.hls)||e.trigger(E.ERROR,{type:v.OTHER_ERROR,details:y.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})})).then((()=>e.close())).catch((t=>{var e;this.log(`Could not close session: ${t}`),null==(e=this.hls)||e.trigger(E.ERROR,{type:v.OTHER_ERROR,details:y.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})}))}}}ea.CDMCleanupPromise=void 0;class sa 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 ia(t,e){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function ra(t,e){const s=t.mode;if("disabled"===s&&(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(s){B.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(t){B.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function na(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues)for(let s=t.cues.length;s--;)e&&t.cues[s].removeEventListener("enter",e),t.removeCue(t.cues[s]);"disabled"===s&&(t.mode=s)}function aa(t,e,s,i){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,s){const i=[],r=function(t,e){if(e<=t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),e<t[i].startTime)n=i-1;else{if(!(e>t[i].startTime&&r<s))return i;r=i+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<=s)i.push(r);else if(r.startTime>s)return i}return i}(t.cues,e,s);for(let e=0;e<r.length;e++)i&&!i(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function oa(t){const e=[];for(let s=0;s<t.length;s++){const i=t[s];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||e.push(t[s])}return e}function la(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()}const ha=.025;let da=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function ca(t,e,s){return`${t.identifier}-${s+1}-${la(e)}`}class ua{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){if(t>=this.assetList.length)return!0;const e=this.playoutLimit;if(t<=0||isNaN(e))return!1;return this.assetList[t].startOffset>e}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 fa(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-fa(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=g(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return fa(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)<ha))}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"]?da.Range:da.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 fa(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<ha)?e.start:e.start+e.duration}function ga(t,e,s){const i=new self.URL(t,s);return"data:"!==i.protocol&&i.searchParams.set("_HLS_primary_id",e),i}function ma(t){const e=t.timelineStart,s=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+s).toFixed(2)}]`}class pa{constructor(t,e,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{const t=this.interstitial.playoutLimit,e=this.currentTime;this.startOffset+e>=t&&this.hls.trigger(E.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=s,this.assetItem=i;let n=i.uri;try{n=ga(n,r.sessionId).href}catch(t){}r.loadSource(n);const a=()=>{this.hasDetails=!0};r.once(E.LEVEL_LOADED,a),r.once(E.AUDIO_TRACK_LOADED,a),r.once(E.SUBTITLE_TRACK_LOADED,a),r.on(E.MEDIA_ATTACHING,((t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&e.addEventListener("timeupdate",this.checkPlayout)}))}bufferedInPlaceToEnd(t){var e;if(!this.interstitial.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t||!this._bufferedEosTime)return!1;const s=this.timelineOffset,i=as.bufferInfo(t,s,0);return this.getAssetTime(i.end)>=this._bufferedEosTime-.02}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=as.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;return t||0}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 s=t-e;if(Math.abs(s)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,t-e),s)}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.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){this.hls.attachMedia(t)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(t,e,s){this.hls.on(t,e)}once(t,e,s){this.hls.once(t,e)}off(t,e,s){this.hls.off(t,e)}toString(){var t,e;return`HlsAssetPlayer: ${ma(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${null!=(e=this.interstitial)&&e.appendInPlace?"append-in-place":""}`}}class va extends x{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(((s,i)=>t<=i.startOffset&&e>i.startOffset?(delete i.error,s+1):s),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 s=-1;t.nextEvent?s=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(s=this.findEventIndex(t.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===e&&(e=t.start),s=this.findItemIndexAtTime(e));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(t,e){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(e&&"primary"!==e&&(r=r[e]),t===r.start||t>r.start&&t<r.end)return i}return-1}findJumpRestrictedIndex(t,e){const s=this.items;if(s)for(let i=t;i<=e&&s[i];i++){const t=s[i].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return i}return-1}findEventIndex(t){const e=this.items;if(e)for(let i=e.length;i--;){var s;if((null==(s=e[i].event)?void 0:s.identifier)===t)return i}return-1}findAssetIndex(t,e){const s=t.assetList,i=s.length;if(i>1)for(let t=0;t<i;t++){const i=s[t];if(!i.error){const s=i.timelineStart;if(e===s||e>s&&e<s+(i.duration||0))return t}}return 0}get assetIdAtEnd(){var t,e;const s=null==(t=this.items)||null==(e=t[this.length-1])?void 0:e.event;if(s){const t=s.assetList,e=t[t.length-1];if(e)return e.identifier}return null}parseInterstitialDateRanges(t,e){const s=t.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},e),a=Object.keys(i),o=r?r.filter((t=>!a.includes(t.identifier))):[];n.length&&n.sort(((t,e)=>{const s=t.cue.pre,i=t.cue.post,r=e.cue.pre,n=e.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=t.startTime,i=e.startTime;if(s!==i)return s-i}return t.dateRange.tagOrder-e.dateRange.tagOrder})),this.events=n,o.forEach((t=>{this.removeEvent(t)})),this.updateSchedule(t,o)}updateSchedule(t,e=[]){const s=this.events||[];if(s.length||e.length||this.length<2){const i=this.items,r=this.parseSchedule(s,t);(e.length||(null==i?void 0:i.length)!==r.length||r.some(((t,e)=>Math.abs(t.playout.start-i[e].playout.start)>.005||Math.abs(t.playout.end-i[e].playout.end)>.005)))&&(this.items=r,this.onScheduleUpdate(e,i))}}parseDateRanges(t,e,s){const i=[],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 ua(o,e),this.eventMap[a]=t,!1===s&&(t.appendInPlace=s)),i.push(t)}}return i}parseSchedule(t,e){const s=[],i=e.main.details,r=i.live?1/0:i.edge;let n=0;if((t=t.filter((t=>!(t.error||t.cue.once&&t.hasPlayed)))).length){this.resolveOffsets(t,e);let i=0,o=0;if(t.forEach(((e,a)=>{const l=e.cue.pre,h=e.cue.post,d=t[a-1]||null,c=e.appendInPlace,u=h?r:e.startOffset,f=e.duration,g=e.timelineOccupancy===da.Range?f:0,m=e.resumptionOffset,p=(null==d?void 0:d.startTime)===u,v=u+e.cumulativeDuration;let y=c?v+f:u+m;if(l||!h&&u<=0){const t=o;o+=g,e.timelineStart=v;const i=n;n+=f,s.push({event:e,start:v,end:y,playout:{start:i,end:n},integrated:{start:t,end:o}})}else{if(!(u<=r))return;{if(!p){const r=u-i;if(r>.033){const l=i,h=o;o+=r;const d=n;n+=r;const c={previousEvent:t[a-1]||null,nextEvent:e,start:l,end:l+r,playout:{start:d,end:n},integrated:{start:h,end:o}};s.push(c)}else r>0&&d&&(d.cumulativeDuration+=r,s[s.length-1].end=u)}h&&(y=v),e.timelineStart=v;const r=o;o+=g;const l=n;n+=f,s.push({event:e,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const E=e.resumeTime;i=h||E>r?r:E})),i<r){var a;const t=i,e=o,l=r-i;o+=l;const h=n;n+=l,s.push({previousEvent:(null==(a=s[s.length-1])?void 0:a.event)||null,nextEvent:null,start:i,end:t+l,playout:{start:h,end:n},integrated:{start:e,end:o}})}this.setDurations(r,n,o)}else{const t=0;s.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 s}setDurations(t,e,s){this.durations={primary:t,playout:e,integrated:s}}resolveOffsets(t,e){const s=e.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;t.forEach(((a,o)=>{const l=a.cue.pre,h=a.cue.post,d=l?0:h?i:a.startTime;this.updateAssetDurations(a);if(n===d?a.cumulativeDuration=r:(r=0,n=d),!h&&a.snapOptions.in&&(a.resumeAnchor=Se(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,e)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<t.length){t[o+1].startTime-t[o].resumeTime<.033&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const c=g(a.resumeOffset)?a.resumeOffset:a.duration;r+=c}))}primaryCanResumeInPlaceAt(t,e){const s=t.resumeTime,i=t.startTime+t.resumptionOffset;if(Math.abs(s-i)>ha)return this.log(`"${t.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1;if(!e)return this.log(`"${t.identifier}" resumption ${s} can not be aligned with media (none selected)`),!1;return!Object.keys(e).some((i=>{const r=e[i].details,n=r.edge;if(s>=n)return this.log(`"${t.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=Se(null,r.fragments,s);if(!a)return this.log(`"${t.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s)<ha+o||Math.abs(a.end-s)<ha+o)&&(this.log(`"${t.identifier}" resumption ${s} not aligned with ${i} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)}))}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let s=0,i=!1,r=!1;t.assetList.forEach(((t,n)=>{const a=e+s;t.startOffset=s,t.timelineStart=a,i||(i=null===t.duration),r||(r=!!t.error);const o=t.error?0:t.duration||0;s+=o})),t.duration=i&&!r?Math.max(s,t.duration):s}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function ya(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class Ea{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const s=t.assetListUrl;let i;try{i=ga(s,this.hls.sessionId,t.baseUrl)}catch(e){const i=this.assignAssetListError(t,y.ASSET_LIST_LOAD_ERROR,e,s);return void this.hls.trigger(E.ERROR,i)}e&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+e);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:i.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,s,i,r)=>{const n=e.data,a=null==n?void 0:n.ASSETS;if(Array.isArray(a))t.assetListResponse=n,this.hls.trigger(E.ASSET_LIST_LOADED,{event:t,assetListResponse:n,networkDetails:r});else{const e=this.assignAssetListError(t,y.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);this.hls.trigger(E.ERROR,e)}},onError:(e,s,i,r)=>{const n=this.assignAssetListError(t,y.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${s.url})`),s.url,r,i);this.hls.trigger(E.ERROR,n)},onTimeout:(e,s,i)=>{const r=this.assignAssetListError(t,y.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,e,i);this.hls.trigger(E.ERROR,r)}};return n.load(a,l,h),this.hls.trigger(E.ASSET_LIST_LOADING,{event:t}),n}assignAssetListError(t,e,s,i,r,n){return t.error=s,{type:v.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:i,error:s,networkDetails:n,stats:r}}}function Ta(t,e,s){Sa(t,e,s),t.addEventListener(e,s)}function Sa(t,e,s){t.removeEventListener(e,s)}function La(t){null==t||t.play().catch((()=>{}))}class Aa{constructor(t){this.buffered=void 0;const e=(e,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return t[s][e]};this.buffered={get length(){return t.length},end:s=>e("end",s,t.length),start:s=>e("start",s,t.length)}}}const Ra={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},ba=t=>String.fromCharCode(Ra[t]||t),Ia=15,_a=100,ka={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Da={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Pa={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ca={25:2,26:4,29:6,30:8,31:10,27:13,28:15},wa=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class xa{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;B.log(`${this.time} [${t}] ${s}`)}}}const Oa=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e};class Ma{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 s=0;s<e.length;s++){const i=e[s];t.hasOwnProperty(i)&&(this[i]=t[i])}}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 Fa{constructor(){this.uchar=" ",this.penState=new Ma}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 Na{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Ma,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<_a;t++)this.chars.push(new Fa);this.logger=t}equals(t){for(let e=0;e<_a;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<_a;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<_a;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>_a&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=_a)}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=ba(t);this.pos>=_a?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<_a;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 s=0;s<_a;s++){const i=this.chars[s].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class Ua{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<Ia;e++)this.rows.push(new Na(t));this.logger=t}reset(){for(let t=0;t<Ia;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let s=0;s<Ia;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<Ia;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<Ia;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 = "+ce(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<Ia;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[t].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let i=0;i<this.nrRollUpRows;i++)this.rows[e-this.nrRollUpRows+i+1].copy(s.rows[t+i])}}this.currRow=e;const s=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,i=Math.max(e-1,0);s.setCursor(t.indent),t.color=s.chars[i].penState.foreground}const i={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(t){this.logger.log(2,(()=>"bkgData = "+ce(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 s="",i=-1;for(let s=0;s<Ia;s++){const r=this.rows[s].getTextString();r&&(i=s+1,t?e.push("Row "+i+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}}class Ba{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Ua(s),this.nonDisplayedMemory=new Ua(s),this.lastOutputScreen=new Ua(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[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 s=Math.floor(t/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[s]}this.logger.log(2,"MIDROW: "+ce(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 $a{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new xa;this.channels=[null,new Ba(t,e,i),new Ba(t+1,s,i)]}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 s=127&e[t],i=127&e[t+1];let r=!1,n=null;if(0===s&&0===i)continue;this.logger.log(3,(()=>"["+Oa([e[t],e[t+1]])+"] -> ("+Oa([s,i])+")"));const a=this.cmdHistory;if(s>=16&&s<=31){if(Ka(s,i,a)){Ga(null,null,a),this.logger.log(3,(()=>"Repeated command ("+Oa([s,i])+") is dropped"));continue}Ga(s,i,this.cmdHistory),r=this.parseCmd(s,i),r||(r=this.parseMidrow(s,i)),r||(r=this.parsePAC(s,i)),r||(r=this.parseBackgroundAttributes(s,i))}else Ga(null,null,a);if(!r&&(n=this.parseChars(s,i),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 "+Oa([s,i])+" orig: "+Oa([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 s=20===t||21===t||23===t?1:2,i=this.channels[s];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),this.currentChannel=s,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(e),this.logger.log(3,(()=>"MIDROW ("+Oa([t,e])+")")),!0)}return!1}parsePAC(t,e){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?ka[t]:Pa[t]:1===i?Da[t]:Ca[t];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(s,e)),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=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 '"+ba(t)+"' in channel "+s)),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(3,(()=>"Char codes = "+Oa(i).join(","))),i}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let s;const i={};16===t||24===t?(s=Math.floor((e-32)/2),i.background=wa[s],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}Ga(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}}function Ga(t,e,s){s.a=t,s.b=e}function Ka(t,e,s){return s.a===t&&s.b===e}var Ha=function(){if(null!=As&&As.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const s=e.toLowerCase();return!!~t.indexOf(s)&&s}function i(t){return s(e,t)}function r(t,...e){let s=1;for(;s<arguments.length;s++){const e=arguments[s];for(const s in e)t[s]=e[s]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=e,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,L="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return h},set:function(t){h=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return d},set:function(t){d=!!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 i=function(e){return s(t,e)}(e);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");m=i,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=i(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=i(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 L},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");L=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Va{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Ya(t){function e(t,e,s,i){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(i||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}class ja{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let i=0;i<s.length;++i)if(e===s[i]){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 s=parseFloat(e);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}}function Wa(t,e,s,i){const r=i?t.split(i):[t];for(const t in r){if("string"!=typeof r[t])continue;const i=r[t].split(s);if(2!==i.length)continue;e(i[0],i[1])}}const qa=new Ha(0,0,""),Xa="middle"===qa.align?"middle":"center";function za(t,e,s){const i=t;function r(){const e=Ya(t);if(null===e)throw new Error("Malformed timestamp: "+i);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'): "+i);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const i=new ja;Wa(t,(function(t,e){let r;switch(t){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===e){i.set(t,s[r].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),i.integer(t,r[0]),i.percent(t,r[0])&&i.set("snapToLines",!1),i.alt(t,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",Xa,"end"]);break;case"position":r=e.split(","),i.percent(t,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",Xa,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",Xa,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===qa.line&&(r=-1),e.line=r,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",Xa);let n=i.get("position","auto");"auto"===n&&50===qa.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function Qa(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class Ja{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Va,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=Qa(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const i=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,e.buffer=t.slice(s),i}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=s();const i=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let i=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(i?i=!1:t=s(),e.state){case"HEADER":/:/.test(t)?Wa(t,(function(t,e){}),/:/):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 Ha(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{za(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==t.indexOf("--\x3e");if(!t||s&&(i=!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 Za=/\r\n|\n\r|\n|\r/g,to=function(t,e,s=0){return t.slice(s,s+e.length)===e};function eo(t,e,s){return la(t.toString())+la(e.toString())+la(s)}function so(t,e,s,i,r,n,a){const o=new Ja,l=K(new Uint8Array(t)).trim().replace(Za,"\n").split("\n"),h=[],d=e?function(t,e=1){return jr(t,9e4,1/e)}(e.baseTime,e.timescale):0;let c,u="00:00.000",f=0,m=0,p=!0;o.oncue=function(t){const n=s[i];let a=s.ccOffset;const o=(f-d)/9e4;if(null!=n&&n.new&&(void 0!==m?a=s.ccOffset=n.start:function(t,e,s){let i=t[e],r=t[i.prevCC];if(!r||!r.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=i.start-r.start,i.new=!1,i=r,r=t[i.prevCC]}t.presentationOffset=s}(s,i,o)),o){if(!e)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,u=Zr(9e4*(t.startTime+a-m),9e4*r)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const g=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(g)),t.id||(t.id=eo(t.startTime,t.endTime,g)),t.endTime>0&&h.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?a(c):n(h)},l.forEach((t=>{if(p){if(to(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{to(t,"LOCAL:")?u=t.slice(6):to(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{m=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(g(e)&&g(s)&&g(i)&&g(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*i,e+=36e5*r,e}(u)/1e3}catch(t){c=t}return}""===t&&(p=!1)}o.parse(t+"\n")})),o.flush()}const io="stpp.ttml.im1t",ro=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,no=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ao={left:"start",center:"center",right:"end",start:"start",end:"end"};function oo(t,e,s,i){const r=vt(new Uint8Array(t),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map((t=>K(t))),a=function(t,e,s=1,i=!1){return jr(t,e,1/s,i)}(e.baseTime,1,e.timescale);try{n.forEach((t=>s(function(t,e){const s=(new DOMParser).parseFromString(t,"text/xml"),i=s.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce(((t,e)=>(t[e]=i.getAttribute(`ttp:${e}`)||r[e],t)),{}),a="preserve"!==i.getAttribute("xml:space"),o=ho(lo(i,"styling","style")),l=ho(lo(i,"layout","region")),h=lo(i,"body","[begin]");return[].map.call(h,(t=>{const s=co(t,a);if(!s||!t.hasAttribute("begin"))return null;const i=go(t.getAttribute("begin"),n),r=go(t.getAttribute("dur"),n);let h=go(t.getAttribute("end"),n);if(null===i)throw fo(t);if(null===h){if(null===r)throw fo(t);h=i+r}const d=new Ha(i-e,h-e,s);d.id=eo(d.startTime,d.endTime,d.text);const c=function(t,e,s){const i="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&&s.hasOwnProperty(a)&&(r=s[a]);return n.reduce(((s,n)=>{const a=uo(e,i,n)||uo(t,i,n)||uo(r,i,n);return a&&(s[n]=a),s}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:u}=c;if(u){const t=ao[u];t&&(d.lineAlign=t),d.align=u}return P(d,c),d})).filter((t=>null!==t))}(t,a))))}catch(t){i(t)}}function lo(t,e,s){const i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function ho(t){return t.reduce(((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t}),{})}function co(t,e){return[].slice.call(t.childNodes).reduce(((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?co(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent}),"")}function uo(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function fo(t){return new Error(`Could not parse ttml timestamp ${t}`)}function go(t,e){if(!t)return null;let s=Ya(t);return null===s&&(ro.test(t)?s=function(t,e){const s=ro.exec(t),i=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/e.frameRate}(t,e):no.test(t)&&(s=function(t,e){const s=no.exec(t),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),s}class mo{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,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function po(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function vo(t,e){return!!t&&t.kind===po(e)&&mn(e,t)}const yo=/\s/,Eo={newCue(t,e,s,i){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let t=0;t<n.chars.length;t++)yo.test(n.chars[t].uchar)&&o?l++:(h+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===s&&(s+=1e-4),l>=16?l--:l++;const i=Qa(h.trim()),f=eo(e,s,i);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,s,i),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=>ra(t,e)))),r}};const To=/(\d+)-(\d+)\/(\d+)/;class So{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||Lo,this.controller=new self.AbortController,this.stats=new Z}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,e,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(P({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),n="arraybuffer"===t.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&g(o)?o:l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,t,this.response))}),e.timeout);(on(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((s=>{var r;this.response=this.loader=s;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,t,this.response))}),l-(a-i.loading.start)),!s.ok){const{status:t,statusText:e}=s;throw new Ao(e||"fetch, bad network response",t,s)}i.loading.first=a,i.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=To.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(g(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(s.headers)||i.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&g(e.highWaterMark)?this.loadProgressively(s,i,t,e.highWaterMark,o):n?s.arrayBuffer():"json"===t.responseType?s.json():s.text()})).then((s=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=s[a];l&&(i.loaded=i.total=l);const h={url:o.url,data:s,code:o.status},d=null==(r=this.callbacks)?void 0:r.onProgress;d&&!g(e.highWaterMark)&&d(i,t,s,o),null==(n=this.callbacks)||n.onSuccess(h,i,t,o)})).catch((e=>{var s;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=e&&e.code||0,n=e?e.message:null;null==(s=this.callbacks)||s.onError({code:r,text:n},t,e?e.details:null,i)}))}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,s,i=0,r){const n=new Fi,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&r(e,s,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(e,s,n.flush().buffer,t)):r(e,s,l.buffer,t),o()})).catch((()=>Promise.reject()));return o()}}function Lo(t,e){return new self.Request(t.url,e)}class Ao extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}}const Ro=/^age:\s*[\d.]+\s*$/im;class bo{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 Z,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,s){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=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return r(s,e.url)})).catch((t=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",e.url,!0),r(s,e.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)})).catch((t=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:t.message},e,s,i)})):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const e in i)t.setRequestHeader(e,i[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&g(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,l="text"===e.responseType?e.responseText:null;if(i>=200&&i<300){const r=null!=l?l:e.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===e.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,t,r,e);const h={url:e.responseURL,data:r,code:i};return void(null==(a=this.callbacks)||a.onSuccess(h,s,t,e))}}const h=r.loadPolicy.errorRetry;var o;if(De(h,s.retry,!1,{url:t.url,data:void 0,code:i}))this.retry(h);else B.error(`${i} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:i,text:e.statusText},t,e,s)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(De(t,this.stats.retry,!0))this.retry(t);else{var e;B.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:s}=this;this.retryDelay=_e(t,s.retry),s.retry++,B.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.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&&Ro.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 Io=w(w({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,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,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:bo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends x{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.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:s,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,h=i?i.duration:s.duration,d=o-l.loading.start,c=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const m=f>-1&&f!==u,p=!!t||m;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const v=r.mainForwardBufferInfo;if(!p&&null===v)return;const y=this.bwEstimator.getEstimateTTFB(),T=Math.abs(a.playbackRate);if(d<=Math.max(y,h/(2*T)*1e3))return;const S=v?v.len/T:0,L=l.loading.first?l.loading.first-l.loading.start:-1,A=l.loaded&&L>-1,R=this.getBwEstimate(),b=r.levels,I=b[u],_=Math.max(l.loaded,Math.round(h*(s.bitrate||I.averageBitrate)/8));let k=A?d-L:d;k<1&&A&&(k=Math.min(d,8*l.loaded/R));const D=A?1e3*l.loaded/k:0,P=y/1e3,C=D?(_-l.loaded)/D:8*_/R+P;if(C<=S)return;const w=D?8*D:R,x=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),O=this.hls.config.abrBandWidthUpFactor;let M,F=Number.POSITIVE_INFINITY;for(M=u-1;M>c;M--){const t=b[M].maxBitrate,e=!b[M].details||x;if(F=this.getTimeToLoadFrag(P,w,h*t,e),F<Math.min(S,h+P))break}if(F>=C)return;if(F>10*h)return;A?this.bwEstimator.sample(d-Math.min(y,L),l.loaded):this.bwEstimator.sampleTTFB(d);const N=b[M].maxBitrate;this.getBwEstimate()*O>N&&this.resetEstimator(N);const U=this.findBestLevel(N,c,M,0,S,1,1);U>-1&&(M=U),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} 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: ${C.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|L} ms\n Current BW estimate: ${g(R)?0|R:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${M} @ ${0|N} bps`),r.nextLoadLevel=r.nextAutoLevel=M,this.clearTimer();const B=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===M&&M>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>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,M>c){let e=this.findBestLevel(this.hls.levels[c].bitrate,c,M,0,t,1,1);-1===e&&(e=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};m||C>2*F?B():this.timer=self.setInterval(B,1e3*F),r.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},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 k(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.FRAG_LOADING,this.onFragLoading,this),t.on(E.FRAG_LOADED,this.onFragLoaded,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this),t.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.FRAG_LOADING,this.onFragLoading,this),t.off(E.FRAG_LOADED,this.onFragLoaded,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this),t.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,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 s=e.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=e.part)?i: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 y.BUFFER_ADD_CODEC_ERROR:case y.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case y.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:i}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const e=performance.now(),s=i?i.stats:t.stats,r=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,s,i){return t+s/e+(i?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,r=i.end-i.first;g(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:s}){const i=s?s.stats:e.stats;if(e.type===R&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+i.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:i,frag:e,part:s,id:e.type};this.onFragBuffered(E.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))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(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==R||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,e,t,0,i,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(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,h,d);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`),h=d=1}}const u=this.findBestLevel(o,n,i,l,c,h,d);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=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,s,i,r,n,a){var o;const l=i+r,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:m,loadLevel:p,config:v}=this.hls;if(1===f.length)return 0;const y=f[d],E=!(null==(o=this.hls.latestLevelDetails)||!o.live),T=-1===p||-1===h;let S,L="SDR",A=(null==y?void 0:y.frameRate)||0;const{audioPreference:R,videoPreference:b}=v,I=this.audioTracksByGroup||(this.audioTracksByGroup=fe(m));let _=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(t,e,s,i){return t.slice(s,i+1).reduce(((t,s,i)=>{if(!s.codecSet)return t;const r=s.audioGroups;let n=t[s.codecSet];n||(t[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach((t=>{if(!t)return;const s=e.groups[t];s&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach((t=>{n.channels[t]=(n.channels[t]||0)+s.channels[t]})))})),t}),{})}(f,I,e,s)),r=function(t,e,s,i,r){const n=Object.keys(t),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let d=!1,c=!1,u=1/0,f=1/0,m=1/0,p=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=de(e,r);for(let e=n.length;e--;){const s=t[n[e]];d||(d=s.channels[2]>0),u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),m=Math.min(m,s.minBitrate),T.filter((t=>s.videoRanges[t]>0)).length>0&&(c=!0)}u=g(u)?u:0,f=g(f)?f:0;const S=Math.max(1080,u),L=Math.max(30,f);m=g(m)?m:s,s=Math.max(m,s),c||(e=void 0);const A=n.length>1;return{codecSet:n.reduce(((e,i)=>{const r=t[i];if(i===e)return e;if(y=c?T.filter((t=>r.videoRanges[t]>0)):[],A){if(r.minBitrate>s)return ue(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return ue(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return ue(i,`audio codec preference "${o}" not found`),e;if(a&&!h){if(!r.channels[a])return ue(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||h)&&d&&0===r.channels[2])return ue(i,"no renditions with stereo sound found"),e;if(r.minHeight>S)return ue(i,`min resolution of ${r.minHeight} > maximum of ${S}`),e;if(r.minFramerate>L)return ue(i,`min framerate of ${r.minFramerate} > maximum of ${L}`),e;if(!y.some((t=>r.videoRanges[t]>0)))return ue(i,`no variants with VIDEO-RANGE of ${ce(y)} found`),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return ue(i,`video codec preference "${l}" not found`),e;if(r.maxScore<v)return ue(i,`max score of ${r.maxScore} < selected max of ${v}`),e}return e&&(Kt(i)>=Kt(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,v=r.maxScore,i)}),void 0),videoRanges:y,preferHDR:E,minFramerate:f,minBitrate:m,minIndex:p}}(i,L,t,R,b),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:d}=r;_=h,S=n,L=d?a[a.length-1]:a[0],A=o,t=Math.max(t,l),this.log(`picked start tier ${ce(r)}`)}else S=null==y?void 0:y.codecSet,L=null==y?void 0:y.videoRange;const k=u?u.duration:c?c.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=s;o>=e;o--){var C;const e=f[o],c=o>d;if(!e)continue;if(v.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&(Zt(e,I,L,A,t,R)||Dt(e.videoCodec))?(e.supportedPromise=te(e,I,s),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,i=s.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${i} ${ce(t)}`):t.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${ce(t)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}))):e.supportedResult=zt}if((S&&e.codecSet!==S||L&&e.videoRange!==L||c&&A>e.frameRate||!c&&A>0&&A<e.frameRate||e.supportedResult&&(null==(C=e.supportedResult.decodingInfoResults)||!C[0].smooth))&&(!T||o!==_)){P.push(o);continue}const m=e.details,y=(u?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||k;let b;b=c?a*t:n*t;const w=k&&i>=2*k&&0===r?e.averageBitrate:e.maxBitrate,x=this.getTimeToLoadFrag(D,b,w*y,void 0===m);if(b>=w&&(o===h||0===e.loadError&&0===e.fragmentError)&&(x<=D||!g(x)||E&&!this.bitrateTestDelay||x<l)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[P[0]].codecs}" ${f[P[0]].videoRange}; not compatible with "${S}" ${L}`),this.info(`switch candidate:${d}->${o} adjustedbw(${Math.round(b)})-bitrate=${Math.round(b-w)} ttfb:${D.toFixed(1)} avgDuration:${y.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${T} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls;return Math.min(Math.max(t,s),e)}},bufferController:class extends x{constructor(t,e){var s;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:s}=this;t&&this.log("Media source opened"),e&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:e,mediaSource:s}),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=(s=$(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.BUFFER_RESET,this.onBufferReset,this),t.on(E.BUFFER_APPENDING,this.onBufferAppending,this),t.on(E.BUFFER_CODECS,this.onBufferCodecs,this),t.on(E.BUFFER_EOS,this.onBufferEos,this),t.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(E.FRAG_PARSED,this.onFragParsed,this),t.on(E.FRAG_CHANGED,this.onFragChanged,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.BUFFER_RESET,this.onBufferReset,this),t.off(E.BUFFER_APPENDING,this.onBufferAppending,this),t.off(E.BUFFER_CODECS,this.onBufferCodecs,this),t.off(E.BUFFER_EOS,this.onBufferEos,this),t.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(E.FRAG_PARSED,this.onFragParsed,this),t.off(E.FRAG_CHANGED,this.onFragChanged,this),t.off(E.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const s={};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 i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===e?P(s,i.tracks):this.sourceBuffers.forEach((t=>{const[e]=t;e&&(s[e]=P({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null})),{media:t,mediaSource:e,tracks:s}}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 s;let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(t,e){const s=this.media=e.media,i=$(this.appendSource);if(this.transferData=this.overrides=void 0,s&&i){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(r),t)this._objectUrl=s.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{s.removeAttribute("src");const e=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||e&&r instanceof e,Tn(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,t),s.load()}catch(e){s.src=t}else s.src=t}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,s;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(s=t.constructor)?void 0:s.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 s=this.tracks,i=e.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(i&&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: ${ce(s,((t,e)=>"initSegment"===t?void 0:e))};\ntransfer tracks: ${ce(i,((t,e)=>"initSegment"===t?void 0:e))}}`),!G(i,s)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,r.forEach((t=>{const e=t,s=i[e];if(s){const t=s.buffer;if(t){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=as.getBuffered(t);i.detectEvictedFragments(e,s,r,null,!0)}const n=Sn(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,s)}}})),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const s=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)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 s=e.length;s--;)t&&e[s].abort(),r.removeSourceBuffer(e[s]);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}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Tn(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(E.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach((([t])=>{t&&this.resetBuffer(t)})),this.initTracks()}resetBuffer(t){var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Sn(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new pn(this.tracks)}onBufferCodecs(t,e){const s=this.tracks,i=Object.keys(e);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const r="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),n=!r&&this.sourceBufferCount&&this.media&&i.some((t=>!s[t]));r||n?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${i}" SourceBuffers`):(i.forEach((t=>{var i,r,n;const a=e[t],{id:o,codec:l,levelCodec:h,container:d,metadata:c,supplemental:u}=a;let f=s[t];const g=null==(i=this.transferData)||null==(r=i.tracks)?void 0:r[t],m=null!=g&&g.buffer?g:f,p=(null==m?void 0:m.pendingCodec)||(null==m?void 0:m.codec),v=null==m?void 0:m.levelCodec;f||(f=s[t]={buffer:void 0,listeners:[],codec:l,supplemental:u,container:d,levelCodec:h,metadata:c,id:o});const y=jt(p,v),E=null==y?void 0:y.replace(vn,"$1");let T=jt(l,h);const S=null==(n=T)?void 0:n.replace(vn,"$1");T&&y&&E!==S&&("audio"===t.slice(0,5)&&(T=Yt(T,this.appendSource)),this.log(`switching codec ${p} to ${T}`),T!==(f.pendingCodec||f.codec)&&(f.pendingCodec=T),f.container=d,this.appendChangeType(t,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((t,e)=>{const s=this.tracks[e];return t[e]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},t}),{})}appendChangeType(t,e,s){const i=`${e};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,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 s=t.start,i=s+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,R))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>i||null!=e&&e.buffer&&as.isBuffered(e.buffer,i)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,R))?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,e){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l}=e,h=l.buffering[r],d=a.sn,c=self.performance.now();h.start=c;const u=a.stats.buffering,f=o?o.stats.buffering:null;0===u.start&&(u.start=c),f&&0===f.start&&(f.start=c);const g=s.audio;let m=!1;"audio"===r&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const p=this.tracks.video,T=null==p?void 0:p.buffer;if(T&&"initSegment"!==d){const t=o||a,e=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend){if("video"===r){const s=t.end;if(e){const t=e.frag.start;(s>t||s<this.lastVideoAppendEnd||as.isBuffered(T,t))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const e=t.start+.05*t.duration,s=T.buffered,i=this.currentOp("video");s.length||i?!i&&!as.isBuffered(T,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const S=(o||a).start,L={label:`append-${r}`,execute:()=>{if(h.executeStart=self.performance.now(),m){const t=this.tracks[r];if(t){const e=t.buffer;if(e){const t=S-e.timestampOffset;Math.abs(t)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${S} (delta: ${t}) sn: ${d})`),e.timestampOffset=S)}}}this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();h.executeEnd=h.end=t,0===u.first&&(u.first=t),f&&0===f.first&&(f.first=t);const e={};this.sourceBuffers.forEach((([t,s])=>{t&&(e[t]=as.getBuffered(s))})),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:e})},onError:t=>{var e;const s={type:v.MEDIA_ERROR,parent:a.type,details:y.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:t,err:t,fatal:!1},i=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR)s.details=y.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)s.errorAction=Ne(!0);else if(t.name===yn&&0===this.sourceBufferCount)s.errorAction=Ne(!0);else{const t=++this.appendErrors[r];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${i||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||i)&&(s.fatal=!0)}this.hls.trigger(E.ERROR,s)}};this.append(L,r,this.isPending(this.tracks[r]))}getFlushOp(t,e,s){return this.log(`queuing "${t}" remove ${e}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:t})},onError:i=>{this.warn(`Failed to remove ${e}-${s} from "${t}" SourceBuffer`,i)}}}onBufferFlushing(t,e){const{type:s,startOffset:i,endOffset:r}=e;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach((([t])=>{t&&this.append(this.getFlushOp(t,i,r),t)}))}onFragParsed(t,e){const{frag:s,part:i}=e,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[st]?r.push("audiovideo"):(n[tt]&&r.push("audio"),n[et]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers((()=>{const t=self.performance.now();s.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:s.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:s,part:i,stats:e,id:s.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])=>{var e,s;return t&&(!(null!=(e=this.tracks[t])&&e.ended)||(null==(s=this.tracks[t])?void 0:s.ending))}))}onBufferEos(t,e){var s;this.sourceBuffers.forEach((([t])=>{if(t){const s=this.tracks[t];e.type&&e.type!==t||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${t} buffer reached EOS`)))}}));const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)}))&&(i?(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(E.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0)))}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(){const t=this.getDurationAndRange();t&&this.blockUntilOpen((()=>this.updateMediaSource(t)))}onError(t,e){if(e.details===y.BUFFER_APPEND_ERROR&&e.frag){var s;const t=null==(s=e.errorAction)?void 0:s.nextAutoLevel;g(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:s}=this;if(!s||null===e)return;if(!this.sourceBufferCount)return;const i=t.config,r=s.currentTime,n=e.levelTargetDuration,a=e.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(g(a)&&a>=0){const t=Math.max(a,n),e=Math.floor(r/n)*n-t;this.flushBackBuffer(r,n,e)}if(g(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){const t=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),e=Math.max(t,n),s=Math.floor(r/n)*n+e;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(t,e,s){this.sourceBuffers.forEach((([t,e])=>{if(e){const r=as.getBuffered(e);if(r.length>0&&s>r.start(0)){var i;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:s});const e=this.tracks[t];if(null!=(i=this.details)&&i.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:t})}}}))}flushFrontBuffer(t,e,s){this.sourceBuffers.forEach((([e,i])=>{if(i){const r=as.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||t>=a&&t<=o)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}}))}getDurationAndRange(){var t;const{details:e,mediaSource:s}=this;if(!e||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&e.live&&s.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,i)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return g(r)?{duration:r}:null;const n=this.media.duration;return i>(g(s.duration)?s.duration:0)&&i>n||!g(n)?{duration:i}:null}updateMediaSource({duration:t,start:e,end:s}){const i=this.mediaSource;this.media&&i&&"open"===i.readyState&&(i.duration!==t&&(g(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),i.duration=t),void 0!==e&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${e}-${s}.`),i.setLiveSeekableRange(e,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:s}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${ce(s)}`),this.tracksReady){var i;const t=null==(i=this.transferData)?void 0:i.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach((([e,s])=>{if(e){const i=this.tracks[e];t[e]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}})),this.hls.trigger(E.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(E.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in t){const n=r,a=t[n];if(this.isPending(a)){const t=this.getTrackCodec(a,n),r=`${a.container};codecs=${t}`;a.codec=t,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${ce(a)}`);try{const t=s.addSourceBuffer(r),i=Sn(n),o=[n,t];e[i]=o,a.buffer=t}catch(t){var i;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(n),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[n],void this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(t,e){const s=t.supplemental;let i=t.codec;s&&("video"===e||"audiovideo"===e)&&Ut(s,"video")&&(i=function(t,e){const s=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)Nt(e[t],"video")||s.push(e[t])}return e&&s.push(e),s.join(",")}(i,s));const r=jt(i,t.levelCodec);return r?"audio"===e.slice(0,5)?Yt(r,this.appendSource):r:""}trackSourceBuffer(t,e){const s=e.buffer;if(!s)return;const i=this.getTrackCodec(e,t);this.tracks[t]={buffer:s,codec:i,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 s=e.removedRanges;null!=s&&s.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:t})}))}get mediaSrc(){var t,e;const s=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==s?void 0:s.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 s=this.currentOp(t);s&&(s.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var s;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,e),this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const r=this.currentOp(t);r&&r.onError(i)}removeExecutor(t,e,s){const{media:i,mediaSource:r}=this,n=this.tracks[t],a=null==n?void 0:n.buffer;if(!i||!r||!a)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const o=g(i.duration)?i.duration:1/0,l=g(r.duration)?r.duration:1/0,h=Math.max(0,e),d=Math.min(s,o,l);d>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${d}] from the ${t} SourceBuffer`),a.remove(h,d)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const s=this.tracks[e],i=null==s?void 0:s.buffer;if(!i)throw new En(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.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:s}=this,i=e.map((t=>this.appendBlocker(t)));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then((e=>{s===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(t){t.forEach((t=>{var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;s&&!s.updating&&this.shiftAndExecuteNext(t)}))}append(t,e,s){this.operationQueue&&this.operationQueue.append(t,e,s)}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,s){const i=this.tracks[t];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,t);i.listeners.push({event:e,listener:n}),r.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const s=e.buffer;s&&(e.listeners.forEach((t=>{s.removeEventListener(t.event,t.listener)})),e.listeners.length=0)}},capLevelController:Ln,errorController:class extends x{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(E.ERROR,this.onError,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(E.ERROR,this.onError,this),t.off(E.ERROR,this.onErrorOut,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===R?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var s;if(e.fatal)return;const i=this.hls,r=e.context;switch(e.details){case y.FRAG_LOAD_ERROR:case y.FRAG_LOAD_TIMEOUT:case y.KEY_LOAD_ERROR:case y.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case y.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction=Ne());case y.FRAG_GAP:case y.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ce);case y.LEVEL_EMPTY_ERROR:case y.LEVEL_PARSING_ERROR:{var n,a;const t=e.parent===R?e.level:i.loadLevel;e.details===y.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(a=n.levelDetails)&&a.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case y.LEVEL_LOAD_ERROR:case y.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case y.AUDIO_TRACK_LOAD_ERROR:case y.AUDIO_TRACK_LOAD_TIMEOUT:case y.SUBTITLE_LOAD_ERROR:case y.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=i.loadLevelObj;if(t&&(r.type===L&&t.hasAudioGroup(r.groupId)||r.type===A&&t.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=Ce,void(e.errorAction.flags=Me)}return;case y.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=i.loadLevelObj,s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?e.errorAction={action:Ce,flags:Fe,hdcpLevel:s}:this.keySystemError(e)}return;case y.BUFFER_ADD_CODEC_ERROR:case y.REMUX_ALLOC_ERROR:case y.BUFFER_APPEND_ERROR:var o;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(o=e.level)?o:i.loadLevel);return;case y.INTERNAL_EXCEPTION:case y.BUFFER_APPENDING_ERROR:case y.BUFFER_FULL_ERROR:case y.LEVEL_SWITCH_ERROR:case y.BUFFER_STALLED_ERROR:case y.BUFFER_SEEK_OVER_HOLE:case y.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=Ne())}e.type===v.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const s=Ie(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(De(s,i,be(t),t.response))return{action:xe,flags:Oe,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(t,e);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=Ie(t.details.startsWith("key")?n:r,t),o=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(i){t.details!==y.FRAG_GAP&&i.fragmentError++;if(De(a,o,be(t),t.response))return{action:xe,flags:Oe,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,n;const e=t.details;i.loadError++,e===y.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||(s.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===b&&e===y.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===y.BUFFER_ADD_CODEC_ERROR||e===y.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:t})=>i.audioCodec!==t)),m="video"===t.sourceBufferName&&(e===y.BUFFER_ADD_CODEC_ERROR||e===y.BUFFER_APPEND_ERROR)&&h.some((({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e)),{type:p,groupId:v}=null!=(n=t.context)?n:{};for(let s=h.length;s--;){const r=(s+d)%h.length;if(r!==d&&r>=c&&r<=u&&0===h[r].loadError){var a,o;const s=h[r];if(e===y.FRAG_GAP&&f===R&&t.frag){const e=h[r].details;if(e){const s=Se(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(p===L&&s.hasAudioGroup(v)||p===A&&s.hasSubtitleGroup(v))continue;if(f===b&&null!=(a=i.audioGroups)&&a.some((t=>s.hasAudioGroup(t)))||f===I&&null!=(o=i.subtitleGroups)&&o.some((t=>s.hasSubtitleGroup(t)))||g&&i.audioCodec===s.audioCodec||!g&&i.audioCodec!==s.audioCodec||m&&i.codecSet===s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Ce,flags:Oe,nextAutoLevel:l}}return{action:Ce,flags:Me}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case Pe:break;case Ce:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===y.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,s=t.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:n}=s;switch(i){case Oe:this.switchLevel(t,n);break;case Fe:r&&(e.maxHdcpLevel=ee[ee.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(t,n)}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===y.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Xt(t.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${t.sourceBufferName}Codec`]===e&&this.hls.removeLevel(i)}}},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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.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),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,r=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(E.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,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:Ns,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,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:Eo,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 Oi{constructor(t,e,s){super(t,e,s,"subtitle-stream-controller",I),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(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=Ai,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:s,success:i}=e;if(rt(s)&&(this.fragPrevious=s),this.state=Ai,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let t=0;t<r.length;t++)if(a>=r[t].start&&a<=r[t].end){n=r[t];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(0===s&&i!==Number.POSITIVE_INFINITY){const t=i-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let s=0;s<e.length;)if(e[s].end<=t)e.shift();else{if(!(e[s].start<t))break;e[s].start=t,s++}})),this.fragmentTracker.removeFragmentsInRange(s,t,I)}}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===I&&(e.details===y.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Li&&(this.state=Ai))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&fn(this.levels,e)?this.levels=e.map((t=>new le(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new le(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,I),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==Li&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,di(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(Ti(n,t),l=n.fragmentStart):e&&(l=e.start,di(n,l))}if(o.details=n,this.levelLastLoaded=o,a===i&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Ai)){Se(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,i=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&ys(i.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,Es(i.method)).catch((t=>{throw r.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((s=>{const i=performance.now();r.trigger(E.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:i}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=Ai}))}}doTick(){if(this.media){if(this.state===Ai){const{currentTrackId:t,levels:e}=this,s=null==e?void 0:e[t];if(!s||!e.length||!s.details)return;if(this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=as.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:a,len:o}=n,l=s.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const h=l.fragments,d=h.length,c=l.edge;let u=null;const f=this.fragPrevious;if(a<c){const t=i.maxFragLookUpTolerance,e=a>c-t?0:t;u=Se(f,h,Math.max(h[0].start,a),e),!u&&f&&f.start<h[0].start&&(u=h[0])}else u=h[d-1];if(u=this.filterReplacedPrimary(u,s.details),!u)return;const g=h[u.sn-l.startSN-1];if(g&&g.cc===u.cc&&this.fragmentTracker.getState(g)===Ue&&(u=g),this.fragmentTracker.getState(u)===Ue){const t=this.mapToInitFragWhenRequired(u);t&&this.loadFragment(t,s,a)}}}else this.state=Ai}loadFragment(t,e,s){rt(t)?super.loadFragment(t,e,s):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new Aa(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends un{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=oa(this.media.textTracks);for(let s=0;s<e.length;s++)if("hidden"===e[s].mode)t=e[s];else if("showing"===e[s].mode){t=e[s];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.LEVEL_LOADING,this.onLevelLoading,this),t.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.LEVEL_LOADING,this.onLevelLoading,this),t.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(E.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 s=this.media;if(!s)return;const i=!!e.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;oa(s.textTracks).forEach((t=>{na(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:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.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 s=me(e,t);if(s>-1)r=t[s];else{const t=me(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<e.length;i++){const r=e[i];if((!s||r.default)&&(s||t)&&(!t||pe(r,t)))return i}if(t){for(let s=0;s<e.length;s++){const i=e[s];if(gn(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(gn(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){if(mn(e[s],t))return s}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==A||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 s=this.currentTrack;if(s&&pe(t,s))return s;const i=me(t,this.tracksInGroup);if(i>-1){const t=this.tracksInGroup[i];return this.setSubtitleTrack(i),t}if(s)return null;{const s=me(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=oa(t.textTracks),s=this.currentTrack;let i;if(s&&(i=e.filter((t=>mn(s,t)))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==i&&(t.mode="disabled")})),i){const t=this.subtitleDisplay?"showing":"hidden";i.mode!==t&&(i.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!g(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t]||null;if(this.trackId=t,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:t});const r=!!i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${t}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=i;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const d=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(d)}},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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(E.FRAG_LOADING,this.onFragLoading,this),t.on(E.FRAG_LOADED,this.onFragLoaded,this),t.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(E.FRAG_LOADING,this.onFragLoading,this),t.off(E.FRAG_LOADED,this.onFragLoaded,this),t.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new mo(this,"textTrack1"),e=new mo(this,"textTrack2"),s=new mo(this,"textTrack3"),i=new mo(this,"textTrack4");this.cea608Parser1=new $a(1,t,e),this.cea608Parser2=new $a(3,s,i)}addCues(t,e,s,i,r){let n=!1;for(let t=r.length;t--;){const i=r[t],d=(a=i[0],o=i[1],l=e,h=s,Math.min(o,h)-Math.max(a,l));if(d>=0&&(i[0]=Math.min(i[0],e),i[1]=Math.max(i[1],s),n=!0,d/(s-e)>.5))return}var a,o,l,h;if(n||r.push([e,s]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,s,i)}else{const r=this.Cues.newCue(null,e,s,i);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:n}=this;s===R&&(this.initPTS[e.cc]={baseTime:i,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach((t=>{this.onFragLoaded(E.FRAG_LOADED,t)})))}getExistingTrack(t,e){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(vo(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:s,media:i}=this,{label:r,languageCode:n}=e[t],a=this.getExistingTrack(r,n);if(a)s[t]=a,na(s[t]),ia(s[t],i);else{const e=this.createTextTrack("captions",r,n);e&&(e[t]=!0,s[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const s={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,s){const i=this.media;if(i)return i.addTextTrack(t,e,s)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const s=!!e.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach((t=>{na(i[t]),delete i[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++)na(e[t])}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[],i=s.some((t=>t.textCodec===io));if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(fn(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,e=t?oa(t.textTracks):null;if(this.tracks.forEach(((t,s)=>{let i;if(e){let s=null;for(let i=0;i<e.length;i++)if(e[i]&&vo(e[i],t)){s=e[i],e[i]=null;break}s&&(i=s)}if(i)na(i);else{const e=po(t);i=this.createTextTrack(e,t.name,t.lang),i&&(i.mode="disabled")}i&&this.textTracks.push(i)})),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(E.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 s=`textTrack${e[1]}`,i=this.captionsProperties[s];i&&(i.label=t.name,t.lang&&(i.languageCode=t.lang),i.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===R){var s,i;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(s=null==(i=e.part)?void 0:i.index)?s:-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:s,payload:i}=e;if(s.type===I)if(i.byteLength){const t=s.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[s.level],r=this.vttCCs;r[s.cc]||(r[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===io?this._parseIMSC1(s,i):this._parseVTTs(e)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;oo(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{s.logger.log(`Failed to parse IMSC1: ${e}`),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:s,payload:i}=t,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&-1===a)return void n.push(t);const o=this.hls;so(null!=(e=s.initSegment)&&e.data?_t(s.initSegment.data,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(t=>{this._appendCues(t,s.level),o.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})}),(e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(s,i),o.logger.log(`Failed to parse VTT cue: ${e}`),r&&a>s.cc||o.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:e})}))}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||oo(e,this.initPTS[t.cc],(()=>{s.textCodec=io,this._parseIMSC1(t,e)}),(()=>{s.textCodec="wvtt"}))}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach((t=>ra(s,t)))}else{const i=this.tracks[e];if(!i)return;const r=i.default?"default":"subtitles"+e;s.trigger(E.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===I&&this.onFragLoaded(E.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=e;if(s.type!==R||"NONE"!==this.closedCaptionsForLevel(s))for(let t=0;t<i.length;t++){const e=i[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const s=this.extractCea608Data(e);this.cea608Parser1.addData(i[t].pts,s[0]),this.cea608Parser2.addData(i[t].pts,s[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!r||"video"===r){const{captionsTracks:t}=this;Object.keys(t).forEach((i=>aa(t[i],e,s)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==i){const{textTracks:t}=this;Object.keys(t).forEach((s=>aa(t[s],e,i)))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let i=2;for(let r=0;r<s;r++){const s=t[i++],r=127&t[i++],n=127&t[i++];if(0===r&&0===n)continue;if(!!(4&s)){const t=3&s;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},audioStreamController:class extends Oi{constructor(t,e,s){super(t,e,s,"audio-stream-controller",b),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(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(E.BUFFER_RESET,this.onBufferReset,this),t.on(E.BUFFER_CREATED,this.onBufferCreated,this),t.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(E.FRAG_LOADING,this.onFragLoading,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(E.BUFFER_RESET,this.onBufferReset,this),t.off(E.BUFFER_CREATED,this.onBufferCreated,this),t.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(E.FRAG_LOADING,this.onFragLoading,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r}){if(s===R){const t=e.cc,s=this.fragCurrent;if(this.initPTS[t]={baseTime:i,timescale:r},this.log(`InitPTS for cc: ${t} found from main: ${i}/${r}`),this.mainAnchor=e,this.state===wi){const s=this.waitingData;(!s&&!this.loadingParts||s&&s.frag.cc!==t)&&(this.nextLoadPosition=this.findSyncFrag(e).start),this.tick()}else!this.hls.hasEnoughToStart&&s&&s.cc!==t?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(e).start,s.abortRequests(),this.resetLoadingState()):this.state===Ai&&this.tick()}}findSyncFrag(t){const e=this.getLevelDetails(),s=t.cc;return function(t,e,s){if(t&&t.startCC<=e&&t.endCC>=e){const i=s.start,r=s.end;let n=t.fragments;if(!s.relurl){const{fragmentHint:e}=t;e&&(n=n.concat(e))}return Te(n,(t=>t.cc<e||t.end<=i?1:t.cc>e||t.start>=r?-1:0))}return null}(e,s,t)||e&&Re(e.fragments,s)||t}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=Li);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s,this.state=Ai):this.state=_i,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case Ai:this.doTickIdle();break;case _i:{const{levels:t,trackId:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=wi}break}case Ii:{var t;const e=performance.now(),s=this.retryDate;if(!s||e>=s||null!=(t=this.media)&&t.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=Ai}break}case wi:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=bi;const t={frag:e,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&(this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${n.cc}`),this.nextLoadPosition=this.findSyncFrag(n).start,this.clearWaitingFragment())}else this.state=Ai}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.state!==Li&&(this.state=Ai))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:s,media:i,trackId:r}=this,n=e.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=_i,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,tt,b));const h=this.getFwdBufferInfo(l,b);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return e.trigger(E.BUFFER_EOS,{type:"audio"}),void(this.state=Pi);const d=h.len,c=e.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing?g:h.end;if(this.switchingTrack&&i){const t=g;o.PTSKnown&&t<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(d>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,h,R,c)),!p)return void(this.bufferFlushed=!0);let v=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&rt(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ge&&(this.mainFragLoading=v=null),v&&rt(v))){if(p.start>v.end){const t=this.fragmentTracker.getFragAtPos(m,R);t&&t.end>v.end&&(v=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(p.start>v.end)return}this.loadFragment(p,a,m)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map((t=>new le(t)))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==Li&&(this.setInterval(100),this.state=Ai,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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(E.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(t,e){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=e;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==Li&&(this.state=_i));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let d=0;if(r.live||null!=(s=h.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;if(h.details)d=this.alignPlaylists(r,h.details,null==(c=this.levelLastLoaded)?void 0:c.details);r.alignedSliding||(Ei(r,l),r.alignedSliding||Ti(r,l),d=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==_i||this.waitForCdnTuneIn(r)||(this.state=Ai),this.tick()}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,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 ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new cn(this.hls,b,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=i?i.index:-1,n=-1!==e,a=new rs(s.level,s.sn,s.stats.chunkCount,r.byteLength,e,n);c.push(r,f,d,"",s,i,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Fi,complete:!1};t.push(new Uint8Array(r)),this.state!==Li&&(this.state=wi)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===R&&rt(e.frag)&&(this.mainFragLoading=e,this.state===Ai&&this.tick())}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type===b)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(rt(s)){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,w({},t)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==R||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var s;if(e.fatal)this.state=Ci;else switch(e.details){case y.FRAG_GAP:case y.FRAG_PARSING_ERROR:case y.FRAG_DECRYPT_ERROR:case y.FRAG_LOAD_ERROR:case y.FRAG_LOAD_TIMEOUT:case y.KEY_LOAD_ERROR:case y.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(b,e);break;case y.AUDIO_TRACK_LOAD_ERROR:case y.AUDIO_TRACK_LOAD_TIMEOUT:case y.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==_i||(null==(s=e.context)?void 0:s.type)!==L||(this.state=Ai);break;case y.BUFFER_ADD_CODEC_ERROR:case y.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.resetLoadingState();break;case y.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case y.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==et&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==et){this.flushing=!1,this.bufferFlushed=!0,this.state===Pi&&(this.state=Ai);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,b),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&d){if(this.state=ki,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,g.tracks,t,n),i.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:g.tracks})}if(c){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[tt]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(tt,t,e,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=P({id:s,frag:o,details:d},f);i.trigger(E.FRAG_PARSING_METADATA,t)}if(u){const t=P({id:s,frag:o,details:d},u);i.trigger(E.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,s,i){if(this.state!==ki)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=b;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(E.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(E.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||i===Ue||i===$e)if(rt(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=wi;const s=this.mainDetails;s&&s.fragmentStart!==e.details.fragmentStart&&Ti(e.details,s)}else super.loadFragment(t,e,s);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;pe({name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},t,ve)||(Ee(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(E.AUDIO_TRACK_SWITCHED,w({},t))}},audioTrackController:class extends un{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(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.LEVEL_LOADING,this.onLevelLoading,this),t.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.LEVEL_LOADING,this.onLevelLoading,this),t.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(E.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.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.audioPreference;if(!r&&e){const s=me(e,t,ve);if(s>-1)r=t[s];else{const t=me(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==L||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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&pe(t,i,ve))return i;const r=me(t,this.tracksInGroup,ve);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(i){let i=e.loadLevel;-1===i&&(i=e.firstAutoLevel);const r=function(t,e,s,i,r){const n=e[i],a=e.reduce(((t,e,s)=>{const i=e.uri;return(t[i]||(t[i]=[])).push(s),t}),{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=ye(e,i,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return me(t,n,r)>-1}));return d>-1?d:ye(e,i,(e=>{const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return me(t,n,r)>-1}))}(t,e.levels,s,i,ve);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=me(t,s);if(e>-1)return s[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 s=this.currentTrack,i=e[t],r=i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${t} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=t,this.currentTrack=i,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,w({},i)),r)return;const n=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const i=e[s];if((!this.selectDefaultTrack||i.default)&&(!t||pe(t,i,ve)))return s}if(t){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(pe({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],ve))return t}for(let s=0;s<e.length;s++){const i=e[s];if(gn(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(gn(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&Ee(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}},emeController:ea,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:An.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:s}=t,i=this.hls.levels[e.level],r=this.getObjectType(e),n={d:1e3*(s||e).duration,ot:r};r!==An.VIDEO&&r!==An.AUDIO&&r!=An.MUXED||(n.br=i.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=s?this.getNextPart(s):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:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||t.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHED,this.onMediaDetached,this),t.on(E.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHED,this.onMediaDetached,this),t.off(E.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(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 s,i;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=e.tracks.video)?void 0:i.buffer}createData(){var t;return{v:1,sf:Rn.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){P(e,this.createData());const s=e.ot===An.INIT||e.ot===An.VIDEO||e.ot===An.MUXED;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:i}=this;i&&(e=Object.keys(e).reduce(((t,s)=>(i.includes(s)&&(t[s]=e[s]),t)),{}));const r={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),zn(t.headers,e,r)):t.url=Jn(t.url,e,r)}getNextFrag(t){var e;const s=null==(e=this.hls.levels[t.level])?void 0:e.details;if(s){const e=t.sn-s.startSN;return s.fragments[e+1]}}getNextPart(t){var e,s;const{index:i,fragment:r}=t,n=null==(e=this.hls.levels[r.level])||null==(s=e.details)?void 0:s.partList;if(n){const{sn:t}=r;for(let e=n.length-1;e>=0;e--){const s=n[e];if(s.index===i&&s.fragment.sn===t)return n[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?An.TIMED_TEXT:"initSegment"===t.sn?An.INIT:"audio"===e?An.AUDIO:"main"===e?this.hls.audioTracks.length?An.VIDEO:An.MUXED:void 0}getTopBandwidth(t){let e,s=0;const i=this.hls;if(t===An.AUDIO)e=i.audioTracks;else{const t=i.maxAutoLevel,s=t>-1?t+1:i.levels.length;e=i.levels.slice(0,s)}for(const t of e)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const e=this.media,s=t===An.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!e)return NaN;return 1e3*as.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}},contentSteeringController:class extends x{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(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.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:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===Ce&&s.flags===Me){const t=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:s,pathwayId:i,type:n}=e.context;s&&t?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&t&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),s.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${ce(i)} penalized: ${ce(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach((t=>{i-s[t]>3e5&&delete s[t]}));for(let i=0;i<t.length;i++){const r=t[i];if(r in s)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,mi(e),this.hls.trigger(E.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(e===L&&i[s].hasAudioGroup(t)||e===A&&i[s].hasSubtitleGroup(t))return i[s].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},i={};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 gs(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=ta(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new le({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++)h.addGroupId("audio",`${t.audioGroups[e]}_clone_${r}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)h.addGroupId("text",`${t.subtitleGroups[e]}_clone_${r}`);return h}));e.push(...o),Zn(this.audioTracks,s,a,r),Zn(this.subtitleTracks,i,a,r)}))}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(e);try{i=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==i.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+t)}const r={responseType:"json",url:i.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);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":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,s,i)=>{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)this.scheduleRefresh(this.uri||e.url,r);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}},interstitialsController:class extends x{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)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const s=e<=-.01;this.timelinePos=t,this.bufferedPos=t;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule()}if(this.checkBuffer(),s&&t<i.start||t>=i.end){var r;const t=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s){const e=this.findItemIndex(i);if(t>e){const s=this.schedule.findJumpRestrictedIndex(e+1,t);if(s>e)return void this.setSchedulePosition(s)}}return void this.setSchedulePosition(t)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const e=i.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;(s&&t<a||t>=a+o)&&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 s=this.playingAsset;if(!s)return;t>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(t,s)},this.onScheduleUpdate=(t,e)=>{const s=this.schedule,i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=t.map((t=>t.identifier)),l=!(!r.length&&!o.length);if(l&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map((t=>ya(t)))}`),o.length&&this.log(`Removed events ${o}`),this.playerQueue.forEach((t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,s=t.timelineOffset-e;if(s)try{t.timelineOffset=e}catch(i){Math.abs(s)>ha&&this.warn(`${i} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}})),i){const t=this.updateItem(i,this.timelinePos);this.itemsMatch(i,t)&&(this.playingItem=t,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const h=this.bufferingItem;if(h){const t=this.updateItem(h,this.bufferedPos);this.itemsMatch(h,t)?this.bufferingItem=t:h.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(h.event,null))}if(t.forEach((t=>{t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,null)}))})),l||e){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.includes(i.event.identifier))return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new Ea(t),this.schedule=new va(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(E.BUFFER_APPENDED,this.onBufferAppended,this),t.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(E.MEDIA_ENDED,this.onMediaEnded,this),t.on(E.ERROR,this.onError,this),t.on(E.DESTROYING,this.onDestroying,this)}unregisterListeners(){const t=this.hls;t&&(t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(E.BUFFER_CODECS,this.onBufferCodecs,this),t.off(E.BUFFER_APPENDED,this.onBufferAppended,this),t.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(E.MEDIA_ENDED,this.onMediaEnded,this),t.off(E.ERROR,this.onError,this),t.off(E.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.manager=null,this.hls=this.HlsPlayerClass=this.schedule=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){Sa(t,"play",this.onPlay),Sa(t,"pause",this.onPause),Sa(t,"seeking",this.onSeeking),Sa(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const s=this.media=e.media;Ta(s,"seeking",this.onSeeking),Ta(s,"timeupdate",this.onTimeupdate),Ta(s,"play",this.onPlay),Ta(s,"pause",this.onPause)}onMediaAttached(t,e){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const t=this.findItemIndex(s);this.setSchedulePosition(t)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const t=this,e=()=>t.bufferingItem||t.waitingItem,s=e=>e?t.getAssetPlayer(e.identifier):e,i=(e,i,r,a,o)=>{if(e){let l=e[i].start;const h=e.event;if(h){if("playout"===i||h.timelineOccupancy!==da.Point){const t=s(r);(null==t?void 0:t.interstitial)===h&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?n():t[a])-e.start}return l}return 0},r=(e,s)=>{if(0!==e&&"primary"!==s&&t.schedule.length){var i;const r=t.schedule.findItemIndexAtTime(e),n=null==(i=t.schedule.items)?void 0:i[r];if(n){return e+(n[s].start-n.start)}}return e},n=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?a("primary"):Math.max(e,0)},a=e=>{var s;return null!=(s=t.primaryDetails)&&s.live?t.primaryDetails.edge:t.schedule.durations[e]},o=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,h=t.schedule.findItemIndexAtTime(e,r),d=null==(a=t.schedule.items)?void 0:a[h],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,d);if(l&&(f||g)){const n=s(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-s,h=(f?s:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let s=e;if("primary"!==r){const t=e-d[r].start;s=d.start+t}const i=!t.isInterstitial(d);if(t.isInterstitial(l)&&!l.event.appendInPlace||!i&&!d.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(h>n){const e=t.schedule.findJumpRestrictedIndex(n+1,h);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(i)t.timelinePos=s,t.checkBuffer();else{var m;const t=null==d||null==(m=d.event)?void 0:m.assetList;if(t){const s=e-(d[r]||d).start;for(let e=t.length;e--;){const i=t[e];if(i.duration&&s>=i.startOffset&&s<i.startOffset+i.duration){a=e;break}}}}t.setSchedulePosition(h,a)}}else{const e=t.media||(f?null==c?void 0:c.media:null);e&&(e.currentTime=s)}}},l=()=>{const s=t.effectivePlayingItem;if(t.isInterstitial(s))return s;const i=e();return t.isInterstitial(i)?i:null},h={get currentTime(){const e=l(),s=t.effectivePlayingItem;return s&&s===e?i(s,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(e){const s=l(),i=t.effectivePlayingItem;i&&i===s&&o(e+i.playout.start,"playout")},get duration(){const t=l();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const s=null==(e=l())?void 0:e.event.assetList;return s?s.map((e=>t.getAssetPlayer(e.identifier))):[]},get playingIndex(){var e;const s=null==(e=l())?void 0:e.event;return s&&t.effectivePlayingAsset?s.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var e,s;return(null==(e=t.schedule)||null==(s=e.events)?void 0:s.slice(0))||[]},get schedule(){var e,s;return(null==(e=t.schedule)||null==(s=e.items)?void 0:s.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const s=e();return t.findItemIndex(s)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return n()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){o(t,"primary")},get duration(){return a("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){o(t,"integrated")},get duration(){return a("integrated")},get seekableStart(){var e;return r((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,s=null==e?void 0:e.event;if(s&&!s.restrictions.skip){const i=t.findItemIndex(e);if(s.appendInPlace){const t=e.playout.start+e.event.duration;o(t+.001,"playout")}else t.advanceAfterAssetEnded(s,i,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,s=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&s)&&this.findItemIndex(e)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e,s;if(null===this.mediaSelection)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&null!=(t=this.bufferingItem)&&null!=(e=t.event)&&e.appendInPlace&&(r=this.primaryMedia);const n=null==(s=r)?void 0:s.currentTime;return void 0!==n&&g(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 s=this.getAssetPlayer(t);s&&this.transferMediaFromPlayer(s,e)}transferMediaFromPlayer(t,e){const s=t.interstitial.appendInPlace,i=t.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&i)return void(this.detachedData={media:i});const s=t.transferMedia();this.log(`transfer MediaSource from ${t} ${ce(s)}`),this.detachedData=s}else e&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(t,e){var s,i;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const t=this.getBufferingPlayer();t?(r=t.transferMedia(),h=`${t}`):h="detached MediaSource"}else h="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ce(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 d=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState),c=d&&r?r:e;if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${h}`),c===r){const e=a&&t.assetId===this.schedule.assetIdAtEnd;c.overrides={duration:this.schedule.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=t.events;if(!e||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(-1===s){const s=this.hls.startPosition;if(this.timelinePos=s,e.length&&e[0].cue.pre){const s=t.findEventIndex(e[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const e=this.timelinePos=s>0?s:0,i=t.findItemIndexAtTime(e);this.setSchedulePosition(i)}}else if(i&&!this.playingItem){const e=t.findItemIndex(i);this.setSchedulePosition(e)}}advanceAfterAssetEnded(t,e,s){const i=s+1;if(t.isAssetPastPlayoutLimit(i)||t.assetList[i].error){const s=this.schedule.items;if(s){const i=e+1;if(i>=s.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos<r&&(this.timelinePos=r,this.checkBuffer()),this.setSchedulePosition(i)}}else this.setSchedulePosition(e,i)}setScheduleToAssetAtTime(t,e){const s=this.schedule,i=e.parentIdentifier,r=s.getEvent(i);if(r){const e=s.findEventIndex(i),n=s.findAssetIndex(r,t);this.setSchedulePosition(e,n)}}setSchedulePosition(t,e){const s=this.schedule.items;if(!s||this.playbackDisabled)return;this.log(`setSchedulePosition ${t}, ${e}`);const i=t>=0?s[t]:null,r=this.playingItem,n=this.playingLastItem;if(this.isInterstitial(r)){var a;const l=r.event,h=this.playingAsset,d=null==h?void 0:h.identifier,c=d?this.getAssetPlayer(d):null;if(c&&d&&(!this.eventItemsMatch(r,i)||void 0!==e&&d!==(null==(a=l.assetList)?void 0:a[e].identifier))){var o;const e=l.findAssetIndex(h);this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${l.assetList.length} ${ma(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:e,event:l,schedule:s.slice(0),scheduleIndex:t,player:c}),this.retreiveMediaSource(d,i),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(r,i)&&(this.endedItem=r,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${ya(r)}`),l.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:l,schedule:s.slice(0),scheduleIndex:t}),l.cue.once)){this.updateSchedule();const t=this.schedule.items;if(i&&t){const s=this.schedule.findItemIndex(i);this.advanceSchedule(s,t,e,r,n)}return}}this.advanceSchedule(t,s,e,r,n)}advanceSchedule(t,e,s,i,r){const n=t>=0?e[t]:null,a=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach((e=>{const s=e.interstitial,i=this.schedule.findEventIndex(s.identifier);(i<t||i>t+1)&&this.clearInterstitial(s,n)})),this.isInterstitial(n)){this.timelinePos=Math.min(Math.max(this.timelinePos,n.start),n.end);const r=n.event;void 0===s&&(s=this.schedule.findAssetIndex(r,this.timelinePos));const o=this.waitingItem;this.assetsBuffered(n,a)||this.setBufferingItem(n);let l=this.preloadAssets(r,s);if(this.eventItemsMatch(n,o||i)||(this.waitingItem=n,this.log(`INTERSTITIAL_STARTED ${ya(n)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(E.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),!a)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=n;const h=r.assetList[s];if(!h){const i=e[t+1],n=this.media;return i&&n&&!this.isInterstitial(i)&&n.currentTime<i.start&&(n.currentTime=this.timelinePos=i.start),void this.advanceAfterAssetEnded(r,t,s||0)}if(l||(l=this.getAssetPlayer(h.identifier)),null===l||l.destroyed){const t=r.assetList.length;this.warn(`asset ${s+1}/${t} player destroyed ${r}`),l=this.createAssetPlayer(r,h,s)}if(!this.eventItemsMatch(n,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(l,s,e,t,a),this.shouldPlay&&La(l.media)}else null!==n?(this.resumePrimary(n,t,i),this.shouldPlay&&La(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t,e;return null==(t=this.mediaSelection)||null==(e=t.main)?void 0:e.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,s){var i;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${ya(t)}`),null==(i=this.detachedData)||!i.mediaSource){let s=this.timelinePos;(s<t.start||s>=t.end)&&(s=this.getPrimaryResumption(t,e),this.timelinePos=s),this.attachPrimary(s,t)}if(!s)return;const r=this.schedule.items;r&&(this.log(`resumed ${ya(t)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:r.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const s=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(s<t.fragmentStart||s>t.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return as.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,s){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(t,s)),s||(this.timelinePos=t,this.startLoadingPrimaryAt(t,s))}startLoadingPrimaryAt(t,e){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(s=i.mainForwardBufferInfo)?void 0:s.start)||i.media.currentTime)-t)>.5?i.startLoad(t,e):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level)return;const s=this.hls.levels[e.level],i=w(w({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,e){const s=this.hls.audioTracks[e.id],i=this.mediaSelection;if(!i)return void(this.altSelection=w(w({},this.altSelection),{},{audio:s}));const r=w(w({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const s=this.hls.subtitleTracks[e.id],i=this.mediaSelection;if(!i)return void(this.altSelection=w(w({},this.altSelection),{},{subtitles:s}));const r=w(w({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(t,e){const s=ge(e);this.playerQueue.forEach((t=>t.hls.setAudioOption(e)||t.hls.setAudioOption(s)))}onSubtitleTrackSwitch(t,e){const s=ge(e);this.playerQueue.forEach((t=>t.hls.setSubtitleOption(e)||-1!==e.id&&t.hls.setSubtitleOption(s)))}onBufferCodecs(t,e){const s=e.tracks;s&&(this.requiredTracks=s)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const i=e[t];if(i.cue.post){var s;const t=this.schedule.findEventIndex(i.identifier),e=null==(s=this.schedule.items)?void 0:s[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){const s=this.schedule.items;if(t&&s){return s[this.findItemIndex(t,e)]||null}return null}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 s;return!!e&&(t===e||t.event.identifier===(null==(s=e.event)?void 0:s.identifier))}findItemIndex(t,e){return t?this.schedule.findItemIndex(t,e):-1}updateSchedule(){const t=this.mediaSelection;t&&this.schedule.updateSchedule(t,[])}checkBuffer(t){const e=this.schedule.items;if(!e)return;const s=as.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=s.len<1),this.updateBufferedPos(s.end,e,t)}updateBufferedPos(t,e,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t)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=i.findItemIndexAtTime(t);if(this.bufferedPos<t){var l,h;const s=this.findItemIndex(r),i=Math.min(s+1,e.length-1),n=e[i];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=i),i-a>1&&!1===(null==r||null==(h=r.event)?void 0:h.appendInPlace))return;if(this.bufferedPos=t,o>s&&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 s&&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 s=this.getAssetPlayer(t.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(e))}))}setBufferingItem(t){const e=this.bufferingItem,s=this.schedule;if(this.itemsMatch(t,e))this.bufferingItem!==t&&(this.bufferingItem=t);else{const{items:i,events:r}=s;if(!i||!r)return e;const n=this.isInterstitial(t),a=this.getBufferingPlayer();if(this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos)),!this.playbackDisabled){const s=a?a.remaining:e?e.end-this.timelinePos:0;this.log(`buffered to boundary ${ya(t)}`+(e?` (${s.toFixed(2)} remaining)`:"")),n?t.event.assetList.forEach((t=>{const e=this.getAssetPlayer(t.identifier);e&&e.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((t=>t.pauseBuffering())))}this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}return e}bufferedToItem(t,e=0){const s=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==s){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),s=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(s)}bufferedToEvent(t,e){const s=t.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const t=this.preloadAssets(s,e);if(null!=t&&t.interstitial.appendInPlace){const i=s.assetList[e],r=this.primaryMedia;i&&r&&this.bufferAssetPlayer(t,r)}}}preloadAssets(t,e){const s=t.assetUrl,i=t.assetList.length,r=0===i&&!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}/${s?1:i} ${t}${n?` live-start: ${o} start-offset: ${n}`:""}`),s)return this.createAsset(t,0,0,r,t.duration,s);const l=this.assetListLoader.loadAssetList(t,n);l&&(t.assetListLoader=l)}else if(!n&&i){for(let s=e;s<i;s++){const e=t.assetList[s],i=this.getAssetPlayerQueueIndex(e.identifier);-1!==i&&!this.playerQueue[i].destroyed||e.error||this.createAssetPlayer(t,e,s)}return this.getAssetPlayer(t.assetList[e].identifier)}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(E.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})}))}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let s=0;s<e.length;s++)if(t===e[s].assetId)return s;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 s=0;s<t.length;s++)if(t[s].media===e)return t[s];return null}createAsset(t,e,s,i,r,n){const a={parentIdentifier:t.identifier,identifier:ca(t,n,e),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,s){this.log(`create HLSAssetPlayer for ${ma(e)}`);const i=this.hls,r=i.userConfig;let n=r.videoPreference;const a=i.loadLevelObj||i.levels[i.currentLevel];(n||a)&&(n=P({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>1){const s=e.duration;s&&t<s&&(h=t)}}const d=e.identifier,c=w(w({},r),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(c.timelineOffset=e.timelineStart));const u=c.cmcd;null!=u&&u.sessionId&&u.contentId&&(c.cmcd=P({},u,{contentId:la(e.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${t} and asset ${d}`);const f=new pa(this.HlsPlayerClass,c,t,e);this.playerQueue.push(f),t.assetList[s]=e;const g=i=>{if(i.live){const e=new Error(`Interstitials MUST be VOD assets ${t}`),i={fatal:!0,type:v.OTHER_ERROR,details:y.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};return void this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,e.message)}const r=i.edge-i.fragmentStart,n=e.duration;(null===n||r>n)&&(this.log(`Interstitial asset "${d}" duration change ${n} > ${r}`),e.duration=r,this.updateSchedule())};f.on(E.LEVEL_UPDATED,((t,{details:e})=>g(e))),f.on(E.LEVEL_PTS_UPDATED,((t,{details:e})=>g(e)));const m=(t,e)=>{const s=this.getAssetPlayer(d);if(s&&e.tracks){s.off(E.BUFFER_CODECS,m),s.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===s.assetItem&&t&&!s.media&&this.bufferAssetPlayer(s,t)}};f.on(E.BUFFER_CODECS,m);const p=()=>{var s;const i=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${i}`),!i)return;const r=this.schedule.findEventIndex(t.identifier),n=t.findAssetIndex(e),a=n+1,o=null==(s=this.schedule.items)?void 0:s[r];if(this.isInterstitial(o))if(-1===n||t.isAssetPastPlayoutLimit(a)||t.assetList[a].error){var l;const t=null==(l=this.schedule.items)?void 0:l[r+1];t&&this.bufferedToItem(t)}else this.bufferedToItem(o,a)};f.on(E.BUFFERED_TO_END,p);const T=e=>()=>{if(!this.getAssetPlayer(d))return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,e)};return f.once(E.MEDIA_ENDED,T(s)),f.once(E.PLAYOUT_LIMIT_REACHED,T(1/0)),f.on(E.ERROR,((e,i)=>{const r=this.getAssetPlayer(d);if(i.details!==y.BUFFER_STALLED_ERROR)this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,`Asset player error ${i.error} ${t}`);else if(null!=r&&r.media){const e=r.currentTime,s=r.duration-e;e&&t.appendInPlace&&s/r.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${d} ${t} at ${r.media.currentTime}`),p()):(this.warn(`Stalled at ${e} of ${e+s} in asset ${d} ${t}`),this.onTimeupdate(),this.checkBuffer(!0))}})),f.on(E.DESTROYING,(()=>{if(!this.getAssetPlayer(d))return;const e=new Error(`Asset player destroyed unexpectedly ${d}`),i={fatal:!0,type:v.OTHER_ERROR,details:y.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,e.message)})),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:s,event:t,player:f}),f}clearInterstitial(t,e){t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,e)})),t.reset()}clearAssetPlayer(t,e){const s=this.getAssetPlayerQueueIndex(t);if(-1!==s){this.log(`clearAssetPlayer "${t}" toSegment: ${e?ya(e):e}`);const i=this.playerQueue[s];this.transferMediaFromPlayer(i,e),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=t,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${t}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:s.slice(0),scheduleIndex:i,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var s,i;const{interstitial:r,assetItem:n,assetId:a}=t,o=this.schedule.findEventIndex(r.identifier),l=null==(s=this.schedule.items)?void 0:s[o];if(!l)return;this.setBufferingItem(l),this.bufferingAsset=n;const h=this.getBufferingPlayer();if(h===t)return;const d=r.appendInPlace;if(d&&!1===(null==h?void 0:h.interstitial.appendInPlace))return;const c=(null==h?void 0:h.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!t.tracks)return;if(c&&!G(c,t.tracks)){const e=new Error(`Asset "${a}" SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),s={fatal:!0,type:v.OTHER_ERROR,details:y.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},i=r.findAssetIndex(n);return void this.handleAssetItemError(s,r,o,i,e.message)}}this.transferMediaTo(t,e)}handleAssetItemError(t,e,s,i,r){if(t.details===y.BUFFER_STALLED_ERROR)return;const n=e.assetList[i]||null;let a=null;if(n){const t=this.getAssetPlayerQueueIndex(n.identifier);a=this.playerQueue[t]||null}const o=this.schedule.items,l=P({},t,{fatal:!1,errorAction:Ne(!0),asset:n,assetListIndex:i,event:e,schedule:o,scheduleIndex:s,player:a});if(this.warn(`Asset item error: ${t.error}`),this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,l),!t.fatal)return;const h=new Error(r);n&&(this.playingAsset!==n&&this.clearAssetPlayer(n.identifier,null),n.error=h),e.assetList.some((t=>!t.error))?e.appendInPlace&&(e.error=h):e.error=h,this.primaryFallback(e)}primaryFallback(t){const e=t.timelineStart,s=this.effectivePlayingItem;if(this.updateSchedule(),s){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${this.timelinePos} playing: ${s?ya(s):"<none>"} error: ${t.error}`),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e));let i=this.timelinePos;-1===i&&(i=this.hls.startPosition);const r=this.updateItem(s,i);if(this.itemsMatch(s,r))this.clearInterstitial(t,null);else{const t=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(t)}}else this.checkStart()}onAssetListLoaded(t,e){var s;const i=e.event,r=i.identifier,n=e.assetListResponse.ASSETS;if(!this.schedule.hasEvent(r))return;const a=i.timelineStart,o=i.duration;let l=0;n.forEach(((t,e)=>{const s=parseFloat(t.DURATION);this.createAsset(i,e,l,a+l,s,t.URI),l+=s})),i.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${o}) ${i}`);const h=this.waitingItem,d=(null==h?void 0:h.event.identifier)===r;this.updateSchedule();const c=null==(s=this.bufferingItem)?void 0:s.event;if(d){var u;const t=this.schedule.findEventIndex(r),e=null==(u=this.schedule.items)?void 0:u[t];if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return i.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${i}`),void this.primaryFallback(i)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==c?void 0:c.identifier)===r&&c.appendInPlace){const t=i.assetList[0],e=this.getAssetPlayer(t.identifier),s=this.primaryMedia;t&&e&&s&&this.bufferAssetPlayer(e,s)}}onError(t,e){switch(e.details){case y.ASSET_LIST_PARSING_ERROR:case y.ASSET_LIST_LOAD_ERROR:case y.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&this.primaryFallback(t);break}case y.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}}}});function _o(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(_o):Object.keys(t).reduce(((e,s)=>(e[s]=_o(t[s]),e)),{}):t}function ko(t,e){const s=t.loader;if(s!==So&&s!==bo)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=So,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Do extends is{constructor(t,e){super("gap-controller",t.logger),this.hls=null,this.fragmentTracker=null,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(E.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.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 s=this.media=e.media;Ta(s,"playing",this.onMediaPlaying),Ta(s,"waiting",this.onMediaWaiting),Ta(s,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:s}=this;s&&(Sa(s,"playing",this.onMediaPlaying),Sa(s,"waiting",this.onMediaWaiting),Sa(s,"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 s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const{media:n,stalled:a}=this;if(!n)return;const{seeking:o}=n,l=this.seeking&&!o,h=!this.seeking&&o,d=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&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(h||l)return void(l&&this.stallResolved(t));if(d)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})));if(!as.getBuffered(n).length)return void(this.nudgeRetry=0);const c=as.bufferInfo(n,t,0),u=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const e=Po(this.hls.inFlightFragments,t),s=c.len>2,i=!u||e||u-t>2&&!f.getPartialFragment(t);if(s||i)return;this.moved=!1}const g=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(c.len>0)&&!u)return;const e=Math.max(u,c.start||0)-t,s=!(null==g||!g.live)?2*g.targetduration:2,i=f.getPartialFragment(t);if(e>0&&(e<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const m=r.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting;if(null===a)return void(this.stalled=v>0&&p-v<m?v:p);const y=p-a;if(!o&&(y>=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(E.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}const S=as.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(S,y)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&t>i.end(0)){const s=as.bufferedInfo(as.timeRangesToArray(this.buffered.audio),t,0);if(s.len>1&&e>=s.start){const s=as.timeRangesToArray(i),r=as.bufferedInfo(s,e,0).bufferedIndex;if(r>-1&&r<s.length-1){const e=as.bufferedInfo(s,t,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===e||e>r)&&n-i<1&&t-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${i} -> ${n} buffered index: ${e}`);this.warn(s.message),this.media.currentTime+=1e-6;const r=this.fragmentTracker.getPartialFragment(t)||void 0,a=as.bufferInfo(this.media,t,0);this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e){var s,i;const{fragmentTracker:r,media:n}=this,a=null==(s=this.hls)?void 0:s.config;if(!n||!r||!a)return;const o=n.currentTime,l=null==(i=this.hls)?void 0:i.latestLevelDetails,h=r.getPartialFragment(o);if(h||null!=l&&l.live&&o<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const d=t.buffered;(d&&d.length>1&&t.len>a.maxBufferHole||t.nextStart&&t.nextStart-o<a.maxBufferHole)&&(e>1e3*a.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}_reportStall(t){const{hls:e,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&e){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ce(t)})`);this.warn(i.message),e.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:s,media:i}=this,r=null==(e=this.hls)?void 0:e.config;if(!i||!s||!r)return 0;const n=i.currentTime,a=as.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const e=a.len<=r.maxBufferHole,h=a.len>0&&a.len<1&&i.readyState<3,d=o-n;if(d>0&&(e||h)){if(d>r.maxBufferHole){let e=!1;if(0===n){const t=s.getAppendedFrag(0,R);t&&o<t.end&&(e=!0)}if(!e){const e=t||s.getAppendedFrag(n,R);if(e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(Po(this.hls.inFlightFragments,o))return 0;let t=!1,i=e.end;for(;i<o;){const e=s.getPartialFragment(i);if(!e){t=!0;break}i+=e.duration}if(t)return 0}}}const e=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${e}`),this.moved=!0,i.currentTime=e,null==t||!t.gap){const s=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${e}`);this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:t||void 0,buffer:a.len,bufferInfo:a})}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:s,nudgeRetry:i}=this,r=null==e?void 0:e.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,e.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),e.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:t.len,bufferInfo:t})}}}function Po(t,e){const s=Co(t.main);if(s&&s.start<=e)return s;const i=Co(t.audio);return i&&i.start<=e?i:null}function Co(t){if(!t)return null;switch(t.state){case Ai:case Li:case Pi:case Ci:return null}return t.frag}function wo(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function xo(t,e,s,i,r){let n=new t(e,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new t(e,s,ce(r?w({type:r},i):i))}return n}const Oo=(()=>{const t=wo();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Mo{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.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.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(t,e){var s;this.media=e.media,!1===(null==(s=e.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){const t=this.hls.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.removeCues&&na(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 s=t[e];if("metadata"===s.kind&&"id3"===s.label)return ia(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:i}}}=this;if(!s&&!i)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===cr.emsg&&!s||!i)continue;const a=or(r[t].data);if(a){const s=r[t].pts;let i=s+r[t].duration;i>Oo&&(i=Oo);i-s<=0&&(i=s+.25);for(let t=0;t<a.length;t++){const r=a[t];if(!lr(r)){this.updateId3CueEnds(s,e);const t=xo(n,s,i,r,e);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(t,e){var s;const i=null==(s=this.id3Track)?void 0:s.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===e&&r.startTime<t&&r.endTime===Oo&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let t;t="audio"===i?t=>t.type===cr.audioId3&&o:"video"===i?t=>t.type===cr.emsg&&a:t=>t.type===cr.audioId3&&o||t.type===cr.emsg&&a,aa(r,e,s,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:s}=this,{dateRanges:i}=t,r=Object.keys(i);let n=this.dateRangeCuesAppended;var a;if(s&&e)if(null!=(a=s.cues)&&a.length){const t=Object.keys(n).filter((t=>!r.includes(t)));for(let e=t.length;e--;){const i=t[e],r=n[i].cues;delete n[i],Object.keys(r).forEach((t=>{try{const e=r[t];e.removeEventListener("enter",this.onEventCueEnter),s.removeCue(e)}catch(t){}}))}}else n=this.dateRangeCuesAppended={};const o=t.fragments[t.fragments.length-1];if(0===r.length||!g(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=wo();for(let t=0;t<r.length;t++){const e=r[t],s=i[e],a=s.startTime,o=n[e],c=(null==o?void 0:o.cues)||{};let u=(null==o?void 0:o.durationKnown)||!1,f=Oo;const{duration:g,endDate:m}=s;if(m&&null!==g)f=a+g,u=!0;else if(s.endOnNext&&!u){const t=r.reduce(((t,e)=>{if(e!==s.id){const r=i[e];if(r.class===s.class&&r.startDate>s.startDate&&(!t||s.startDate<t.startDate))return r}return t}),null);t&&(f=t.startTime,u=!0)}const p=Object.keys(s.attr);for(let t=0;t<p.length;t++){const i=p[t];if("ID"===(d=i)||"CLASS"===d||"CUE"===d||"START-DATE"===d||"DURATION"===d||"END-DATE"===d||"END-ON-NEXT"===d)continue;const r=c[i];if(r)u&&!o.durationKnown?r.endTime=f:Math.abs(r.startTime-a)>.01&&(r.startTime=a,r.endTime=f);else if(l){let t=s.attr[i];ms(i)&&(h=t,t=Uint8Array.from(h.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const r=xo(l,a,f,{key:i,data:t},cr.dateRange);r&&(r.id=e,this.id3Track.addCue(r),c[i]=r,this.hls.config.interstitialsController&&("X-ASSET-LIST"!==i&&"X-ASSET-URL"!==i||r.addEventListener("enter",this.onEventCueEnter)))}}n[e]={cues:c,dateRange:s,durationKnown:u}}var h,d}}class Fo{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 s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(e,Math.max(1,s));this.changeMediaPlaybackRate(t,i)}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:s,targetduration:i}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}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 s=this.levelDetails;if(null===s)return null;const i=s.edge,r=t-e-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.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 s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(E.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(E.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 s;e.details===y.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var s,i;t.playbackRate!==e&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.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 No extends un{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(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this),t.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this),t.off(E.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 s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{var e;const h=t.attrs;let{audioCodec:d,videoCodec:c}=t;d&&(t.audioCodec=d=Yt(d,s)||void 0),0===(null==(e=c)?void 0:e.indexOf("avc1"))&&(c=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");if(s.length>2){let i=s.shift()+".";i+=parseInt(s.shift()).toString(16),i+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=i}}return e.join(",")}(c));const{width:u,height:f,unknownCodecs:g}=t;let m=g?g.length:0;if(g)for(let e=m;e--;){const s=g[e];this.isAudioSupported(s)?(t.audioCodec=d=d?`${d},${s}`:s,m--,Ft.audio[d.substring(0,4)]=2):this.isVideoSupported(s)&&(t.videoCodec=c=c?`${c},${s}`:s,m--,Ft.video[c.substring(0,4)]=2)}if(a||(a=!(!u||!f)),o||(o=!!c),l||(l=!!d),m||d&&!this.isAudioSupported(d)||c&&!this.isVideoSupported(c))return void this.log(`Some or all CODECS not supported "${h.CODECS}"`);const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=h,L=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(r[L])if(r[L].uri===t.url||t.attrs["PATHWAY-ID"])r[L].addGroupId("audio",h.AUDIO),r[L].addGroupId("text",h.SUBTITLES);else{const e=n[L]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=this.createLevel(t);r[L]=s,i.push(s)}else{const e=this.createLevel(t);r[L]=e,n[L]=1,i.push(e)}})),this.filterAndSortMediaOptions(i,e,a,o,l)}createLevel(t){const e=new le(t),s=t.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(t.message),e.supportedResult=Qt(t,[])}return e}isAudioSupported(t){return Ut(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Ut(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,s,i,r){let n=[],a=[],o=t;if((s||i)&&r&&(o=o.filter((({videoCodec:t,videoRange:e,width:s,height:i})=>{return(!!t||!(!s||!i))&&(!!(r=e)&&se.indexOf(r)>-1);var r}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){let t="no level with compatible codecs found in manifest",s=t;e.levels.length&&(s=`one or more CODECS in variant not supported: ${ce(e.levels.map((t=>t.attrs.CODECS)).filter(((t,e,s)=>s.indexOf(t)===e)))}`,this.warn(s),t+=` (${s})`);const i=new Error(t);this.hls.trigger(E.ERROR,{type:v.MEDIA_ERROR,details:y.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:i,reason:s})}}));e.audioTracks&&(n=e.audioTracks.filter((t=>!t.audioCodec||this.isAudioSupported(t.audioCodec))),Uo(n)),e.subtitles&&(a=e.subtitles,Uo(a));const l=o.slice(0);o.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&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 se.indexOf(t.videoRange)-se.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=Gt(t.videoCodec),i=Gt(e.videoCodec);if(s!==i)return i-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=Kt(t.codecSet),i=Kt(e.codecSet);if(s!==i)return i-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;t<l.length;t++)if(l[t].pathwayId===o[0].pathwayId){h=l[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===h){var d;this._firstLevel=t;const e=h.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${e}`),void 0===(null==(d=this.hls.userConfig)?void 0:d.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const c=r&&!i,u=this.hls.config,f=!(!u.audioStreamController||!u.audioTrackController),g={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:f&&!c&&n.some((t=>!!t.url))};this.hls.trigger(E.MANIFEST_PARSED,g)}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 s=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(E.ERROR,{type:v.OTHER_ERROR,details:y.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:s,reason:s.message}),i)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&i&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,l);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(),s=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=s}}onError(t,e){!e.fatal&&e.context&&e.context.type===S&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===R){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),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(i,e,t)}else null!=(s=e.deliveryDirectives)&&s.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 s=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(E.LEVEL_LOADING,{url:s,level:i,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 s=this._levels.filter(((e,s)=>s!==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)));mi(s),this._levels=s,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 i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(E.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Uo(t){const e={};t.forEach((t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++}))}function Bo(){return self.SourceBuffer||self.WebKitSourceBuffer}function $o(){if(!$())return!1;const t=Bo();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class Go extends Oi{constructor(t,e,s){super(t,e,s,"stream-controller",R),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,e=t?t.currentTime:null;if(null===e||!g(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const s=this.getFwdBufferInfoAtPos(t,e,R,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.LEVEL_LOADING,this.onLevelLoading,this),t.on(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(E.BUFFER_CREATED,this.onBufferCreated,this),t.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(E.BUFFER_CREATED,this.onBufferCreated,this),t.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this._hasEnoughToStart=!!e}s>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s),this.state=Ai,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=Li}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case xi:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=Ai;break}if(this.hls.nextLoadLevel!==this.level){this.state=Ai;break}break}case Ii:{var t;const e=self.performance.now(),s=this.retryDate;if(!s||e>=s||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,s=null==t?void 0:t[e];this.resetStartWhenNotLoaded(s||null),this.state=Ai}}}this.state===Ai&&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:s,media:i}=this;if(null===e||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger(E.BUFFER_EOS,t),void(this.state=Pi)}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 l=n.details;if(!l||this.state===xi||this.waitForLive(n))return this.level=r,this.state=xi,void(this.startFragRequested=!1);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&rt(u)&&this.fragmentTracker.getState(u)!==Ge){var f;const t=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,e=l.fragments[t-1];e&&u.cc===e.cc&&(u=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const t=this.audioOnly&&!this.altAudio?tt:et,e=(t===et?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,R)}u=this.getNextFragmentLoopLoading(u,l,a,R,d)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i===Ue||i===$e?rt(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,s):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,R)}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 s;const i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.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],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(e.currentTime+s);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,i=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,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 Ri:case bi:case Ii:case ki:case Di:this.state=Ai}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;Ta(s,"playing",this.onMediaPlaying),Ta(s,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:s}=this;s&&(Sa(s,"playing",this.onMediaPlaying),Sa(s,"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(E.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 s=!1,i=!1;e.levels.forEach((t=>{const e=t.audioCodec;e&&(s=s||-1!==e.indexOf("mp4a.40.2"),i=i||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&i&&!function(){var t;const e=Bo();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:s}=this;if(!s||this.state!==Ai)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=xi)}onLevelLoaded(t,e){var s;const{levels:i,startFragRequested:r}=this,n=e.level,a=e.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=e.levelInfo,h=this.fragCurrent;!h||this.state!==bi&&this.state!==Ii||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,d),this.hls.trigger(E.LEVEL_UPDATED,{details:a,level:n}),this.state===xi){if(this.waitForCdnTuneIn(a))return;this.state=Ai}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),s.currentTime=i))}}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=s.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new cn(this.hls,R,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new rs(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,m,p)}onAudioTrackSwitching(t,e){const s=this.hls,i=2===this.altAudio;if(Ee(e.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;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(i)return this.fragmentTracker.removeAllFragments(),s.once(E.BUFFER_FLUSHED,(()=>{var t;null==(t=this.hls)||t.trigger(E.AUDIO_TRACK_SWITCHED,e)})),void s.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(E.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=Ee(e.url,this.hls);if(s){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=s?2:0,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(r=t,i=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e,r=s.type===R;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Di&&(this.state=Ai));const t=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),rt(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&as.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var s;if(e.fatal)this.state=Ci;else switch(e.details){case y.FRAG_GAP:case y.FRAG_PARSING_ERROR:case y.FRAG_DECRYPT_ERROR:case y.FRAG_LOAD_ERROR:case y.FRAG_LOAD_TIMEOUT:case y.KEY_LOAD_ERROR:case y.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(R,e);break;case y.LEVEL_LOAD_ERROR:case y.LEVEL_LOAD_TIMEOUT:case y.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==xi||(null==(s=e.context)?void 0:s.type)!==S||(this.state=Ai);break;case y.BUFFER_ADD_CODEC_ERROR:case y.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.resetLoadingState();break;case y.BUFFER_FULL_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case y.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=Ai,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==tt||!this.altAudio){const t=(e===et?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,R),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 s=this.startPosition;if(s>=0&&e<s){if(t.seeking)return void this.log(`could not seek to ${s}, already seeking at ${e}`);const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=as.getBuffered(t),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);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`),s+=o,this.startPosition=s),e<s&&(this.log(`seek to target start position ${s} from current time ${e} buffer start ${a}`),t.currentTime=s)}}_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:s}=this,i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=Ai,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(E.FRAG_LOADED,t),i.bitrateTest=!1}))}_handleTransmuxComplete(t){var e;const s=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:d,text:c,id3:u,initSegment:f}=r,{details:m}=h,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=ki,f){if(null!=f&&f.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,f.tracks,t,n),i.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:f.tracks})}const t=f.initPTS,e=f.timescale;g(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},i.trigger(E.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:e}))}if(d&&m){p&&"audiovideo"===d.type&&this.logMuxedErr(o);const t=m.fragments[o.sn-1-m.startSN],e=o.sn===m.startSN,s=!t||o.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:i,startDTS:r,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:t,endPTS:i,startDTS:r,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!s&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<l-this.config.maxBufferHole&&!s)return void this.backtrack(o);s&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,i,o.start,a,!0)}else e&&t-(m.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,t,i,r,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,e||s)}else{if(!e&&!s)return void this.backtrack(o);o.gap=!0}}if(p){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=p;l&&(l.elementaryStreams[tt]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(tt,t,e,s,i),this.bufferFragmentData(p,o,l,n)}if(m&&null!=u&&null!=(e=u.samples)&&e.length){const t={id:s,frag:o,details:m,samples:u.samples};i.trigger(E.FRAG_PARSING_METADATA,t)}if(m&&c){const t={id:s,frag:o,details:m,samples:c.samples};i.trigger(E.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${rt(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,s,i){if(this.state!==ki)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=e;if(r){let s=jt(r.codec,t.audioCodec);"mp4a"===s&&(s="mp4a.40.5");const i=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===i.indexOf("firefox")&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&-1!==i.indexOf("android")&&"audio/mpeg"!==r.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),t.audioCodec&&t.audioCodec!==s&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${s}"`),r.levelCodec=s,r.id=R,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${t.audioCodec||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=R;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){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||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(E.BUFFER_CODECS,e),!this.hls)return;o.forEach((t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:t,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,R)}get maxBufferLength(){const{levels:t,level:e}=this,s=null==t?void 0:t[e];return s?this.getMaxBufferLength(s.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=Ai}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(as.isBuffered(t,s)?e=this.getAppendedFrag(s):as.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s||(this.fragPlaying=e,this.hls.trigger(E.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(E.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return g(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(g(e)){const t=this.getLevelDetails(),s=this.currentFrag||(t?Se(null,t.fragments,e):null);if(s){const t=s.programDateTime;if(null!==t){const i=t+1e3*(e-s.start);return new Date(i)}}}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 Ko{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=y.KEY_LOAD_ERROR,s,i,r){return new ss({type:v.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:s,networkDetails:i})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=t;for(let t=0;t<e.length;t++){const r=e[t];if(i<=r.cc&&("initSegment"===s||"initSegment"===r.sn||s<r.sn)){this.emeController.selectKeySystemFormat(r).then((t=>{r.setKeyFormat(t)}));break}}}}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 s,i;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const s=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,y.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,y.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(s=a)&&s.decryptdata.key)return r.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(i=a)&&i.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(r.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,y.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(s);if(e)return(t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,s)))).catch((e=>{throw t.keyLoadPromise=null,e}))}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,i=new(0,s.loader)(s);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise(((r,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,s,i)=>{const{frag:a,keyInfo:o,url:l}=s;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,y.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(t,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(e,y.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,w({url:a.url,data:void 0},t)))},onTimeout:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,y.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,y.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,h)}))}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function Ho(t){const{type:e}=t;switch(e){case L:return b;case A:return I;default:return R}}function Vo(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}class Yo{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(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.LEVEL_LOADING,this.onLevelLoading,this),t.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.LEVEL_LOADING,this.onLevelLoading,this),t.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=new(s||i)(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:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:T,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:S,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:L,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:A,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const s=this.loaders[S];if(s){const t=s.context;t&&!e.levels.some((e=>e===t.levelOrTrack))&&(s.abort(),delete this.loaders[S])}}load(t){var e;const s=this.hls.config;let i,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,s=r.context;if(s&&s.levelOrTrack===t.levelOrTrack&&(s.url===t.url||s.deliveryDirectives&&!t.deliveryDirectives))return void(s.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${s.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(i=t.type===T?s.manifestLoadPolicy.default:P({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),g(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===S&&null!==t.level?e=this.hls.levels[t.level].details:t.type===L&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===A&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);i=P({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),Ws.isMediaPlaylist(n)||s.type!==T?this.handleTrackOrLevelPlaylist(t,e,s,i||null,r):this.handleMasterPlaylist(t,e,s,i)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),i||null,e)},onError:(t,e,s,i)=>{this.handleNetworkError(e,s,!1,t,i)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};r.load(t,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:s}=this.hls;(t||s)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,s,i){const r=this.hls,n=t.data,a=Vo(t,s),o=Ws.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,i,e);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Ws.parseMasterPlaylistMedia(n,a,o);if(g.length){g.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"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new gs({}),bitrate:0,url:""}))}r.trigger(E.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:i,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(t,e,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=Vo(t,s),d=g(o)?o:g(a)?a:0,c=Ho(s),u=Ws.parseLevelPlaylist(t.data,h,d,c,0,this.variableList);if(l===T){const t={attrs:new gs({}),bitrate:0,details:u,name:"",url:h};u.requestScheduled=e.loading.start+ci(u,0),n.trigger(E.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:h,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,t,e,s,i,r)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:y.MANIFEST_PARSING_ERROR,fatal:e.type===T,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===S?n+=`: ${t.level} id: ${t.id}`:t.type!==L&&t.type!==A||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=y.UNKNOWN,l=!1;const h=this.getInternalLoader(t);switch(t.type){case T:o=s?y.MANIFEST_LOAD_TIMEOUT:y.MANIFEST_LOAD_ERROR,l=!0;break;case S:o=s?y.LEVEL_LOAD_TIMEOUT:y.LEVEL_LOAD_ERROR,l=!1;break;case L:o=s?y.AUDIO_TRACK_LOAD_TIMEOUT:y.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case A:o=s?y.SUBTITLE_TRACK_LOAD_TIMEOUT:y.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(t.type);const d={type:v.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:r};if(i){const s=(null==e?void 0:e.url)||t.url;d.response=w({url:s,data:void 0},i)}this.hls.trigger(E.ERROR,d)}handlePlaylistLoaded(t,e,s,i,r,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:c}=i,u=Vo(e,i),f=Ho(i),g="number"==typeof i.level&&f===R?l:void 0;if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:y.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:n,reason:n.message,response:e,context:i,level:g,parent:f,networkDetails:r,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const m=t.playlistParsingError;if(m){if(this.hls.logger.warn(m),!a.config.ignorePlaylistParsingErrors)return void a.trigger(E.ERROR,{type:v.NETWORK_ERROR,details:y.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:e,context:i,level:g,parent:f,networkDetails:r,stats:s});t.playlistParsingError=null}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case T:case S:a.trigger(E.LEVEL_LOADED,{details:t,levelInfo:i.levelOrTrack||a.levels[0],level:g||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:c,withoutMultiVariant:o===T});break;case L:a.trigger(E.AUDIO_TRACK_LOADED,{details:t,track:i.levelOrTrack,id:h||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:c});break;case A:a.trigger(E.SUBTITLE_TRACK_LOADED,{details:t,track:i.levelOrTrack,id:h||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:c})}}}class jo{static get version(){return Gi}static isMSESupported(){return $o()}static isSupported(){return function(){if(!$o())return!1;const t=$();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($t(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported($t(e,"audio")))))}()}static getMediaSource(){return $()}static get Events(){return E}static get MetadataSchema(){return cr}static get ErrorTypes(){return v}static get ErrorDetails(){return y}static get DefaultConfig(){return jo.defaultConfig?jo.defaultConfig:Io}static set DefaultConfig(t){jo.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 $i,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,s){const i=F();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach((e=>{i[e]=N(e,t,s)}));try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.2`)}catch(t){return F()}r.forEach((e=>{U[e]=N(e,t)}))}else P(U,i);return i}(t.debug||!1,"Hls instance",t.assetPlayerId),s=this.config=function(t,e,s){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 i=_o(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((s=>{const r=`${t}Loading${s}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=i[n].default;switch(e[n]={default:t},s){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&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${ce(e[n])}`)})),w(w({},i),e)}(jo.DefaultConfig,t,e);this.userConfig=t,s.progressive&&ko(s,e);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=s,l=new a(this),h=this.abrController=new i(this),d=new Ke(this),c=s.interstitialsController,u=c?this.interstitialsController=new c(this,jo):null,f=this.bufferController=new r(this,d),g=this.capLevelController=new n(this),m=new o(this),p=new Yo(this),v=s.contentSteeringController,y=v?new v(this):null,T=this.levelController=new No(this,y),S=new Mo(this),L=new Ko(this.config),A=this.streamController=new Go(this,d,L),R=this.gapController=new Do(this,d);g.setStreamController(A),m.setStreamController(A);const b=[p,T,A];u&&b.splice(1,0,u),y&&b.splice(1,0,y),this.networkControllers=b;const I=[h,f,R,g,m,S,d];this.audioTrackController=this.createController(s.audioTrackController,b);const _=s.audioStreamController;_&&b.push(this.audioStreamController=new _(this,d,L)),this.subtitleTrackController=this.createController(s.subtitleTrackController,b);const k=s.subtitleStreamController;k&&b.push(this.subtititleStreamController=new k(this,d,L)),this.createController(s.timelineController,I),L.emeController=this.emeController=this.createController(s.emeController,I),this.cmcdController=this.createController(s.cmcdController,I),this.latencyController=this.createController(Fo,I),this.coreComponents=I,b.push(l);const D=l.onErrorOut;"function"==typeof D&&this.on(E.ERROR,D,l),this.on(E.MANIFEST_LOADED,p.onManifestLoaded,p)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,i){this._emitter.off(t,e,s,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}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 s=t===E.ERROR;this.trigger(E.ERROR,{type:v.OTHER_ERROR,details:y.INTERNAL_EXCEPTION,fatal:s,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(E.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(E.ERROR,{type:v.OTHER_ERROR,details:y.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,s=e?t.media:t,i=e?t:{media:s};this._media=s,this.trigger(E.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,s=this._url,i=this._url=J.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),e&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(E.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 s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,e),this.started&&this.networkControllers);s++);}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={[R]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[b]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[I]=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 s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|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 ee.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 s=t.length;for(let i=0;i<s;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let e=i;e--;){const i=t[e].attrs["HDCP-LEVEL"];if(i&&i<=s)return e}return i}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 te(t,fe(e),navigator.mediaCapabilities)}}jo.defaultConfig=void 0;var Wo=t.Utils.now,qo=t.Utils.listContainsIgnoreCase;t.Events.register("PLAYBACK_FRAGMENT_CHANGED"),t.Events.register("PLAYBACK_FRAGMENT_PARSING_METADATA");var Xo=function(e){function r(){var t;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r);for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return(t=s(this,r,[].concat(i))).options.hlsPlayback=h(h({},t.defaultOptions),t.options.hlsPlayback),t._timeUpdateThrottleDelay=200,t._timeUpdateFiringRate=.2,t._durationChangeMinOffset=.5,t._setInitialState(),t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&d(t,e)}(r,e),n=r,o=[{key:"HLSJS",get:function(){return jo}}],(a=[{key:"name",get:function(){return"hls"}},{key:"supportedVersion",get:function(){return{min:"0.11.5"}}},{key:"levels",get:function(){return this._levels||[]}},{key:"currentLevel",get:function(){return null===this._currentLevel||void 0===this._currentLevel?-1:this._currentLevel},set:function(e){this._currentLevel=e,this.trigger(t.Events.PLAYBACK_LEVEL_SWITCH_START),this.options.playback.hlsUseNextLevel?this._hls.nextLevel=this._currentLevel:this._hls.currentLevel=this._currentLevel}},{key:"isReady",get:function(){return this._isReadyState}},{key:"latency",get:function(){return this._hls.latency}},{key:"liveSyncPosition",get:function(){return this._hls.liveSyncPosition}},{key:"currentProgramDateTime",get:function(){return this._hls.playingDate}},{key:"_startTime",get:function(){return this._playbackType===t.Playback.LIVE&&"EVENT"!==this._playlistType?this._extrapolatedStartTime:this._playableRegionStartTime}},{key:"_now",get:function(){return Wo()}},{key:"_extrapolatedStartTime",get:function(){if(!this._localStartTimeCorrelation)return this._playableRegionStartTime;var t=this._localStartTimeCorrelation,e=this._now-t.local,s=(t.remote+e)/1e3;return Math.min(s,this._playableRegionStartTime+this._extrapolatedWindowDuration)}},{key:"_extrapolatedEndTime",get:function(){var t=this._playableRegionStartTime+this._playableRegionDuration;if(!this._localEndTimeCorrelation)return t;var e=this._localEndTimeCorrelation,s=this._now-e.local,i=(e.remote+s)/1e3;return Math.max(t-this._extrapolatedWindowDuration,Math.min(i,t))}},{key:"_duration",get:function(){return this._extrapolatedEndTime-this._startTime}},{key:"_extrapolatedWindowDuration",get:function(){return null===this._segmentTargetDuration?0:this._extrapolatedWindowNumSegments*this._segmentTargetDuration}},{key:"bandwidthEstimate",get:function(){return this._hls&&this._hls.bandwidthEstimate}},{key:"defaultOptions",get:function(){return{preload:!0}}},{key:"customListeners",get:function(){return this.options.hlsPlayback&&this.options.hlsPlayback.customListeners||[]}},{key:"sourceMedia",get:function(){return this.options.src}},{key:"currentTimestamp",get:function(){return this._currentFragment?(this._currentFragment.programDateTime+1e3*(this.el.currentTime-this._currentFragment.start))/1e3:null}},{key:"_setInitialState",value:function(){this._minDvrSize=void 0===this.options.hlsMinimumDvrSize?60:this.options.hlsMinimumDvrSize,this._extrapolatedWindowNumSegments=this.options.playback&&void 0!==this.options.playback.extrapolatedWindowNumSegments?this.options.playback.extrapolatedWindowNumSegments:2,this._playbackType=t.Playback.VOD,this._lastTimeUpdate={current:0,total:0,firstFragDateTime:0},this._lastTimeUpdateFiredTime=0,this._lastDuration=null,this._playableRegionStartTime=0,this._localStartTimeCorrelation=null,this._localEndTimeCorrelation=null,this._playableRegionDuration=0,this._programDateTime=0,this._durationExcludesAfterLiveSyncPoint=!1,this._segmentTargetDuration=null,this._playlistType=null,this._recoverAttemptsRemaining=this.options.hlsRecoverAttempts||16}},{key:"_setup",value:function(){this._destroyHLSInstance(),this._createHLSInstance(),this._listenHLSEvents(),this._attachHLSMedia()}},{key:"_destroyHLSInstance",value:function(){this._hls&&(this._manifestLoading=!1,this._ccIsSetup=!1,this._ccTracksUpdated=!1,this._setInitialState(),this._hls.destroy(),this._hls=null)}},{key:"_createHLSInstance",value:function(){var t=h({},this.options.playback.hlsjsConfig);this._hls=new jo(t)}},{key:"_attachHLSMedia",value:function(){this._hls&&this._hls.attachMedia(this.el)}},{key:"_listenHLSEvents",value:function(){var t=this;this._hls&&(this._hls.once(jo.Events.MEDIA_ATTACHED,(function(){t.options.hlsPlayback.preload&&t._hls.loadSource(t.options.src)})),this._hls.on(jo.Events.MANIFEST_LOADING,(function(){return t._manifestLoading=!0})),this._hls.on(jo.Events.LEVEL_LOADED,(function(e,s){return t._updatePlaybackType(e,s)})),this._hls.on(jo.Events.LEVEL_UPDATED,(function(e,s){return t._onLevelUpdated(e,s)})),this._hls.on(jo.Events.LEVEL_SWITCHED,(function(e,s){return t._onLevelSwitch(e,s)})),this._hls.on(jo.Events.FRAG_CHANGED,(function(e,s){return t._onFragmentChanged(e,s)})),this._hls.on(jo.Events.FRAG_LOADED,(function(e,s){return t._onFragmentLoaded(e,s)})),this._hls.on(jo.Events.FRAG_BUFFERED,(function(e,s){return t._onFragmentBuffered(e,s)})),this._hls.on(jo.Events.FRAG_PARSING_METADATA,(function(e,s){return t._onFragmentParsingMetadata(e,s)})),this._hls.on(jo.Events.ERROR,(function(e,s){return t._onHLSJSError(e,s)})),this._hls.on(jo.Events.SUBTITLE_TRACK_LOADED,(function(e,s){return t._onSubtitleLoaded(e,s)})),this._hls.on(jo.Events.SUBTITLE_TRACKS_UPDATED,(function(){return t._ccTracksUpdated=!0})),this.bindCustomListeners())}},{key:"bindCustomListeners",value:function(){var t=this;this.customListeners.forEach((function(e){var s=e.eventName,i=e.once?"once":"on";s&&t._hls["".concat(i)](s,e.callback)}))}},{key:"unbindCustomListeners",value:function(){var t=this;this.customListeners.forEach((function(e){var s=e.eventName;s&&t._hls.off(s,e.callback)}))}},{key:"_onFragmentParsingMetadata",value:function(e,s){this.trigger(t.Events.Custom.PLAYBACK_FRAGMENT_PARSING_METADATA,{evt:e,data:s})}},{key:"render",value:function(){return this._ready(),c(r,"render",this,3)([])}},{key:"_ready",value:function(){this._isReadyState||(!this._hls&&this._setup(),this._isReadyState=!0,this.trigger(t.Events.PLAYBACK_READY,this.name))}},{key:"_recover",value:function(e,s,i){if(this._recoveredDecodingError)if(this._recoveredAudioCodecError){t.Log.error("hlsjs: failed to recover",{evt:e,data:s}),i.level=t.PlayerError.Levels.FATAL;var r=this.createError(i);this.trigger(t.Events.PLAYBACK_ERROR,r),this.stop()}else this._recoveredAudioCodecError=!0,this._hls.swapAudioCodec(),this._hls.recoverMediaError(),this.play();else this._recoveredDecodingError=!0,this._hls.recoverMediaError(),this.play()}},{key:"_setupSrc",value:function(t){}},{key:"_startTimeUpdateTimer",value:function(){var t=this;this._timeUpdateTimer||(this._timeUpdateTimer=setInterval((function(){t._onDurationChange(),t._onTimeUpdate()}),100))}},{key:"_stopTimeUpdateTimer",value:function(){this._timeUpdateTimer&&(clearInterval(this._timeUpdateTimer),this._timeUpdateTimer=null)}},{key:"getProgramDateTime",value:function(){return this._programDateTime}},{key:"getDuration",value:function(){return this._duration}},{key:"getCurrentTime",value:function(){return Math.max(0,this.el.currentTime-this._startTime)}},{key:"getStartTimeOffset",value:function(){return this._startTime}},{key:"seekPercentage",value:function(t){var e=t>0?this._duration*(t/100):this._duration;this.seek(e)}},{key:"seek",value:function(e){e<0&&(t.Log.warn("Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point."),e=this.getDuration()),e+=this._startTime,this.el.currentTime=e}},{key:"seekToLivePoint",value:function(){this.seek(this.getDuration())}},{key:"_updateSettings",value:function(){this._playbackType===t.Playback.VOD?this.settings.left=["playpause","position","duration"]:this.dvrEnabled?this.settings.left=["playpause"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(t.Events.PLAYBACK_SETTINGSUPDATE)}},{key:"_onHLSJSError",value:function(e,s){var i,r={code:"".concat(s.type,"_").concat(s.details),description:"".concat(this.name," error: type: ").concat(s.type,", details: ").concat(s.details),raw:s};if(s.response&&(r.description+=", response: ".concat(JSON.stringify(s.response))),s.fatal)if(this._recoverAttemptsRemaining>0)switch(this._recoverAttemptsRemaining-=1,s.type){case jo.ErrorTypes.NETWORK_ERROR:switch(s.details){case jo.ErrorDetails.MANIFEST_LOAD_ERROR:case jo.ErrorDetails.MANIFEST_LOAD_TIMEOUT:case jo.ErrorDetails.MANIFEST_PARSING_ERROR:case jo.ErrorDetails.LEVEL_LOAD_ERROR:case jo.ErrorDetails.LEVEL_LOAD_TIMEOUT:t.Log.error("hlsjs: unrecoverable network fatal error.",{evt:e,data:s}),i=this.createError(r),this.trigger(t.Events.PLAYBACK_ERROR,i),this.stop();break;default:t.Log.warn("hlsjs: trying to recover from network error.",{evt:e,data:s}),r.level=t.PlayerError.Levels.WARN,this._hls.startLoad()}break;case jo.ErrorTypes.MEDIA_ERROR:t.Log.warn("hlsjs: trying to recover from media error.",{evt:e,data:s}),r.level=t.PlayerError.Levels.WARN,this._recover(e,s,r);break;default:t.Log.error("hlsjs: could not recover from error.",{evt:e,data:s}),i=this.createError(r),this.trigger(t.Events.PLAYBACK_ERROR,i),this.stop()}else t.Log.error("hlsjs: could not recover from error after maximum number of attempts.",{evt:e,data:s}),i=this.createError(r),this.trigger(t.Events.PLAYBACK_ERROR,i),this.stop();else{if(this.options.playback.triggerFatalErrorOnResourceDenied&&this._keyIsDenied(s))return t.Log.error("hlsjs: could not load decrypt key.",{evt:e,data:s}),i=this.createError(r),this.trigger(t.Events.PLAYBACK_ERROR,i),void this.stop();r.level=t.PlayerError.Levels.WARN,t.Log.warn("hlsjs: non-fatal error occurred",{evt:e,data:s})}}},{key:"_keyIsDenied",value:function(t){return t.type===jo.ErrorTypes.NETWORK_ERROR&&t.details===jo.ErrorDetails.KEY_LOAD_ERROR&&t.response&&t.response.code>=400}},{key:"_onTimeUpdate",value:function(){var e={current:this.getCurrentTime(),total:this.getDuration(),firstFragDateTime:this.getProgramDateTime()};this._shouldThrottleTimeUpdate(e)||(this._lastTimeUpdate=e,this._lastTimeUpdateFiredTime=this._now,this.trigger(t.Events.PLAYBACK_TIMEUPDATE,e,this.name))}},{key:"_shouldThrottleTimeUpdate",value:function(t){var e=Math.abs(t.current-this._lastTimeUpdate.current)<this._timeUpdateFiringRate,s=Math.abs(t.total-this._lastTimeUpdate.total)<this._durationChangeMinOffset,i=t.firstFragDateTime===this._lastTimeUpdate.firstFragDateTime,r=e&&s&&i,n=this._now-this._lastTimeUpdateFiredTime<this._timeUpdateThrottleDelay;return r&&n}},{key:"_onDurationChange",value:function(){var t=this.getDuration();Math.abs(this._lastDuration-t)<this._durationChangeMinOffset||(this._lastDuration=t,c(r,"_onDurationChange",this,3)([]))}},{key:"_onProgress",value:function(){if(this.el.buffered.length){for(var e=[],s=0,i=0;i<this.el.buffered.length;i++)e=[].concat(u(e),[{start:Math.max(0,this.el.buffered.start(i)-this._playableRegionStartTime),end:Math.max(0,this.el.buffered.end(i)-this._playableRegionStartTime)}]),this.el.currentTime>=e[i].start&&this.el.currentTime<=e[i].end&&(s=i);var r={start:e[s].start,current:e[s].end,total:this.getDuration()};this.trigger(t.Events.PLAYBACK_PROGRESS,r,e)}}},{key:"load",value:function(t){this._stopTimeUpdateTimer(),this.options.src=t,this._setup()}},{key:"play",value:function(){!this._hls&&this._setup(),!this._manifestLoading&&!this.options.hlsPlayback.preload&&this._hls.loadSource(this.options.src),c(r,"play",this,3)([]),this._startTimeUpdateTimer()}},{key:"pause",value:function(){this._hls&&this.el.pause()}},{key:"stop",value:function(){this._stopTimeUpdateTimer(),this._hls&&c(r,"stop",this,3)([]),this._destroyHLSInstance()}},{key:"destroy",value:function(){this._stopTimeUpdateTimer(),this._destroyHLSInstance(),c(r,"destroy",this,3)([])}},{key:"_updatePlaybackType",value:function(e,s){this._playbackType=s.details.live?t.Playback.LIVE:t.Playback.VOD,this._onLevelUpdated(e,s),this._ccTracksUpdated&&this._playbackType===t.Playback.LIVE&&this.hasClosedCaptionsTracks&&this._onSubtitleLoaded()}},{key:"_fillLevels",value:function(){this._levels=this._hls.levels.map((function(t,e){return{id:e,level:t,label:"".concat(t.bitrate/1e3,"Kbps")}})),this.trigger(t.Events.PLAYBACK_LEVELS_AVAILABLE,this._levels)}},{key:"_onLevelUpdated",value:function(e,s){this._segmentTargetDuration=s.details.targetduration,this._playlistType=s.details.type||null;var i=!1,r=!1,n=s.details.fragments,a=this._playableRegionStartTime,o=this._playableRegionDuration;if(0!==n.length){if(n[0].rawProgramDateTime&&(this._programDateTime=n[0].rawProgramDateTime),this._playableRegionStartTime!==n[0].start&&(i=!0,this._playableRegionStartTime=n[0].start),i)if(this._localStartTimeCorrelation){var l=this._localStartTimeCorrelation,h=this._now-l.local,d=(l.remote+h)/1e3;d<n[0].start?this._localStartTimeCorrelation={local:this._now,remote:1e3*n[0].start}:d>a+this._extrapolatedWindowDuration&&(this._localStartTimeCorrelation={local:this._now,remote:1e3*Math.max(n[0].start,a+this._extrapolatedWindowDuration)})}else this._localStartTimeCorrelation={local:this._now,remote:1e3*(n[0].start+this._extrapolatedWindowDuration/2)};var c=s.details.totalduration;if(this._playbackType===t.Playback.LIVE){var u=s.details.targetduration*((this.options.playback.hlsjsConfig||{}).liveSyncDurationCount||jo.DefaultConfig.liveSyncDurationCount);u<=c?(c-=u,this._durationExcludesAfterLiveSyncPoint=!0):this._durationExcludesAfterLiveSyncPoint=!1}c!==this._playableRegionDuration&&(r=!0,this._playableRegionDuration=c);var f=n[0].start+c,g=a+o;if(f!==g)if(this._localEndTimeCorrelation){var m=this._localEndTimeCorrelation,p=this._now-m.local,v=(m.remote+p)/1e3;v>f?this._localEndTimeCorrelation={local:this._now,remote:1e3*f}:v<f-this._extrapolatedWindowDuration?this._localEndTimeCorrelation={local:this._now,remote:1e3*(f-this._extrapolatedWindowDuration)}:v>g&&(this._localEndTimeCorrelation={local:this._now,remote:1e3*g})}else this._localEndTimeCorrelation={local:this._now,remote:1e3*f};r&&this._onDurationChange(),i&&this._onProgress()}}},{key:"_onFragmentChanged",value:function(e,s){this._currentFragment=s.frag,this.trigger(t.Events.Custom.PLAYBACK_FRAGMENT_CHANGED,s)}},{key:"_onFragmentLoaded",value:function(e,s){this.trigger(t.Events.PLAYBACK_FRAGMENT_LOADED,s)}},{key:"_onFragmentBuffered",value:function(e,s){this.trigger(t.Events.PLAYBACK_FRAGMENT_BUFFERED,s)}},{key:"_onSubtitleLoaded",value:function(){if(!this._ccIsSetup){this.trigger(t.Events.PLAYBACK_SUBTITLE_AVAILABLE);var e=this._playbackType===t.Playback.LIVE?-1:this.closedCaptionsTrackId;this.closedCaptionsTrackId=e,this._ccIsSetup=!0}}},{key:"_onLevelSwitch",value:function(e,s){this.levels.length||this._fillLevels(),this.trigger(t.Events.PLAYBACK_LEVEL_SWITCH_END),this.trigger(t.Events.PLAYBACK_LEVEL_SWITCH,s);var i=this._hls.levels[s.level];i&&(this.highDefinition=i.height>=720||i.bitrate/1e3>=2e3,this.trigger(t.Events.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinition),this.trigger(t.Events.PLAYBACK_BITRATE,{height:i.height,width:i.width,bandwidth:i.bitrate,bitrate:i.bitrate,level:s.level}))}},{key:"dvrEnabled",get:function(){return this._durationExcludesAfterLiveSyncPoint&&this._duration>=this._minDvrSize&&this.getPlaybackType()===t.Playback.LIVE}},{key:"getPlaybackType",value:function(){return this._playbackType}},{key:"isSeekEnabled",value:function(){return this._playbackType===t.Playback.VOD||this.dvrEnabled}}])&&i(n.prototype,a),o&&i(n,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,a,o}(t.HTML5Video);return Xo.canPlay=function(t,e){var s=t.split("?")[0].match(/.*\.(.*)$/)||[],i=s.length>1&&"m3u8"===s[1].toLowerCase()||qo(e,["application/vnd.apple.mpegurl","application/x-mpegURL"]);return!(!jo.isSupported()||!i)},Xo}(core);
1
+ var HlsjsPlayback=function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,s=Array(t);i<t;i++)s[i]=e[i];return s}function t(e,t,i){return t=n(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,a()?Reflect.construct(t,i||[],n(e).constructor):t.apply(e,i))}function i(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,d(s.key),s)}}function s(e,t,i){return(t=d(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function r(){return r="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,i){var s=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=n(e)););return e}(e,t);if(s){var r=Object.getOwnPropertyDescriptor(s,t);return r.get?r.get.call(arguments.length<3?e:i):r.value}},r.apply(null,arguments)}function n(e){return n=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},n(e)}function a(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(a=function(){return!!e})()}function o(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function l(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?o(Object(i),!0).forEach((function(t){s(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):o(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function h(e,t){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},h(e,t)}function u(e,t,i,s){var a=r(n(1&s?e.prototype:e),t,i);return 2&s&&"function"==typeof a?function(e){return a.apply(i,e)}:a}function c(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||function(t,i){if(t){if("string"==typeof t)return e(t,i);var s={}.toString.call(t).slice(8,-1);return"Object"===s&&t.constructor&&(s=t.constructor.name),"Map"===s||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?e(t,i):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t||"default");if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,s=Array(t);i<t;i++)s[i]=e[i];return s}function g(e,t,i){return t=T(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,b()?Reflect.construct(t,i||[],T(e).constructor):t.apply(e,i))}function p(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function m(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,P(s.key),s)}}function v(e,t,i){return t&&m(e.prototype,t),i&&m(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function y(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=w(e))||t){i&&(e=i);var s=0,r=function(){};return{s:r,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,a=!0,o=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){o=!0,n=e},f:function(){try{a||null==i.return||i.return()}finally{if(o)throw n}}}}function A(e,t,i){return(t=P(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function E(){return E="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,i){var s=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=T(e)););return e}(e,t);if(s){var r=Object.getOwnPropertyDescriptor(s,t);return r.get?r.get.call(arguments.length<3?e:i):r.value}},E.apply(null,arguments)}function T(e){return T=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},T(e)}function S(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&k(e,t)}function b(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(b=function(){return!!e})()}function L(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function _(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?L(Object(i),!0).forEach((function(t){A(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):L(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function k(e,t){return k=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},k(e,t)}function R(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var s,r,n,a,o=[],l=!0,h=!1;try{if(n=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;l=!1}else for(;!(l=(s=n.call(i)).done)&&(o.push(s.value),o.length!==t);l=!0);}catch(e){h=!0,r=e}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(h)throw r}}return o}}(e,t)||w(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function I(e,t,i,s){var r=E(T(e.prototype),t,i);return"function"==typeof r?function(e){return r.apply(i,e)}:r}function D(e){return function(e){if(Array.isArray(e))return f(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||w(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function P(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function C(e){return C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},C(e)}function w(e,t){if(e){if("string"==typeof e)return f(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?f(e,t):void 0}}function O(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var x=function(){var e,t,i,s,r,n,a=[],o=a.concat,l=a.filter,h=a.slice,u=window.document,c={},d={},f={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},g=/^\s*<(\w+|!)[^>]*>/,p=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,m=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,v=/^(?:body|html)$/i,y=/([A-Z])/g,A=["val","css","html","text","data","width","height","offset"],E=u.createElement("table"),T=u.createElement("tr"),S={tr:u.createElement("tbody"),tbody:E,thead:E,tfoot:E,td:T,th:T,"*":u.createElement("div")},b=/complete|loaded|interactive/,L=/^[\w-]*$/,_={},k=_.toString,R={},I=u.createElement("div"),D={tabindex:"tabIndex",readonly:"readOnly",for:"htmlFor",class:"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},P=Array.isArray||function(e){return e instanceof Array};function C(e){return null==e?String(e):_[k.call(e)]||"object"}function w(e){return"function"==C(e)}function O(e){return null!=e&&e==e.window}function x(e){return null!=e&&e.nodeType==e.DOCUMENT_NODE}function M(e){return"object"==C(e)}function F(e){return M(e)&&!O(e)&&Object.getPrototypeOf(e)==Object.prototype}function N(e){var t=!!e&&"length"in e&&e.length,s=i.type(e);return"function"!=s&&!O(e)&&("array"==s||0===t||"number"==typeof t&&t>0&&t-1 in e)}function U(e){return e.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function B(e){return e in d?d[e]:d[e]=new RegExp("(^|\\s)"+e+"(\\s|$)")}function $(e,t){return"number"!=typeof t||f[U(e)]?t:t+"px"}function G(e){return"children"in e?h.call(e.children):i.map(e.childNodes,(function(e){if(1==e.nodeType)return e}))}function K(e,t){var i,s=e?e.length:0;for(i=0;i<s;i++)this[i]=e[i];this.length=s,this.selector=t||""}function V(i,s,r){for(t in s)r&&(F(s[t])||P(s[t]))?(F(s[t])&&!F(i[t])&&(i[t]={}),P(s[t])&&!P(i[t])&&(i[t]=[]),V(i[t],s[t],r)):s[t]!==e&&(i[t]=s[t])}function H(e,t){return null==t?i(e):i(e).filter(t)}function Y(e,t,i,s){return w(t)?t.call(e,i,s):t}function j(e,t,i){null==i?e.removeAttribute(t):e.setAttribute(t,i)}function W(t,i){var s=t.className||"",r=s&&s.baseVal!==e;if(i===e)return r?s.baseVal:s;r?s.baseVal=i:t.className=i}function q(e){try{return e?"true"==e||"false"!=e&&("null"==e?null:+e+""==e?+e:/^[\[\{]/.test(e)?i.parseJSON(e):e):e}catch(t){return e}}function z(e,t){t(e);for(var i=0,s=e.childNodes.length;i<s;i++)z(e.childNodes[i],t)}return R.matches=function(e,t){if(!t||!e||1!==e.nodeType)return!1;var i=e.matches||e.webkitMatchesSelector||e.mozMatchesSelector||e.oMatchesSelector||e.matchesSelector;if(i)return i.call(e,t);var s,r=e.parentNode,n=!r;return n&&(r=I).appendChild(e),s=~R.qsa(r,t).indexOf(e),n&&I.removeChild(e),s},r=function(e){return e.replace(/-+(.)?/g,(function(e,t){return t?t.toUpperCase():""}))},n=function(e){return l.call(e,(function(t,i){return e.indexOf(t)==i}))},R.fragment=function(t,s,r){var n,a,o;return p.test(t)&&(n=i(u.createElement(RegExp.$1))),n||(t.replace&&(t=t.replace(m,"<$1></$2>")),s===e&&(s=g.test(t)&&RegExp.$1),s in S||(s="*"),(o=S[s]).innerHTML=""+t,n=i.each(h.call(o.childNodes),(function(){o.removeChild(this)}))),F(r)&&(a=i(n),i.each(r,(function(e,t){A.indexOf(e)>-1?a[e](t):a.attr(e,t)}))),n},R.Z=function(e,t){return new K(e,t)},R.isZ=function(e){return e instanceof R.Z},R.init=function(t,s){var r,n;if(!t)return R.Z();if("string"==typeof t)if("<"==(t=t.trim())[0]&&g.test(t))r=R.fragment(t,RegExp.$1,s),t=null;else{if(s!==e)return i(s).find(t);r=R.qsa(u,t)}else{if(w(t))return i(u).ready(t);if(R.isZ(t))return t;if(P(t))n=t,r=l.call(n,(function(e){return null!=e}));else if(M(t))r=[t],t=null;else if(g.test(t))r=R.fragment(t.trim(),RegExp.$1,s),t=null;else{if(s!==e)return i(s).find(t);r=R.qsa(u,t)}}return R.Z(r,t)},(i=function(e,t){return R.init(e,t)}).extend=function(e){var t,i=h.call(arguments,1);return"boolean"==typeof e&&(t=e,e=i.shift()),i.forEach((function(i){V(e,i,t)})),e},R.qsa=function(e,t){var i,s="#"==t[0],r=!s&&"."==t[0],n=s||r?t.slice(1):t,a=L.test(n);return e.getElementById&&a&&s?(i=e.getElementById(n))?[i]:[]:1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType?[]:h.call(a&&!s&&e.getElementsByClassName?r?e.getElementsByClassName(n):e.getElementsByTagName(t):e.querySelectorAll(t))},i.contains=u.documentElement.contains?function(e,t){return e!==t&&e.contains(t)}:function(e,t){for(;t&&(t=t.parentNode);)if(t===e)return!0;return!1},i.type=C,i.isFunction=w,i.isWindow=O,i.isArray=P,i.isPlainObject=F,i.isEmptyObject=function(e){var t;for(t in e)return!1;return!0},i.isNumeric=function(e){var t=Number(e),i=typeof e;return null!=e&&"boolean"!=i&&("string"!=i||e.length)&&!isNaN(t)&&isFinite(t)||!1},i.inArray=function(e,t,i){return a.indexOf.call(t,e,i)},i.camelCase=r,i.trim=function(e){return null==e?"":String.prototype.trim.call(e)},i.uuid=0,i.support={},i.expr={},i.noop=function(){},i.map=function(e,t){var s,r,n,a,o=[];if(N(e))for(r=0;r<e.length;r++)null!=(s=t(e[r],r))&&o.push(s);else for(n in e)null!=(s=t(e[n],n))&&o.push(s);return(a=o).length>0?i.fn.concat.apply([],a):a},i.each=function(e,t){var i,s;if(N(e)){for(i=0;i<e.length;i++)if(!1===t.call(e[i],i,e[i]))return e}else for(s in e)if(!1===t.call(e[s],s,e[s]))return e;return e},i.grep=function(e,t){return l.call(e,t)},window.JSON&&(i.parseJSON=JSON.parse),i.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),(function(e,t){_["[object "+t+"]"]=t.toLowerCase()})),i.fn={constructor:R.Z,length:0,forEach:a.forEach,reduce:a.reduce,push:a.push,sort:a.sort,splice:a.splice,indexOf:a.indexOf,concat:function(){var e,t,i=[];for(e=0;e<arguments.length;e++)t=arguments[e],i[e]=R.isZ(t)?t.toArray():t;return o.apply(R.isZ(this)?this.toArray():this,i)},map:function(e){return i(i.map(this,(function(t,i){return e.call(t,i,t)})))},slice:function(){return i(h.apply(this,arguments))},ready:function(e){return b.test(u.readyState)&&u.body?e(i):u.addEventListener("DOMContentLoaded",(function(){e(i)}),!1),this},get:function(t){return t===e?h.call(this):this[t>=0?t:t+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each((function(){null!=this.parentNode&&this.parentNode.removeChild(this)}))},each:function(e){return a.every.call(this,(function(t,i){return!1!==e.call(t,i,t)})),this},filter:function(e){return w(e)?this.not(this.not(e)):i(l.call(this,(function(t){return R.matches(t,e)})))},add:function(e,t){return i(n(this.concat(i(e,t))))},is:function(e){return this.length>0&&R.matches(this[0],e)},not:function(t){var s=[];if(w(t)&&t.call!==e)this.each((function(e){t.call(this,e)||s.push(this)}));else{var r="string"==typeof t?this.filter(t):N(t)&&w(t.item)?h.call(t):i(t);this.forEach((function(e){r.indexOf(e)<0&&s.push(e)}))}return i(s)},has:function(e){return this.filter((function(){return M(e)?i.contains(this,e):i(this).find(e).size()}))},eq:function(e){return-1===e?this.slice(e):this.slice(e,+e+1)},first:function(){var e=this[0];return e&&!M(e)?e:i(e)},last:function(){var e=this[this.length-1];return e&&!M(e)?e:i(e)},find:function(e){var t=this;return e?"object"==typeof e?i(e).filter((function(){var e=this;return a.some.call(t,(function(t){return i.contains(t,e)}))})):1==this.length?i(R.qsa(this[0],e)):this.map((function(){return R.qsa(this,e)})):i()},closest:function(e,t){var s=[],r="object"==typeof e&&i(e);return this.each((function(i,n){for(;n&&!(r?r.indexOf(n)>=0:R.matches(n,e));)n=n!==t&&!x(n)&&n.parentNode;n&&s.indexOf(n)<0&&s.push(n)})),i(s)},parents:function(e){for(var t=[],s=this;s.length>0;)s=i.map(s,(function(e){if((e=e.parentNode)&&!x(e)&&t.indexOf(e)<0)return t.push(e),e}));return H(t,e)},parent:function(e){return H(n(this.pluck("parentNode")),e)},children:function(e){return H(this.map((function(){return G(this)})),e)},contents:function(){return this.map((function(){return this.contentDocument||h.call(this.childNodes)}))},siblings:function(e){return H(this.map((function(e,t){return l.call(G(t.parentNode),(function(e){return e!==t}))})),e)},empty:function(){return this.each((function(){this.innerHTML=""}))},pluck:function(e){return i.map(this,(function(t){return t[e]}))},show:function(){return this.each((function(){var e,t,i;"none"==this.style.display&&(this.style.display=""),"none"==getComputedStyle(this,"").getPropertyValue("display")&&(this.style.display=(e=this.nodeName,c[e]||(t=u.createElement(e),u.body.appendChild(t),i=getComputedStyle(t,"").getPropertyValue("display"),t.parentNode.removeChild(t),"none"==i&&(i="block"),c[e]=i),c[e]))}))},replaceWith:function(e){return this.before(e).remove()},wrap:function(e){var t=w(e);if(this[0]&&!t)var s=i(e).get(0),r=s.parentNode||this.length>1;return this.each((function(n){i(this).wrapAll(t?e.call(this,n):r?s.cloneNode(!0):s)}))},wrapAll:function(e){if(this[0]){var t;for(i(this[0]).before(e=i(e));(t=e.children()).length;)e=t.first();i(e).append(this)}return this},wrapInner:function(e){var t=w(e);return this.each((function(s){var r=i(this),n=r.contents(),a=t?e.call(this,s):e;n.length?n.wrapAll(a):r.append(a)}))},unwrap:function(){return this.parent().each((function(){i(this).replaceWith(i(this).children())})),this},clone:function(){return this.map((function(){return this.cloneNode(!0)}))},hide:function(){return this.css("display","none")},toggle:function(t){return this.each((function(){var s=i(this);(t===e?"none"==s.css("display"):t)?s.show():s.hide()}))},prev:function(e){return i(this.pluck("previousElementSibling")).filter(e||"*")},next:function(e){return i(this.pluck("nextElementSibling")).filter(e||"*")},html:function(e){return 0 in arguments?this.each((function(t){var s=this.innerHTML;i(this).empty().append(Y(this,e,t,s))})):0 in this?this[0].innerHTML:null},text:function(e){return 0 in arguments?this.each((function(t){var i=Y(this,e,t,this.textContent);this.textContent=null==i?"":""+i})):0 in this?this.pluck("textContent").join(""):null},attr:function(i,s){var r;return"string"!=typeof i||1 in arguments?this.each((function(e){if(1===this.nodeType)if(M(i))for(t in i)j(this,t,i[t]);else j(this,i,Y(this,s,e,this.getAttribute(i)))})):0 in this&&1==this[0].nodeType&&null!=(r=this[0].getAttribute(i))?r:e},removeAttr:function(e){return this.each((function(){1===this.nodeType&&e.split(" ").forEach((function(e){j(this,e)}),this)}))},prop:function(e,t){return e=D[e]||e,1 in arguments?this.each((function(i){this[e]=Y(this,t,i,this[e])})):this[0]&&this[0][e]},removeProp:function(e){return e=D[e]||e,this.each((function(){delete this[e]}))},data:function(t,i){var s="data-"+t.replace(y,"-$1").toLowerCase(),r=1 in arguments?this.attr(s,i):this.attr(s);return null!==r?q(r):e},val:function(e){return 0 in arguments?(null==e&&(e=""),this.each((function(t){this.value=Y(this,e,t,this.value)}))):this[0]&&(this[0].multiple?i(this[0]).find("option").filter((function(){return this.selected})).pluck("value"):this[0].value)},offset:function(e){if(e)return this.each((function(t){var s=i(this),r=Y(this,e,t,s.offset()),n=s.offsetParent().offset(),a={top:r.top-n.top,left:r.left-n.left};"static"==s.css("position")&&(a.position="relative"),s.css(a)}));if(!this.length)return null;if(u.documentElement!==this[0]&&!i.contains(u.documentElement,this[0]))return{top:0,left:0};var t=this[0].getBoundingClientRect();return{left:t.left+window.pageXOffset,top:t.top+window.pageYOffset,width:Math.round(t.width),height:Math.round(t.height)}},css:function(e,s){if(arguments.length<2){var n=this[0];if("string"==typeof e){if(!n)return;return n.style[r(e)]||getComputedStyle(n,"").getPropertyValue(e)}if(P(e)){if(!n)return;var a={},o=getComputedStyle(n,"");return i.each(e,(function(e,t){a[t]=n.style[r(t)]||o.getPropertyValue(t)})),a}}var l="";if("string"==C(e))s||0===s?l=U(e)+":"+$(e,s):this.each((function(){this.style.removeProperty(U(e))}));else for(t in e)e[t]||0===e[t]?l+=U(t)+":"+$(t,e[t])+";":this.each((function(){this.style.removeProperty(U(t))}));return this.each((function(){this.style.cssText+=";"+l}))},index:function(e){return e?this.indexOf(i(e)[0]):this.parent().children().indexOf(this[0])},hasClass:function(e){return!!e&&a.some.call(this,(function(e){return this.test(W(e))}),B(e))},addClass:function(e){return e?this.each((function(t){if("className"in this){s=[];var r=W(this);Y(this,e,t,r).split(/\s+/g).forEach((function(e){i(this).hasClass(e)||s.push(e)}),this),s.length&&W(this,r+(r?" ":"")+s.join(" "))}})):this},removeClass:function(t){return this.each((function(i){if("className"in this){if(t===e)return W(this,"");s=W(this),Y(this,t,i,s).split(/\s+/g).forEach((function(e){s=s.replace(B(e)," ")})),W(this,s.trim())}}))},toggleClass:function(t,s){return t?this.each((function(r){var n=i(this);Y(this,t,r,W(this)).split(/\s+/g).forEach((function(t){(s===e?!n.hasClass(t):s)?n.addClass(t):n.removeClass(t)}))})):this},scrollTop:function(t){if(this.length){var i="scrollTop"in this[0];return t===e?i?this[0].scrollTop:this[0].pageYOffset:this.each(i?function(){this.scrollTop=t}:function(){this.scrollTo(this.scrollX,t)})}},scrollLeft:function(t){if(this.length){var i="scrollLeft"in this[0];return t===e?i?this[0].scrollLeft:this[0].pageXOffset:this.each(i?function(){this.scrollLeft=t}:function(){this.scrollTo(t,this.scrollY)})}},position:function(){if(this.length){var e=this[0],t=this.offsetParent(),s=this.offset(),r=v.test(t[0].nodeName)?{top:0,left:0}:t.offset();return s.top-=parseFloat(i(e).css("margin-top"))||0,s.left-=parseFloat(i(e).css("margin-left"))||0,r.top+=parseFloat(i(t[0]).css("border-top-width"))||0,r.left+=parseFloat(i(t[0]).css("border-left-width"))||0,{top:s.top-r.top,left:s.left-r.left}}},offsetParent:function(){return this.map((function(){for(var e=this.offsetParent||u.body;e&&!v.test(e.nodeName)&&"static"==i(e).css("position");)e=e.offsetParent;return e}))}},i.fn.detach=i.fn.remove,["width","height"].forEach((function(t){var s=t.replace(/./,(function(e){return e[0].toUpperCase()}));i.fn[t]=function(r){var n,a=this[0];return r===e?O(a)?a["inner"+s]:x(a)?a.documentElement["scroll"+s]:(n=this.offset())&&n[t]:this.each((function(e){(a=i(this)).css(t,Y(this,r,e,a[t]()))}))}})),["after","prepend","before","append"].forEach((function(t,s){var r=s%2;i.fn[t]=function(){var t,n,a=i.map(arguments,(function(s){var r=[];return"array"==(t=C(s))?(s.forEach((function(t){return t.nodeType!==e?r.push(t):i.zepto.isZ(t)?r=r.concat(t.get()):void(r=r.concat(R.fragment(t)))})),r):"object"==t||null==s?s:R.fragment(s)})),o=this.length>1;return a.length<1?this:this.each((function(e,t){n=r?t:t.parentNode,t=0==s?t.nextSibling:1==s?t.firstChild:2==s?t:null;var l=i.contains(u.documentElement,n);a.forEach((function(e){if(o)e=e.cloneNode(!0);else if(!n)return i(e).remove();n.insertBefore(e,t),l&&z(e,(function(e){if(!(null==e.nodeName||"SCRIPT"!==e.nodeName.toUpperCase()||e.type&&"text/javascript"!==e.type||e.src)){var t=e.ownerDocument?e.ownerDocument.defaultView:window;t.eval.call(t,e.innerHTML)}}))}))}))},i.fn[r?t+"To":"insert"+(s?"Before":"After")]=function(e){return i(e)[t](this),this}})),R.Z.prototype=K.prototype=i.fn,R.uniq=n,R.deserializeValue=q,i.zepto=R,i}();window.Zepto=x,void 0===window.$&&(window.$=x),function(e){var t,i,s=+new Date,r=window.document,n=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,a=/^(?:text|application)\/javascript/i,o=/^(?:text|application)\/xml/i,l="application/json",h="text/html",u=/^\s*$/,c=r.createElement("a");function d(t,i,s,n){if(t.global)return function(t,i,s){var r=e.Event(i);return e(t).trigger(r,s),!r.isDefaultPrevented()}(i||r,s,n)}function f(e,t){var i=t.context;if(!1===t.beforeSend.call(i,e,t)||!1===d(t,i,"ajaxBeforeSend",[e,t]))return!1;d(t,i,"ajaxSend",[e,t])}function g(e,t,i,s){var r=i.context,n="success";i.success.call(r,e,n,t),s&&s.resolveWith(r,[e,n,t]),d(i,r,"ajaxSuccess",[t,i,e]),m(n,t,i)}function p(e,t,i,s,r){var n=s.context;s.error.call(n,i,t,e),r&&r.rejectWith(n,[i,t,e]),d(s,n,"ajaxError",[i,s,e||t]),m(t,i,s)}function m(t,i,s){var r=s.context;s.complete.call(r,i,t),d(s,r,"ajaxComplete",[i,s]),function(t){t.global&&! --e.active&&d(t,null,"ajaxStop")}(s)}function v(){}function y(e,t){return""==t?e:(e+"&"+t).replace(/[&?]{1,2}/,"?")}function A(t,i,s,r){return e.isFunction(i)&&(r=s,s=i,i=void 0),e.isFunction(s)||(r=s,s=void 0),{url:t,data:i,success:s,dataType:r}}c.href=window.location.href,e.active=0,e.ajaxJSONP=function(t,i){if(!("type"in t))return e.ajax(t);var n,a,o=t.jsonpCallback,l=(e.isFunction(o)?o():o)||"Zepto"+s++,h=r.createElement("script"),u=window[l],c=function(t){e(h).triggerHandler("error",t||"abort")},d={abort:c};return i&&i.promise(d),e(h).on("load error",(function(s,r){clearTimeout(a),e(h).off().remove(),"error"!=s.type&&n?g(n[0],d,t,i):p(null,r||"error",d,t,i),window[l]=u,n&&e.isFunction(u)&&u(n[0]),u=n=void 0})),!1===f(d,t)?(c("abort"),d):(window[l]=function(){n=arguments},h.src=t.url.replace(/\?(.+)=\?/,"?$1="+l),r.head.appendChild(h),t.timeout>0&&(a=setTimeout((function(){c("timeout")}),t.timeout)),d)},e.ajaxSettings={type:"GET",beforeSend:v,success:v,error:v,complete:v,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:l,xml:"application/xml, text/xml",html:h,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0,dataFilter:v},e.ajax=function(s){var n,m,A=e.extend({},s||{}),E=e.Deferred&&e.Deferred();for(t in e.ajaxSettings)void 0===A[t]&&(A[t]=e.ajaxSettings[t]);!function(t){t.global&&0==e.active++&&d(t,null,"ajaxStart")}(A),A.crossDomain||((n=r.createElement("a")).href=A.url,n.href=n.href,A.crossDomain=c.protocol+"//"+c.host!=n.protocol+"//"+n.host),A.url||(A.url=window.location.toString()),(m=A.url.indexOf("#"))>-1&&(A.url=A.url.slice(0,m)),function(t){t.processData&&t.data&&"string"!=e.type(t.data)&&(t.data=e.param(t.data,t.traditional)),!t.data||t.type&&"GET"!=t.type.toUpperCase()&&"jsonp"!=t.dataType||(t.url=y(t.url,t.data),t.data=void 0)}(A);var T=A.dataType,S=/\?.+=\?/.test(A.url);if(S&&(T="jsonp"),!1!==A.cache&&(s&&!0===s.cache||"script"!=T&&"jsonp"!=T)||(A.url=y(A.url,"_="+Date.now())),"jsonp"==T)return S||(A.url=y(A.url,A.jsonp?A.jsonp+"=?":!1===A.jsonp?"":"callback=?")),e.ajaxJSONP(A,E);var b,L=A.accepts[T],_={},k=function(e,t){_[e.toLowerCase()]=[e,t]},R=/^([\w-]+:)\/\//.test(A.url)?RegExp.$1:window.location.protocol,I=A.xhr(),D=I.setRequestHeader;if(E&&E.promise(I),A.crossDomain||k("X-Requested-With","XMLHttpRequest"),k("Accept",L||"*/*"),(L=A.mimeType||L)&&(L.indexOf(",")>-1&&(L=L.split(",",2)[0]),I.overrideMimeType&&I.overrideMimeType(L)),(A.contentType||!1!==A.contentType&&A.data&&"GET"!=A.type.toUpperCase())&&k("Content-Type",A.contentType||"application/x-www-form-urlencoded"),A.headers)for(i in A.headers)k(i,A.headers[i]);if(I.setRequestHeader=k,I.onreadystatechange=function(){if(4==I.readyState){I.onreadystatechange=v,clearTimeout(b);var t,i=!1;if(I.status>=200&&I.status<300||304==I.status||0==I.status&&"file:"==R){if(T=T||function(e){return e&&(e=e.split(";",2)[0]),e&&(e==h?"html":e==l?"json":a.test(e)?"script":o.test(e)&&"xml")||"text"}(A.mimeType||I.getResponseHeader("content-type")),"arraybuffer"==I.responseType||"blob"==I.responseType)t=I.response;else{t=I.responseText;try{t=function(e,t,i){if(i.dataFilter==v)return e;var s=i.context;return i.dataFilter.call(s,e,t)}(t,T,A),"script"==T?(0,eval)(t):"xml"==T?t=I.responseXML:"json"==T&&(t=u.test(t)?null:e.parseJSON(t))}catch(e){i=e}if(i)return p(i,"parsererror",I,A,E)}g(t,I,A,E)}else p(I.statusText||null,I.status?"error":"abort",I,A,E)}},!1===f(I,A))return I.abort(),p(null,"abort",I,A,E),I;var P=!("async"in A)||A.async;if(I.open(A.type,A.url,P,A.username,A.password),A.xhrFields)for(i in A.xhrFields)I[i]=A.xhrFields[i];for(i in _)D.apply(I,_[i]);return A.timeout>0&&(b=setTimeout((function(){I.onreadystatechange=v,I.abort(),p(null,"timeout",I,A,E)}),A.timeout)),I.send(A.data?A.data:null),I},e.get=function(){return e.ajax(A.apply(null,arguments))},e.post=function(){var t=A.apply(null,arguments);return t.type="POST",e.ajax(t)},e.getJSON=function(){var t=A.apply(null,arguments);return t.dataType="json",e.ajax(t)},e.fn.load=function(t,i,s){if(!this.length)return this;var r,a=this,o=t.split(/\s/),l=A(t,i,s),h=l.success;return o.length>1&&(l.url=o[0],r=o[1]),l.success=function(t){a.html(r?e("<div>").html(t.replace(n,"")).find(r):t),h&&h.apply(a,arguments)},e.ajax(l),this};var E=encodeURIComponent;function T(t,i,s,r){var n,a=e.isArray(i),o=e.isPlainObject(i);e.each(i,(function(i,l){n=e.type(l),r&&(i=s?r:r+"["+(o||"object"==n||"array"==n?i:"")+"]"),!r&&a?t.add(l.name,l.value):"array"==n||!s&&"object"==n?T(t,l,s,i):t.add(i,l)}))}e.param=function(t,i){var s=[];return s.add=function(t,i){e.isFunction(i)&&(i=i()),null==i&&(i=""),this.push(E(t)+"="+E(i))},T(s,t,i),s.join("&").replace(/%20/g,"+")}}(x),function(e){e.Callbacks=function(t){t=e.extend({},t);var i,s,r,n,a,o,l=[],h=!t.once&&[],u=function(e){for(i=t.memory&&e,s=!0,o=n||0,n=0,a=l.length,r=!0;l&&o<a;++o)if(!1===l[o].apply(e[0],e[1])&&t.stopOnFalse){i=!1;break}r=!1,l&&(h?h.length&&u(h.shift()):i?l.length=0:c.disable())},c={add:function(){if(l){var s=l.length,o=function(i){e.each(i,(function(e,i){"function"==typeof i?t.unique&&c.has(i)||l.push(i):i&&i.length&&"string"!=typeof i&&o(i)}))};o(arguments),r?a=l.length:i&&(n=s,u(i))}return this},remove:function(){return l&&e.each(arguments,(function(t,i){for(var s;(s=e.inArray(i,l,s))>-1;)l.splice(s,1),r&&(s<=a&&--a,s<=o&&--o)})),this},has:function(t){return!(!l||!(t?e.inArray(t,l)>-1:l.length))},empty:function(){return a=l.length=0,this},disable:function(){return l=h=i=void 0,this},disabled:function(){return!l},lock:function(){return h=void 0,i||c.disable(),this},locked:function(){return!h},fireWith:function(e,t){return!l||s&&!h||(t=[e,(t=t||[]).slice?t.slice():t],r?h.push(t):u(t)),this},fire:function(){return c.fireWith(this,arguments)},fired:function(){return!!s}};return c}}(x),function(e){var t=Array.prototype.slice;function i(t){var s=[["resolve","done",e.Callbacks({once:1,memory:1}),"resolved"],["reject","fail",e.Callbacks({once:1,memory:1}),"rejected"],["notify","progress",e.Callbacks({memory:1})]],r="pending",n={state:function(){return r},always:function(){return a.done(arguments).fail(arguments),this},then:function(){var t=arguments;return i((function(i){e.each(s,(function(s,r){var o=e.isFunction(t[s])&&t[s];a[r[1]]((function(){var t=o&&o.apply(this,arguments);if(t&&e.isFunction(t.promise))t.promise().done(i.resolve).fail(i.reject).progress(i.notify);else{var s=this===n?i.promise():this,a=o?[t]:arguments;i[r[0]+"With"](s,a)}}))})),t=null})).promise()},promise:function(t){return null!=t?e.extend(t,n):n}},a={};return e.each(s,(function(e,t){var i=t[2],o=t[3];n[t[1]]=i.add,o&&i.add((function(){r=o}),s[1^e][2].disable,s[2][2].lock),a[t[0]]=function(){return a[t[0]+"With"](this===a?n:this,arguments),this},a[t[0]+"With"]=i.fireWith})),n.promise(a),t&&t.call(a,a),a}e.when=function(s){var r,n,a,o=t.call(arguments),l=o.length,h=0,u=1!==l||s&&e.isFunction(s.promise)?l:0,c=1===u?s:i(),d=function(e,i,s){return function(n){i[e]=this,s[e]=arguments.length>1?t.call(arguments):n,s===r?c.notifyWith(i,s):--u||c.resolveWith(i,s)}};if(l>1)for(r=new Array(l),n=new Array(l),a=new Array(l);h<l;++h)o[h]&&e.isFunction(o[h].promise)?o[h].promise().done(d(h,a,o)).fail(c.reject).progress(d(h,n,r)):--u;return u||c.resolveWith(a,o),c.promise()},e.Deferred=i}(x),function(e){var t,i=1,s=Array.prototype.slice,r=e.isFunction,n=function(e){return"string"==typeof e},a={},o={},l="onfocusin"in window,h={focus:"focusin",blur:"focusout"},u={mouseenter:"mouseover",mouseleave:"mouseout"};function c(e){return e._zid||(e._zid=i++)}function d(e,t,i,s){if((t=f(t)).ns)var r=(n=t.ns,new RegExp("(?:^| )"+n.replace(" "," .* ?")+"(?: |$)"));var n;return(a[c(e)]||[]).filter((function(e){return e&&(!t.e||e.e==t.e)&&(!t.ns||r.test(e.ns))&&(!i||c(e.fn)===c(i))&&(!s||e.sel==s)}))}function f(e){var t=(""+e).split(".");return{e:t[0],ns:t.slice(1).sort().join(" ")}}function g(e,t){return e.del&&!l&&e.e in h||!!t}function p(e){return u[e]||l&&h[e]||e}function m(i,s,r,n,o,l,h){var d=c(i),m=a[d]||(a[d]=[]);s.split(/\s/).forEach((function(s){if("ready"==s)return e(document).ready(r);var a=f(s);a.fn=r,a.sel=o,a.e in u&&(r=function(t){var i=t.relatedTarget;if(!i||i!==this&&!e.contains(this,i))return a.fn.apply(this,arguments)}),a.del=l;var c=l||r;a.proxy=function(e){if(!(e=S(e)).isImmediatePropagationStopped()){e.data=n;var s=c.apply(i,e._args==t?[e]:[e].concat(e._args));return!1===s&&(e.preventDefault(),e.stopPropagation()),s}},a.i=m.length,m.push(a),"addEventListener"in i&&i.addEventListener(p(a.e),a.proxy,g(a,h))}))}function v(e,t,i,s,r){var n=c(e);(t||"").split(/\s/).forEach((function(t){d(e,t,i,s).forEach((function(t){delete a[n][t.i],"removeEventListener"in e&&e.removeEventListener(p(t.e),t.proxy,g(t,r))}))}))}o.click=o.mousedown=o.mouseup=o.mousemove="MouseEvents",e.event={add:m,remove:v},e.proxy=function(t,i){var a=2 in arguments&&s.call(arguments,2);if(r(t)){var o=function(){return t.apply(i,a?a.concat(s.call(arguments)):arguments)};return o._zid=c(t),o}if(n(i))return a?(a.unshift(t[i],t),e.proxy.apply(null,a)):e.proxy(t[i],t);throw new TypeError("expected function")},e.fn.bind=function(e,t,i){return this.on(e,t,i)},e.fn.unbind=function(e,t){return this.off(e,t)},e.fn.one=function(e,t,i,s){return this.on(e,t,i,s,1)};var y=function(){return!0},A=function(){return!1},E=/^([A-Z]|returnValue$|layer[XY]$|webkitMovement[XY]$)/,T={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};function S(i,s){return!s&&i.isDefaultPrevented||(s||(s=i),e.each(T,(function(e,t){var r=s[e];i[e]=function(){return this[t]=y,r&&r.apply(s,arguments)},i[t]=A})),i.timeStamp||(i.timeStamp=Date.now()),(s.defaultPrevented!==t?s.defaultPrevented:"returnValue"in s?!1===s.returnValue:s.getPreventDefault&&s.getPreventDefault())&&(i.isDefaultPrevented=y)),i}function b(e){var i,s={originalEvent:e};for(i in e)E.test(i)||e[i]===t||(s[i]=e[i]);return S(s,e)}e.fn.delegate=function(e,t,i){return this.on(t,e,i)},e.fn.undelegate=function(e,t,i){return this.off(t,e,i)},e.fn.live=function(t,i){return e(document.body).delegate(this.selector,t,i),this},e.fn.die=function(t,i){return e(document.body).undelegate(this.selector,t,i),this},e.fn.on=function(i,a,o,l,h){var u,c,d=this;return i&&!n(i)?(e.each(i,(function(e,t){d.on(e,a,o,t,h)})),d):(n(a)||r(l)||!1===l||(l=o,o=a,a=t),l!==t&&!1!==o||(l=o,o=t),!1===l&&(l=A),d.each((function(t,r){h&&(u=function(e){return v(r,e.type,l),l.apply(this,arguments)}),a&&(c=function(t){var i,n=e(t.target).closest(a,r).get(0);if(n&&n!==r)return i=e.extend(b(t),{currentTarget:n,liveFired:r}),(u||l).apply(n,[i].concat(s.call(arguments,1)))}),m(r,i,l,o,a,c||u)})))},e.fn.off=function(i,s,a){var o=this;return i&&!n(i)?(e.each(i,(function(e,t){o.off(e,s,t)})),o):(n(s)||r(a)||!1===a||(a=s,s=t),!1===a&&(a=A),o.each((function(){v(this,i,a,s)})))},e.fn.trigger=function(t,i){return(t=n(t)||e.isPlainObject(t)?e.Event(t):S(t))._args=i,this.each((function(){t.type in h&&"function"==typeof this[t.type]?this[t.type]():"dispatchEvent"in this?this.dispatchEvent(t):e(this).triggerHandler(t,i)}))},e.fn.triggerHandler=function(t,i){var s,r;return this.each((function(a,o){(s=b(n(t)?e.Event(t):t))._args=i,s.target=o,e.each(d(o,t.type||t),(function(e,t){if(r=t.proxy(s),s.isImmediatePropagationStopped())return!1}))})),r},"focusin focusout focus blur load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach((function(t){e.fn[t]=function(e){return 0 in arguments?this.bind(t,e):this.trigger(t)}})),e.Event=function(e,t){n(e)||(e=(t=e).type);var i=document.createEvent(o[e]||"Events"),s=!0;if(t)for(var r in t)"bubbles"==r?s=!!t[r]:i[r]=t[r];return i.initEvent(e,s,!0),S(i)}}(x),function(){try{getComputedStyle(void 0)}catch(t){var e=getComputedStyle;window.getComputedStyle=function(t,i){try{return e(t,i)}catch(e){return null}}}}(),function(e){var t=e.zepto,i=t.qsa,s=t.matches;function r(t){return!(!(t=e(t)).width()&&!t.height())&&"none"!==t.css("display")}var n=e.expr[":"]={visible:function(){if(r(this))return this},hidden:function(){if(!r(this))return this},selected:function(){if(this.selected)return this},checked:function(){if(this.checked)return this},parent:function(){return this.parentNode},first:function(e){if(0===e)return this},last:function(e,t){if(e===t.length-1)return this},eq:function(e,t,i){if(e===i)return this},contains:function(t,i,s){if(e(this).text().indexOf(s)>-1)return this},has:function(e,i,s){if(t.qsa(this,s).length)return this}},a=new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"),o=/^\s*>/,l="Zepto"+ +new Date;function h(e,t){e=e.replace(/=#\]/g,'="#"]');var i,s,r=a.exec(e);if(r&&r[2]in n&&(i=n[r[2]],s=r[3],e=r[1],s)){var o=Number(s);s=isNaN(o)?s.replace(/^["']|["']$/g,""):o}return t(e,i,s)}t.qsa=function(s,r){return h(r,(function(n,a,h){try{var u;!n&&a?n="*":o.test(n)&&(u=e(s).addClass(l),n="."+l+" "+n);var c=i(s,n)}catch(e){throw console.error("error performing selector: %o",r),e}finally{u&&u.removeClass(l)}return a?t.uniq(e.map(c,(function(e,t){return a.call(e,t,c,h)}))):c}))},t.matches=function(e,t){return h(t,(function(t,i,r){return(!t||s(e,t))&&(!i||i.call(e,null,r)===e)}))}}(x);var M=O(x);Array.prototype.find||Object.defineProperty(Array.prototype,"find",{value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');var t=Object(this),i=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var s=arguments[1],r=0;r<i;){var n=t[r];if(e.call(s,n,r,t))return n;r++}}}),Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),i=t.length,s=new Array(i);i--;)s[i]=[t[i],e[t[i]]];return s}),Object.values||(Object.values=function(e){for(var t=Object.keys(e),i=t.length,s=new Array(i);i--;)s[i]=e[t[i]];return s}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(e),s=1;s<arguments.length;s++){var r=arguments[s];if(null!=r)for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(i[n]=r[n])}return i},writable:!0,configurable:!0}),Array.prototype.findIndex||Object.defineProperty(Array.prototype,"findIndex",{value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');var t=Object(this),i=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var s=arguments[1],r=0;r<i;){var n=t[r];if(e.call(s,n,r,t))return r;r++}return-1},configurable:!0,writable:!0});var F,N,U,B={mp4:"data:video/mp4;base64,AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAC721kYXQhEAUgpBv/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3pwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcCEQBSCkG//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADengAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAsJtb292AAAAbG12aGQAAAAAAAAAAAAAAAAAAAPoAAAALwABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAB7HRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAIAAAAAAAAALwAAAAAAAAAAAAAAAQEAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAC8AAAAAAAEAAAAAAWRtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAAKxEAAAIAFXEAAAAAAAtaGRscgAAAAAAAAAAc291bgAAAAAAAAAAAAAAAFNvdW5kSGFuZGxlcgAAAAEPbWluZgAAABBzbWhkAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAADTc3RibAAAAGdzdHNkAAAAAAAAAAEAAABXbXA0YQAAAAAAAAABAAAAAAAAAAAAAgAQAAAAAKxEAAAAAAAzZXNkcwAAAAADgICAIgACAASAgIAUQBUAAAAAAfQAAAHz+QWAgIACEhAGgICAAQIAAAAYc3R0cwAAAAAAAAABAAAAAgAABAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAIAAAABAAAAHHN0c3oAAAAAAAAAAAAAAAIAAAFzAAABdAAAABRzdGNvAAAAAAAAAAEAAAAsAAAAYnVkdGEAAABabWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAtaWxzdAAAACWpdG9vAAAAHWRhdGEAAAABAAAAAExhdmY1Ni40MC4xMDE="},$=[{name:"Chromium",group:"Chrome",identifier:"Chromium/([0-9.]*)"},{name:"Chrome Mobile",group:"Chrome",identifier:"Chrome/([0-9.]*) Mobile",versionIdentifier:"Chrome/([0-9.]*)"},{name:"Chrome",group:"Chrome",identifier:"Chrome/([0-9.]*)"},{name:"Chrome for iOS",group:"Chrome",identifier:"CriOS/([0-9.]*)"},{name:"Android Browser",group:"Chrome",identifier:"CrMo/([0-9.]*)"},{name:"Firefox",group:"Firefox",identifier:"Firefox/([0-9.]*)"},{name:"Opera Mini",group:"Opera",identifier:"Opera Mini/([0-9.]*)"},{name:"Opera",group:"Opera",identifier:"Opera ([0-9.]*)"},{name:"Opera",group:"Opera",identifier:"Opera/([0-9.]*)",versionIdentifier:"Version/([0-9.]*)"},{name:"IEMobile",group:"Explorer",identifier:"IEMobile/([0-9.]*)"},{name:"Internet Explorer",group:"Explorer",identifier:"MSIE ([a-zA-Z0-9.]*)"},{name:"Internet Explorer",group:"Explorer",identifier:"Trident/([0-9.]*)",versionIdentifier:"rv:([0-9.]*)"},{name:"Spartan",group:"Spartan",identifier:"Edge/([0-9.]*)",versionIdentifier:"Edge/([0-9.]*)"},{name:"Safari",group:"Safari",identifier:"Safari/([0-9.]*)",versionIdentifier:"Version/([0-9.]*)"}],G=[{name:"Windows 2000",group:"Windows",identifier:"Windows NT 5.0",version:"5.0"},{name:"Windows XP",group:"Windows",identifier:"Windows NT 5.1",version:"5.1"},{name:"Windows Vista",group:"Windows",identifier:"Windows NT 6.0",version:"6.0"},{name:"Windows 7",group:"Windows",identifier:"Windows NT 6.1",version:"7.0"},{name:"Windows 8",group:"Windows",identifier:"Windows NT 6.2",version:"8.0"},{name:"Windows 8.1",group:"Windows",identifier:"Windows NT 6.3",version:"8.1"},{name:"Windows 10",group:"Windows",identifier:"Windows NT 10.0",version:"10.0"},{name:"Windows Phone",group:"Windows Phone",identifier:"Windows Phone ([0-9.]*)"},{name:"Windows Phone",group:"Windows Phone",identifier:"Windows Phone OS ([0-9.]*)"},{name:"Windows",group:"Windows",identifier:"Windows"},{name:"Chrome OS",group:"Chrome OS",identifier:"CrOS"},{name:"Android",group:"Android",identifier:"Android",versionIdentifier:"Android ([a-zA-Z0-9.-]*)"},{name:"iPad",group:"iOS",identifier:"iPad",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"iPod",group:"iOS",identifier:"iPod",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"iPhone",group:"iOS",identifier:"iPhone OS",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"Mac OS X High Sierra",group:"Mac OS",identifier:"Mac OS X (10([_|.])13([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Sierra",group:"Mac OS",identifier:"Mac OS X (10([_|.])12([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X El Capitan",group:"Mac OS",identifier:"Mac OS X (10([_|.])11([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Yosemite",group:"Mac OS",identifier:"Mac OS X (10([_|.])10([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Mavericks",group:"Mac OS",identifier:"Mac OS X (10([_|.])9([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Mountain Lion",group:"Mac OS",identifier:"Mac OS X (10([_|.])8([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Lion",group:"Mac OS",identifier:"Mac OS X (10([_|.])7([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Snow Leopard",group:"Mac OS",identifier:"Mac OS X (10([_|.])6([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Leopard",group:"Mac OS",identifier:"Mac OS X (10([_|.])5([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Tiger",group:"Mac OS",identifier:"Mac OS X (10([_|.])4([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Panther",group:"Mac OS",identifier:"Mac OS X (10([_|.])3([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Jaguar",group:"Mac OS",identifier:"Mac OS X (10([_|.])2([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Puma",group:"Mac OS",identifier:"Mac OS X (10([_|.])1([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Cheetah",group:"Mac OS",identifier:"Mac OS X (10([_|.])0([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS",group:"Mac OS",identifier:"Mac OS"},{name:"Ubuntu",group:"Linux",identifier:"Ubuntu",versionIdentifier:"Ubuntu/([0-9.]*)"},{name:"Debian",group:"Linux",identifier:"Debian"},{name:"Gentoo",group:"Linux",identifier:"Gentoo"},{name:"Linux",group:"Linux",identifier:"Linux"},{name:"BlackBerry",group:"BlackBerry",identifier:"BlackBerry"}],K={},V=function(e,t){var i=e.split(".",2);t.fullVersion=e,i[0]&&(t.majorVersion=parseInt(i[0])),i[1]&&(t.minorVersion=parseInt(i[1]))},H=function(e,t,i){var s="["==t.substr(0,1)?new RegExp(t,"g"):t,r=e.split(s,2);"."!=t&&(e=e.replace(new RegExp(t,"g"),".")),i.fullVersion=e,r&&r[0]&&(i.majorVersion=parseInt(r[0])),r&&r[1]&&(i.minorVersion=parseInt(r[1]))},Y=function(e){var t,i=e.match(/\b(playstation 4|nx|opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return t=/\brv[ :]+(\d+)/g.exec(e)||[],{name:"IE",version:parseInt(t[1]||"")};if("Chrome"===i[1]){if(null!=(t=e.match(/\bOPR\/(\d+)/)))return{name:"Opera",version:parseInt(t[1])};if(null!=(t=e.match(/\bEdge\/(\d+)/)))return{name:"Edge",version:parseInt(t[1])}}else/android/i.test(e)&&(t=e.match(/version\/(\d+)/i))&&(i.splice(1,1,"Android WebView"),i.splice(2,1,t[1]));return{name:(i=i[2]?[i[1],i[2]]:[navigator.appName,navigator.appVersion,"-?"])[0],version:parseInt(i[1])}}(navigator.userAgent);K.isEdge=/Edg|EdgiOS|EdgA/i.test(navigator.userAgent),K.isChrome=/Chrome|CriOS/i.test(navigator.userAgent)&&!K.isEdge,K.isSafari=/Safari/i.test(navigator.userAgent)&&!K.isChrome&&!K.isEdge,K.isFirefox=/Firefox/i.test(navigator.userAgent),K.isLegacyIE=!!window.ActiveXObject,K.isIE=K.isLegacyIE||/trident.*rv:1\d/i.test(navigator.userAgent),K.isIE11=/trident.*rv:11/i.test(navigator.userAgent),K.isChromecast=K.isChrome&&/CrKey/i.test(navigator.userAgent),K.isMobile=/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Mobile Safari|Opera Mini/i.test(navigator.userAgent),K.isiOS=/iPad|iPhone|iPod/i.test(navigator.userAgent),K.isAndroid=/Android/i.test(navigator.userAgent),K.isWindowsPhone=/Windows Phone/i.test(navigator.userAgent),K.isWin8App=/MSAppHost/i.test(navigator.userAgent),K.isWiiU=/WiiU/i.test(navigator.userAgent),K.isPS4=/PlayStation 4/i.test(navigator.userAgent),K.hasLocalstorage=function(){try{return localStorage.setItem("clappr","clappr"),localStorage.removeItem("clappr"),!0}catch(e){return!1}}(),K.hasFlash=function(){try{return!!new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(e){return!(!navigator.mimeTypes||void 0===navigator.mimeTypes["application/x-shockwave-flash"]||!navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)}}(),K.name=Y.name,K.version=Y.version,K.userAgent=navigator.userAgent,K.data=function(){var e,t={},i=K.userAgent.toLowerCase(),s=y($);try{for(s.s();!(e=s.n()).done;){var r=e.value,n=new RegExp(r.identifier.toLowerCase()).exec(i);if(null!=n&&n[1]){if(t.name=r.name,t.group=r.group,r.versionIdentifier){var a=new RegExp(r.versionIdentifier.toLowerCase()).exec(i);null!=a&&a[1]&&V(a[1],t)}else V(n[1],t);break}}}catch(e){s.e(e)}finally{s.f()}return t}(),K.os=function(){var e,t={},i=K.userAgent.toLowerCase(),s=y(G);try{for(s.s();!(e=s.n()).done;){var r=e.value,n=new RegExp(r.identifier.toLowerCase()).exec(i);if(null!=n){if(t.name=r.name,t.group=r.group,r.version)H(r.version,r.versionSeparator?r.versionSeparator:".",t);else if(n[1])H(n[1],r.versionSeparator?r.versionSeparator:".",t);else if(r.versionIdentifier){var a=new RegExp(r.versionIdentifier.toLowerCase()).exec(i);null!=a&&a[1]&&H(a[1],r.versionSeparator?r.versionSeparator:".",t)}break}}}catch(e){s.e(e)}finally{s.f()}return t}(),K.isWindows=/^Windows$/i.test(K.os.group),K.isMacOS=/^Mac OS$/i.test(K.os.group),K.isLinux=/^Linux$/i.test(K.os.group),K.viewport=((F={}).width=M(window).width(),F.height=M(window).height(),F),K.device=(N=K.userAgent,(U=/\((iP(?:hone|ad|od))?(?:[^;]*; ){0,2}([^)]+(?=\)))/.exec(N))&&(U[1]||U[2])||""),void 0!==window.orientation&&function(){switch(window.orientation){case-90:case 90:K.viewport.orientation="landscape";break;default:K.viewport.orientation="portrait"}}();var j={},W=[],q=(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||function(e){window.setTimeout(e,1e3/60)}).bind(window),z=(window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.clearTimeout).bind(window);function X(e,t){if(t)for(var i in t){var s=Object.getOwnPropertyDescriptor(t,i);s?Object.defineProperty(e,i,s):e[i]=t[i]}return e}function Q(e,t){var i=function(e){function i(){var e;p(this,i);for(var s=arguments.length,r=new Array(s),n=0;n<s;n++)r[n]=arguments[n];return e=g(this,i,[].concat(r)),t.initialize&&t.initialize.apply(e,r),e}return S(i,e),v(i)}(e);return X(i.prototype,t),i}var Z={fullscreenElement:function(){return document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement},requestFullscreen:function(e){if(e.requestFullscreen)return e.requestFullscreen();if(e.webkitRequestFullscreen){if("function"==typeof e.then)return e.webkitRequestFullscreen();e.webkitRequestFullscreen()}else{if(e.mozRequestFullScreen)return e.mozRequestFullScreen();if(e.msRequestFullscreen)return e.msRequestFullscreen();e.querySelector&&e.querySelector("video")&&e.querySelector("video").webkitEnterFullScreen?e.querySelector("video").webkitEnterFullScreen():e.webkitEnterFullScreen&&e.webkitEnterFullScreen()}},cancelFullscreen:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;e.exitFullscreen?e.exitFullscreen():e.webkitCancelFullScreen?e.webkitCancelFullScreen():e.webkitExitFullscreen?e.webkitExitFullscreen():e.mozCancelFullScreen?e.mozCancelFullScreen():e.msExitFullscreen&&e.msExitFullscreen()},fullscreenEnabled:function(){return!!(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled)}},J=function(){return v((function e(){p(this,e)}),null,[{key:"params",get:function(){var e=window.location.search.substring(1);return e!==this.query&&(this._urlParams=this.parse(e),this.query=e),this._urlParams}},{key:"hashParams",get:function(){var e=window.location.hash.substring(1);return e!==this.hash&&(this._hashParams=this.parse(e),this.hash=e),this._hashParams}},{key:"parse",value:function(e){for(var t,i=/\+/g,s=/([^&=]+)=?([^&]*)/g,r=function(e){return decodeURIComponent(e.replace(i," "))},n={};t=s.exec(e);)n[r(t[1]).toLowerCase()]=r(t[2]);return n}}])}();function ee(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"t",t=0,i=J.params[e]||J.hashParams[e]||"",s=i.match(/[0-9]+[hms]+/g)||[];if(s.length>0){var r={h:3600,m:60,s:1};s.forEach((function(e){if(e){var i=e[e.length-1],s=parseInt(e.slice(0,e.length-1),10);t+=s*r[i]}}))}else i&&(t=parseInt(i,10));return t}function te(e){return j[e]||(j[e]=0),e+ ++j[e]}function ie(e){return e-parseFloat(e)+1>=0}function se(){var e=document.getElementsByTagName("script");return e.length?e[e.length-1].src:""}function re(){return window.navigator&&window.navigator.language}function ne(e,t){var i=(t=Object.assign({inline:!1,muted:!1,timeout:250,type:"video",source:B.mp4,element:null},t)).element?t.element:document.createElement(t.type);i.muted=t.muted,!0===t.muted&&i.setAttribute("muted","muted"),!0===t.inline&&i.setAttribute("playsinline","playsinline"),i.src=t.source;var s=i.play(),r=setTimeout((function(){n(!1,new Error("Timeout ".concat(t.timeout," ms has been reached")))}),t.timeout),n=function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;clearTimeout(r),e(t,i)};void 0!==s?s.then((function(){return n(!0)})).catch((function(e){return n(!1,e)})):n(!0)}var ae=function(){return v((function e(){p(this,e)}),null,[{key:"configure",value:function(e){this.options=M.extend(!0,this.options,e)}},{key:"create",value:function(e){return this.options.recycleVideo&&"video"===e&&W.length>0?W.shift():document.createElement(e)}},{key:"garbage",value:function(e){this.options.recycleVideo&&"VIDEO"===e.tagName.toUpperCase()&&(M(e).children().remove(),Object.values(e.attributes).forEach((function(t){return e.removeAttribute(t.name)})),W.push(e))}}])}();ae.options={recycleVideo:!1};var oe=function(){return v((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:500;p(this,e),this.delay=t,this.lastTime=0}),[{key:"handle",value:function(e,t){var i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s=(new Date).getTime(),r=s-this.lastTime;r<this.delay&&r>0&&(t(),i&&e.preventDefault()),this.lastTime=s}}])}(),le=function(){return window.performance&&window.performance.now?performance.now():Date.now()},he=function(e,t){return void 0!==e&&void 0!==t&&void 0!==t.find((function(t){return e.toLowerCase()===t.toLowerCase()}))},ue="font-weight: bold; font-size: 13px;",ce="color: #ff8000;"+ue,de="color: #ff0000;"+ue,fe=["color: #0000ff;"+ue,"color: #006600;"+ue,ce,de,de],ge=["debug","info","warn","error","disabled"],pe=function(){return v((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3;p(this,e),this.EXCLUDE_LIST=["timeupdate","playback:timeupdate","playback:progress","container:hover","container:timeupdate","container:progress","core:mousemove"],this.level=t,this.previousLevel=this.level,this.offLevel=i}),[{key:"level",get:function(){return this._level},set:function(e){this._level=e}},{key:"debug",value:function(e){this.log(e,0,Array.prototype.slice.call(arguments,1))}},{key:"info",value:function(e){this.log(e,1,Array.prototype.slice.call(arguments,1))}},{key:"warn",value:function(e){this.log(e,2,Array.prototype.slice.call(arguments,1))}},{key:"error",value:function(e){this.log(e,3,Array.prototype.slice.call(arguments,1))}},{key:"onOff",value:function(){this.level===this.offLevel?this.level=this.previousLevel:(this.previousLevel=this.level,this.level=this.offLevel),window.console&&window.console.log&&window.console.log("%c[Clappr.Log] set log level to "+ge[this.level],ce)}},{key:"log",value:function(e,t,i){if(!(t<this.level||this.EXCLUDE_LIST.indexOf(i[0])>=0)){i||(i=e,e=null);var s=fe[t],r="";e&&(r="["+e+"]"),window.console&&window.console.log&&window.console.log.apply(console,["%c["+ge[t]+"]"+r,s].concat(i))}}}])}();pe.LEVEL_DEBUG=0,pe.LEVEL_INFO=1,pe.LEVEL_WARN=2,pe.LEVEL_ERROR=3,pe.getInstance=function(){return void 0===this._instance&&(this._instance=new this),this._instance},pe.setLevel=function(e){this.getInstance().level=e},pe.debug=function(){this.getInstance().debug.apply(this.getInstance(),arguments)},pe.info=function(){this.getInstance().info.apply(this.getInstance(),arguments)},pe.warn=function(){this.getInstance().warn.apply(this.getInstance(),arguments)},pe.error=function(){this.getInstance().error.apply(this.getInstance(),arguments)};var me=Array.prototype.slice,ve=/\s+/,ye=function(e,t,i,s){if(!i)return!0;if("object"===C(i)){for(var r in i)e[t].apply(e,[r,i[r]].concat(s));return!1}if(ve.test(i)){for(var n=i.split(ve),a=0,o=n.length;a<o;a++)e[t].apply(e,[n[a]].concat(s));return!1}return!0},Ae=function(e,t,i,s){var r,n=-1,a=e.length,o=t[0],l=t[1],h=t[2];!function u(){try{switch(t.length){case 0:for(;++n<a;)(r=e[n]).callback.call(r.ctx);return;case 1:for(;++n<a;)(r=e[n]).callback.call(r.ctx,o);return;case 2:for(;++n<a;)(r=e[n]).callback.call(r.ctx,o,l);return;case 3:for(;++n<a;)(r=e[n]).callback.call(r.ctx,o,l,h);return;default:for(;++n<a;)(r=e[n]).callback.apply(r.ctx,t);return}}catch(e){pe.error.apply(pe,[i,"error on event",s,"trigger","-",e]),u()}}()},Ee=function(){function e(){p(this,e)}return v(e,[{key:"on",value:function(e,t,i){return ye(this,"on",e,[t,i])&&t?(this._events||(this._events={}),(this._events[e]||(this._events[e]=[])).push({callback:t,context:i,ctx:i||this}),this):this}},{key:"once",value:function(e,t,i){var s,r=this;if(!ye(this,"once",e,[t,i])||!t)return this;return s=function(){r.off(e,s),t.apply(this,arguments)},s._callback=t,this.on(e,s,i)}},{key:"off",value:function(e,t,i){var s,r,n,a,o,l,h,u;if(!this._events||!ye(this,"off",e,[t,i]))return this;if(!e&&!t&&!i)return this._events=void 0,this;for(o=0,l=(a=e?[e]:Object.keys(this._events)).length;o<l;o++)if(e=a[o],n=this._events[e]){if(this._events[e]=s=[],t||i)for(h=0,u=n.length;h<u;h++)r=n[h],(t&&t!==r.callback&&t!==r.callback._callback||i&&i!==r.context)&&s.push(r);s.length||delete this._events[e]}return this}},{key:"trigger",value:function(e){var t=this.name||this.constructor.name;if(pe.debug.apply(pe,[t].concat(Array.prototype.slice.call(arguments))),!this._events)return this;var i=me.call(arguments,1);if(!ye(this,"trigger",e,i))return this;var s=this._events[e],r=this._events.all;return s&&Ae(s,i,t,e),r&&Ae(r,arguments,t,e),this}},{key:"stopListening",value:function(e,t,i){var s=this._listeningTo;if(!s)return this;var r=!t&&!i;for(var n in i||"object"!==C(t)||(i=this),e&&((s={})[e._listenId]=e),s)(e=s[n]).off(t,i,this),(r||0===Object.keys(e._events).length)&&delete this._listeningTo[n];return this}}],[{key:"register",value:function(t){e.Custom||(e.Custom={});var i="string"==typeof t&&t.toUpperCase().trim();i&&!e.Custom[i]?e.Custom[i]=i.toLowerCase().split("_").map((function(e,t){return 0===t?e:e=e[0].toUpperCase()+e.slice(1)})).join(""):pe.error("Events","Error when register event: "+t)}},{key:"listAvailableCustomEvents",value:function(){return e.Custom||(e.Custom={}),Object.keys(e.Custom).filter((function(t){return"string"==typeof e.Custom[t]}))}}])}();Ee.prototype.listenTo=function(e,t,i){return(this._listeningTo||(this._listeningTo={}))[e._listenId||(e._listenId=te("l"))]=e,i||"object"!==C(t)||(i=this),e.on(t,i,this),this},Ee.prototype.listenToOnce=function(e,t,i){return(this._listeningTo||(this._listeningTo={}))[e._listenId||(e._listenId=te("l"))]=e,i||"object"!==C(t)||(i=this),e.once(t,i,this),this},Ee.PLAYER_READY="ready",Ee.PLAYER_RESIZE="resize",Ee.PLAYER_FULLSCREEN="fullscreen",Ee.PLAYER_PLAY="play",Ee.PLAYER_PAUSE="pause",Ee.PLAYER_STOP="stop",Ee.PLAYER_ENDED="ended",Ee.PLAYER_SEEK="seek",Ee.PLAYER_ERROR="playererror",Ee.ERROR="error",Ee.PLAYER_TIMEUPDATE="timeupdate",Ee.PLAYER_VOLUMEUPDATE="volumeupdate",Ee.PLAYER_SUBTITLE_AVAILABLE="subtitleavailable",Ee.PLAYBACK_PIP_ENTER="playback:picture-in-picture:enter",Ee.PLAYBACK_PIP_EXIT="playback:picture-in-picture:exit",Ee.PLAYBACK_PROGRESS="playback:progress",Ee.PLAYBACK_TIMEUPDATE="playback:timeupdate",Ee.PLAYBACK_READY="playback:ready",Ee.PLAYBACK_BUFFERING="playback:buffering",Ee.PLAYBACK_BUFFERFULL="playback:bufferfull",Ee.PLAYBACK_SETTINGSUPDATE="playback:settingsupdate",Ee.PLAYBACK_LOADEDMETADATA="playback:loadedmetadata",Ee.PLAYBACK_HIGHDEFINITIONUPDATE="playback:highdefinitionupdate",Ee.PLAYBACK_BITRATE="playback:bitrate",Ee.PLAYBACK_LEVELS_AVAILABLE="playback:levels:available",Ee.PLAYBACK_LEVEL_SWITCH_START="playback:levels:switch:start",Ee.PLAYBACK_LEVEL_SWITCH_END="playback:levels:switch:end",Ee.PLAYBACK_PLAYBACKSTATE="playback:playbackstate",Ee.PLAYBACK_DVR="playback:dvr",Ee.PLAYBACK_MEDIACONTROL_DISABLE="playback:mediacontrol:disable",Ee.PLAYBACK_MEDIACONTROL_ENABLE="playback:mediacontrol:enable",Ee.PLAYBACK_ENDED="playback:ended",Ee.PLAYBACK_PLAY_INTENT="playback:play:intent",Ee.PLAYBACK_PLAY="playback:play",Ee.PLAYBACK_PAUSE="playback:pause",Ee.PLAYBACK_SEEK="playback:seek",Ee.PLAYBACK_SEEKED="playback:seeked",Ee.PLAYBACK_STOP="playback:stop",Ee.PLAYBACK_ERROR="playback:error",Ee.PLAYBACK_STATS_ADD="playback:stats:add",Ee.PLAYBACK_FRAGMENT_LOADED="playback:fragment:loaded",Ee.PLAYBACK_FRAGMENT_BUFFERED="playback:fragment:buffered",Ee.PLAYBACK_LEVEL_SWITCH="playback:level:switch",Ee.PLAYBACK_SUBTITLE_AVAILABLE="playback:subtitle:available",Ee.PLAYBACK_SUBTITLE_CHANGED="playback:subtitle:changed",Ee.PLAYBACK_AUDIO_AVAILABLE="playback:audio:available",Ee.PLAYBACK_AUDIO_CHANGED="playback:audio:changed",Ee.PLAYBACK_RESIZE="playback:resize",Ee.CORE_CONTAINERS_CREATED="core:containers:created",Ee.CORE_ACTIVE_CONTAINER_CHANGED="core:active:container:changed",Ee.CORE_OPTIONS_WILL_CHANGE="core:options:will:change",Ee.CORE_OPTIONS_CHANGE="core:options:change",Ee.CORE_READY="core:ready",Ee.CORE_FULLSCREEN="core:fullscreen",Ee.CORE_RESIZE="core:resize",Ee.CORE_SCREEN_ORIENTATION_CHANGED="core:screen:orientation:changed",Ee.CORE_MOUSE_MOVE="core:mousemove",Ee.CORE_MOUSE_LEAVE="core:mouseleave",Ee.CONTAINER_PLAYBACKSTATE="container:playbackstate",Ee.CONTAINER_PLAYBACKDVRSTATECHANGED="container:dvr",Ee.CONTAINER_BITRATE="container:bitrate",Ee.CONTAINER_STATS_REPORT="container:stats:report",Ee.CONTAINER_DESTROYED="container:destroyed",Ee.CONTAINER_READY="container:ready",Ee.CONTAINER_RESIZE="container:resize",Ee.CONTAINER_ERROR="container:error",Ee.CONTAINER_LOADEDMETADATA="container:loadedmetadata",Ee.CONTAINER_SUBTITLE_AVAILABLE="container:subtitle:available",Ee.CONTAINER_SUBTITLE_CHANGED="container:subtitle:changed",Ee.CONTAINER_AUDIO_AVAILABLE="container:audio:available",Ee.CONTAINER_AUDIO_CHANGED="container:audio:changed",Ee.CONTAINER_TIMEUPDATE="container:timeupdate",Ee.CONTAINER_PROGRESS="container:progress",Ee.CONTAINER_PLAY="container:play",Ee.CONTAINER_STOP="container:stop",Ee.CONTAINER_PAUSE="container:pause",Ee.CONTAINER_ENDED="container:ended",Ee.CONTAINER_CLICK="container:click",Ee.CONTAINER_DBLCLICK="container:dblclick",Ee.CONTAINER_CONTEXTMENU="container:contextmenu",Ee.CONTAINER_MOUSE_ENTER="container:mouseenter",Ee.CONTAINER_MOUSE_LEAVE="container:mouseleave",Ee.CONTAINER_MOUSE_UP="container:mouseup",Ee.CONTAINER_MOUSE_DOWN="container:mousedown",Ee.CONTAINER_PIP_ENTER="container:picture-in-picture:enter",Ee.CONTAINER_PIP_EXIT="container:picture-in-picture:exit",Ee.CONTAINER_SEEK="container:seek",Ee.CONTAINER_SEEKED="container:seeked",Ee.CONTAINER_VOLUME="container:volume",Ee.CONTAINER_FULLSCREEN="container:fullscreen",Ee.CONTAINER_STATE_BUFFERING="container:state:buffering",Ee.CONTAINER_STATE_BUFFERFULL="container:state:bufferfull",Ee.CONTAINER_SETTINGSUPDATE="container:settingsupdate",Ee.CONTAINER_HIGHDEFINITIONUPDATE="container:highdefinitionupdate",Ee.CONTAINER_MEDIACONTROL_SHOW="container:mediacontrol:show",Ee.CONTAINER_MEDIACONTROL_HIDE="container:mediacontrol:hide",Ee.CONTAINER_MEDIACONTROL_DISABLE="container:mediacontrol:disable",Ee.CONTAINER_MEDIACONTROL_ENABLE="container:mediacontrol:enable",Ee.CONTAINER_STATS_ADD="container:stats:add",Ee.CONTAINER_OPTIONS_WILL_CHANGE="container:options:will:change",Ee.CONTAINER_OPTIONS_CHANGE="container:options:change",Ee.MEDIACONTROL_RENDERED="mediacontrol:rendered",Ee.MEDIACONTROL_FULLSCREEN="mediacontrol:fullscreen",Ee.MEDIACONTROL_SHOW="mediacontrol:show",Ee.MEDIACONTROL_HIDE="mediacontrol:hide",Ee.MEDIACONTROL_MOUSEMOVE_SEEKBAR="mediacontrol:mousemove:seekbar",Ee.MEDIACONTROL_MOUSELEAVE_SEEKBAR="mediacontrol:mouseleave:seekbar",Ee.MEDIACONTROL_PLAYING="mediacontrol:playing",Ee.MEDIACONTROL_NOTPLAYING="mediacontrol:notplaying",Ee.MEDIACONTROL_CONTAINERCHANGED="mediacontrol:containerchanged",Ee.MEDIACONTROL_OPTIONS_CHANGE="mediacontrol:options:change";var Te=function(e){function t(){var e,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return p(this,t),(e=g(this,t,[i]))._options=i,e.uniqueId=te("o"),e}return S(t,e),v(t,[{key:"options",get:function(){return this._options}}])}(Ee),Se={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},be=/(.)^/,Le={"'":"'","\\":"\\","\r":"r","\n":"n","\t":"t","\u2028":"u2028","\u2029":"u2029"},_e=/\\|'|\r|\n|\t|\u2028|\u2029/g,ke={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"},Re=new RegExp("[&<>\"']","g"),Ie=function(e){return null===e?"":(""+e).replace(Re,(function(e){return ke[e]}))},De=0,Pe=function(e,t){var i,s=new RegExp([(Se.escape||be).source,(Se.interpolate||be).source,(Se.evaluate||be).source].join("|")+"|$","g"),r=0,n="__p+='";e.replace(s,(function(t,i,s,a,o){return n+=e.slice(r,o).replace(_e,(function(e){return"\\"+Le[e]})),i&&(n+="'+\n((__t=("+i+"))==null?'':escapeExpr(__t))+\n'"),s&&(n+="'+\n((__t=("+s+"))==null?'':__t)+\n'"),a&&(n+="';\n"+a+"\n__p+='"),r=o+t.length,t})),n+="';\n",Se.variable||(n="with(obj||{}){\n"+n+"}\n"),n="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+n+"return __p;\n//# sourceURL=/microtemplates/source["+De+++"]";try{i=new Function(Se.variable||"obj","escapeExpr",n)}catch(e){throw e.source=n,e}if(t)return i(t,Ie);var a=function(e){return i.call(this,e,Ie)};return a.source="function("+(Se.variable||"obj")+"){\n"+n+"}",a};Pe.settings=Se;var Ce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{baseUrl:""};return M('<style class="clappr-style"></style>').html(Pe(e.toString())(t))},we=/^(\S+)\s*(.*)$/,Oe=function(e){function t(e){var i;return p(this,t),(i=g(this,t,[e])).cid=te("c"),i._ensureElement(),i.delegateEvents(),i}return S(t,e),v(t,[{key:"tagName",get:function(){return"div"}},{key:"events",get:function(){return{}}},{key:"attributes",get:function(){return{}}},{key:"$",value:function(e){return this.$el.find(e)}},{key:"render",value:function(){return this}},{key:"destroy",value:function(){return this.$el.remove(),this.stopListening(),this.undelegateEvents(),this}},{key:"setElement",value:function(e,t){return this.$el&&this.undelegateEvents(),this.$el=M.zepto.isZ(e)?e:M(e),this.el=this.$el[0],!1!==t&&this.delegateEvents(),this}},{key:"delegateEvents",value:function(e){for(var t in e||(e=this.events),this.undelegateEvents(),e){var i=e[t];if(i&&i.constructor!==Function&&(i=this[e[t]]),i){var s=t.match(we),r=s[1],n=s[2];r+=".delegateEvents"+this.cid,""===n?this.$el.on(r,i.bind(this)):this.$el.on(r,n,i.bind(this))}}return this}},{key:"undelegateEvents",value:function(){return this.$el.off(".delegateEvents"+this.cid),this}},{key:"_ensureElement",value:function(){if(this.el)this.setElement(this.el,!1);else{var e=M.extend(!0,{},this.attributes);this.id&&(e.id=this.id),this.className&&(e.class=this.className);var t=M(ae.create(this.tagName)).attr(e);this.setElement(t,!1)}}},{key:"onResize",value:function(){return this}},{key:"resize",value:function(e){var t=ie(e.width)?"".concat(e.width,"px"):"".concat(e.width),i=ie(e.height)?"".concat(e.height,"px"):"".concat(e.height);return this.el.style.width=t,this.el.style.height=i,this.onResize(e),this}}])}(Te),xe=function(e){function t(){var e,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;return p(this,t),(e=g(this,t,[i])).core=s,e}return S(t,e),v(t,[{key:"name",get:function(){return"error"}},{key:"createError",value:function(e){this.core?this.core.trigger(Ee.ERROR,e):pe.warn(this.name,"Core is not set. Error: ",e)}}],[{key:"Levels",get:function(){return{FATAL:"FATAL",WARN:"WARN",INFO:"INFO"}}}])}(Te),Me={createError:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{useCodePrefix:!0},i=this.constructor&&this.constructor.type||"",s=this.name||i,r=this.i18n||this.core&&this.core.i18n||this.container&&this.container.i18n,n="".concat(s,":").concat(e&&e.code||"unknown"),a={description:"",level:xe.Levels.FATAL,origin:s,scope:i,raw:{}},o=Object.assign({},a,e,{code:t.useCodePrefix?n:e.code});if(r&&o.level==xe.Levels.FATAL&&!o.UI){var l={title:r.t("default_error_title"),message:r.t("default_error_message")};o.UI=l}return this.playerError?this.playerError.createError(o):pe.warn(s,"PlayerError is not defined. Error: ",o),o}},Fe=function(e){function t(e){var i;return p(this,t),(i=g(this,t,[e.options])).core=e,i.enabled=!0,i.bindEvents(),i.render(),i}return S(t,e),v(t,[{key:"playerError",get:function(){return this.core.playerError}},{key:"bindEvents",value:function(){}},{key:"getExternalInterface",value:function(){return{}}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.$el.show(),this.enabled=!0)}},{key:"disable",value:function(){this.stopListening(),this.$el.hide(),this.enabled=!1}},{key:"render",value:function(){return this}}])}(Oe);Object.assign(Fe.prototype,Me),Fe.extend=function(e){return Q(Fe,e)},Fe.type="core";var Ne=function(e){function t(e,i,s){var r;return p(this,t),(r=g(this,t,[e]))._i18n=i,r.currentTime=0,r.volume=100,r.playback=e.playback,r.playerError=s,r.settings=M.extend(!0,{},r.playback.settings),r.isReady=!1,r.mediaControlDisabled=!1,r.plugins=[r.playback],r.dblTapHandler=new oe(500),r.clickTimer=null,r.clickDelay=200,r.actionsMetadata={},r.bindEvents(),r}return S(t,e),v(t,[{key:"name",get:function(){return"Container"}},{key:"attributes",get:function(){return{class:"container","data-container":""}}},{key:"events",get:function(){return{click:"clicked",dblclick:"dblClicked",touchend:"dblTap",contextmenu:"onContextMenu",mouseenter:"mouseEnter",mouseleave:"mouseLeave",mouseup:"onMouseUp",mousedown:"onMouseDown"}}},{key:"ended",get:function(){return this.playback.ended}},{key:"buffering",get:function(){return this.playback.buffering}},{key:"i18n",get:function(){return this._i18n}},{key:"hasClosedCaptionsTracks",get:function(){return this.playback.hasClosedCaptionsTracks}},{key:"closedCaptionsTracks",get:function(){return this.playback.closedCaptionsTracks}},{key:"closedCaptionsTrackId",get:function(){return this.playback.closedCaptionsTrackId},set:function(e){this.playback.closedCaptionsTrackId=e}},{key:"audioTracks",get:function(){return this.playback.audioTracks}},{key:"currentAudioTrack",get:function(){return this.playback.currentAudioTrack}},{key:"isPiPActive",get:function(){return this.playback.isPiPActive}},{key:"bindEvents",value:function(){this.listenTo(this.playback,Ee.PLAYBACK_PROGRESS,this.onProgress),this.listenTo(this.playback,Ee.PLAYBACK_TIMEUPDATE,this.timeUpdated),this.listenTo(this.playback,Ee.PLAYBACK_READY,this.ready),this.listenTo(this.playback,Ee.PLAYBACK_BUFFERING,this.onBuffering),this.listenTo(this.playback,Ee.PLAYBACK_BUFFERFULL,this.bufferfull),this.listenTo(this.playback,Ee.PLAYBACK_SETTINGSUPDATE,this.settingsUpdate),this.listenTo(this.playback,Ee.PLAYBACK_LOADEDMETADATA,this.loadedMetadata),this.listenTo(this.playback,Ee.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinitionUpdate),this.listenTo(this.playback,Ee.PLAYBACK_BITRATE,this.updateBitrate),this.listenTo(this.playback,Ee.PLAYBACK_PLAYBACKSTATE,this.playbackStateChanged),this.listenTo(this.playback,Ee.PLAYBACK_DVR,this.playbackDvrStateChanged),this.listenTo(this.playback,Ee.PLAYBACK_MEDIACONTROL_DISABLE,this.disableMediaControl),this.listenTo(this.playback,Ee.PLAYBACK_MEDIACONTROL_ENABLE,this.enableMediaControl),this.listenTo(this.playback,Ee.PLAYBACK_SEEK,this.onSeek),this.listenTo(this.playback,Ee.PLAYBACK_SEEKED,this.onSeeked),this.listenTo(this.playback,Ee.PLAYBACK_ENDED,this.onEnded),this.listenTo(this.playback,Ee.PLAYBACK_PLAY,this.playing),this.listenTo(this.playback,Ee.PLAYBACK_PAUSE,this.paused),this.listenTo(this.playback,Ee.PLAYBACK_STOP,this.stopped),this.listenTo(this.playback,Ee.PLAYBACK_ERROR,this.error),this.listenTo(this.playback,Ee.PLAYBACK_SUBTITLE_AVAILABLE,this.subtitleAvailable),this.listenTo(this.playback,Ee.PLAYBACK_SUBTITLE_CHANGED,this.subtitleChanged),this.listenTo(this.playback,Ee.PLAYBACK_AUDIO_AVAILABLE,this.audioAvailable),this.listenTo(this.playback,Ee.PLAYBACK_AUDIO_CHANGED,this.audioChanged),this.listenTo(this.playback,Ee.PLAYBACK_PIP_ENTER,this.onEnterPiP),this.listenTo(this.playback,Ee.PLAYBACK_PIP_EXIT,this.onExitPiP)}},{key:"subtitleAvailable",value:function(){this.trigger(Ee.CONTAINER_SUBTITLE_AVAILABLE)}},{key:"subtitleChanged",value:function(e){this.trigger(Ee.CONTAINER_SUBTITLE_CHANGED,e)}},{key:"audioAvailable",value:function(e){this.trigger(Ee.CONTAINER_AUDIO_AVAILABLE,e)}},{key:"audioChanged",value:function(e){this.trigger(Ee.CONTAINER_AUDIO_CHANGED,e)}},{key:"playbackStateChanged",value:function(e){this.trigger(Ee.CONTAINER_PLAYBACKSTATE,e)}},{key:"playbackDvrStateChanged",value:function(e){this.settings=this.playback.settings,this.dvrInUse=e,this.trigger(Ee.CONTAINER_PLAYBACKDVRSTATECHANGED,e)}},{key:"updateBitrate",value:function(e){this.trigger(Ee.CONTAINER_BITRATE,e)}},{key:"statsReport",value:function(e){this.trigger(Ee.CONTAINER_STATS_REPORT,e)}},{key:"getPlaybackType",value:function(){return this.playback.getPlaybackType()}},{key:"isDvrEnabled",value:function(){return!!this.playback.dvrEnabled}},{key:"isDvrInUse",value:function(){return!!this.dvrInUse}},{key:"destroy",value:function(){this.disableResizeObserver(),this.trigger(Ee.CONTAINER_DESTROYED,this,this.name),this.stopListening(),this.plugins.forEach((function(e){return e.destroy()})),this.$el.remove(),this.undelegateEvents()}},{key:"setStyle",value:function(e){this.$el.css(e)}},{key:"ready",value:function(){this.isReady=!0,this.trigger(Ee.CONTAINER_READY,this.name)}},{key:"isPlaying",value:function(){return this.playback.isPlaying()}},{key:"getStartTimeOffset",value:function(){return this.playback.getStartTimeOffset()}},{key:"getCurrentTime",value:function(){return this.currentTime}},{key:"getDuration",value:function(){return this.playback.getDuration()}},{key:"error",value:function(e){this.isReady||this.ready(),this.trigger(Ee.CONTAINER_ERROR,e,this.name)}},{key:"loadedMetadata",value:function(e){this.trigger(Ee.CONTAINER_LOADEDMETADATA,e)}},{key:"timeUpdated",value:function(e){this.currentTime=e.current,this.trigger(Ee.CONTAINER_TIMEUPDATE,e,this.name)}},{key:"onProgress",value:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.trigger.apply(this,[Ee.CONTAINER_PROGRESS].concat(t,[this.name]))}},{key:"playing",value:function(){this.trigger(Ee.CONTAINER_PLAY,this.name,this.actionsMetadata.playEvent||{}),this.actionsMetadata.playEvent={}}},{key:"paused",value:function(){this.trigger(Ee.CONTAINER_PAUSE,this.name,this.actionsMetadata.pauseEvent||{}),this.actionsMetadata.pauseEvent={}}},{key:"stopped",value:function(){this.trigger(Ee.CONTAINER_STOP,this.actionsMetadata.stopEvent||{}),this.actionsMetadata.stopEvent={}}},{key:"play",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.actionsMetadata.playEvent=e,this.playback.play(e)}},{key:"stop",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.actionsMetadata.stopEvent=e,this.playback.stop(e),this.currentTime=0}},{key:"switchAudioTrack",value:function(e){this.playback.switchAudioTrack(e)}},{key:"pause",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.actionsMetadata.pauseEvent=e,this.playback.pause(e)}},{key:"onEnded",value:function(){this.trigger(Ee.CONTAINER_ENDED,this,this.name),this.currentTime=0}},{key:"clicked",value:function(){var e=this;this.options.chromeless&&!this.options.allowUserInteraction||(this.clickTimer=setTimeout((function(){e.clickTimer&&e.trigger(Ee.CONTAINER_CLICK,e,e.name)}),this.clickDelay))}},{key:"cancelClicked",value:function(){clearTimeout(this.clickTimer),this.clickTimer=null}},{key:"dblClicked",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||(this.cancelClicked(),this.trigger(Ee.CONTAINER_DBLCLICK,this,this.name))}},{key:"dblTap",value:function(e){var t=this;this.options.chromeless&&!this.options.allowUserInteraction||this.dblTapHandler.handle(e,(function(){t.cancelClicked(),t.trigger(Ee.CONTAINER_DBLCLICK,t,t.name)}))}},{key:"onContextMenu",value:function(e){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Ee.CONTAINER_CONTEXTMENU,e,this.name)}},{key:"seek",value:function(e){this.playback.seek(e)}},{key:"onSeek",value:function(e){this.trigger(Ee.CONTAINER_SEEK,e,this.name)}},{key:"onSeeked",value:function(){this.trigger(Ee.CONTAINER_SEEKED,this.name)}},{key:"seekPercentage",value:function(e){var t=this.getDuration();if(e>=0&&e<=100){var i=t*(e/100);this.seek(i)}}},{key:"setVolume",value:function(e){this.volume=parseFloat(e),this.trigger(Ee.CONTAINER_VOLUME,this.volume,this.name),this.playback.volume(this.volume)}},{key:"fullscreen",value:function(){this.trigger(Ee.CONTAINER_FULLSCREEN,this.name)}},{key:"onBuffering",value:function(){this.trigger(Ee.CONTAINER_STATE_BUFFERING,this.name)}},{key:"bufferfull",value:function(){this.trigger(Ee.CONTAINER_STATE_BUFFERFULL,this.name)}},{key:"onEnterPiP",value:function(){this.trigger(Ee.CONTAINER_PIP_ENTER,this.name)}},{key:"onExitPiP",value:function(){this.trigger(Ee.CONTAINER_PIP_EXIT,this.name)}},{key:"addPlugin",value:function(e){this.plugins.push(e)}},{key:"hasPlugin",value:function(e){return!!this.getPlugin(e)}},{key:"getPlugin",value:function(e){return this.plugins.filter((function(t){return t.name===e}))[0]}},{key:"mouseEnter",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Ee.CONTAINER_MOUSE_ENTER)}},{key:"mouseLeave",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Ee.CONTAINER_MOUSE_LEAVE)}},{key:"mouseUp",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Ee.CONTAINER_MOUSE_UP)}},{key:"mouseDown",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Ee.CONTAINER_MOUSE_DOWN)}},{key:"enterPiP",value:function(){this.playback.enterPiP()}},{key:"exitPiP",value:function(){this.playback.exitPiP()}},{key:"settingsUpdate",value:function(){this.settings=this.playback.settings,this.trigger(Ee.CONTAINER_SETTINGSUPDATE)}},{key:"highDefinitionUpdate",value:function(e){this.trigger(Ee.CONTAINER_HIGHDEFINITIONUPDATE,e)}},{key:"isHighDefinitionInUse",value:function(){return this.playback.isHighDefinitionInUse()}},{key:"disableMediaControl",value:function(){this.mediaControlDisabled||(this.mediaControlDisabled=!0,this.trigger(Ee.CONTAINER_MEDIACONTROL_DISABLE))}},{key:"enableMediaControl",value:function(){this.mediaControlDisabled&&(this.mediaControlDisabled=!1,this.trigger(Ee.CONTAINER_MEDIACONTROL_ENABLE))}},{key:"updateStyle",value:function(){!this.options.chromeless||this.options.allowUserInteraction?this.$el.removeClass("chromeless"):this.$el.addClass("chromeless")}},{key:"enableResizeObserver",value:function(){var e=this;this.disableResizeObserver(),this.resizeObserverInterval=setInterval((function(){return e.checkResize()}),500)}},{key:"disableResizeObserver",value:function(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval)}},{key:"checkResize",value:function(){var e={width:this.el.clientWidth,height:this.el.clientHeight},t=this.currentSize||{},i=t.width;(t.height!==e.height||i!==e.width)&&(this.currentSize=e,this.trigger(Ee.CONTAINER_RESIZE,e))}},{key:"onResize",value:function(e){return this.playback.resize(e),this}},{key:"configure",value:function(e,t){this.trigger(Ee.CONTAINER_OPTIONS_WILL_CHANGE,t),this._options=M.extend(!0,this._options,e),this.updateStyle(),this.playback.configure(this.options),this.trigger(Ee.CONTAINER_OPTIONS_CHANGE)}},{key:"render",value:function(){var e=Ce(".container[data-container] {\n position: absolute;\n background-color: black;\n height: 100%;\n width: 100%;\n max-width: 100%; }\n .container[data-container] .chromeless {\n cursor: default; }\n\n[data-player]:not(.nocursor) .container[data-container]:not(.chromeless).pointer-enabled {\n cursor: pointer; }\n".toString(),{baseUrl:this.options.baseUrl});return this.$el.append(e[0]),this.$el.append(this.playback.render().el),this.updateStyle(),this.checkResize(),this.enableResizeObserver(),this}}])}(Oe);Object.assign(Ne.prototype,Me);var Ue=function(e){function t(e,i,s){var r;return p(this,t),(r=g(this,t,[e])).settings={},r._i18n=i,r.playerError=s,r._consented=!1,r}return S(t,e),v(t,[{key:"isAudioOnly",get:function(){return!1}},{key:"isAdaptive",get:function(){return!1}},{key:"ended",get:function(){return!1}},{key:"i18n",get:function(){return this._i18n}},{key:"buffering",get:function(){return!1}},{key:"latency",get:function(){return null}},{key:"currentProgramDateTime",get:function(){return null}},{key:"isPiPActive",get:function(){return!1}},{key:"consent",value:function(e){"function"==typeof e&&e()}},{key:"play",value:function(){}},{key:"pause",value:function(){}},{key:"stop",value:function(){}},{key:"enterPiP",value:function(){}},{key:"exitPiP",value:function(){}},{key:"seek",value:function(e){}},{key:"seekPercentage",value:function(e){}},{key:"getStartTimeOffset",value:function(){return 0}},{key:"getDuration",value:function(){return 0}},{key:"isPlaying",value:function(){return!1}},{key:"isReady",get:function(){return!1}},{key:"hasClosedCaptionsTracks",get:function(){return this.closedCaptionsTracks.length>0}},{key:"closedCaptionsTracks",get:function(){return[]}},{key:"closedCaptionsTrackId",get:function(){return-1},set:function(e){}},{key:"audioTracks",get:function(){return[]}},{key:"currentAudioTrack",get:function(){return null}},{key:"switchAudioTrack",value:function(e){}},{key:"getPlaybackType",value:function(){return t.NO_OP}},{key:"isHighDefinitionInUse",value:function(){return!1}},{key:"mute",value:function(){}},{key:"unmute",value:function(){}},{key:"volume",value:function(e){}},{key:"configure",value:function(e){this._options=M.extend(!0,this._options,e)}},{key:"attemptAutoPlay",value:function(){var e=this;this.canAutoPlay((function(t,i){t&&e.play()}))}},{key:"canAutoPlay",value:function(e){e(!0,null)}},{key:"onResize",value:function(e){return this.trigger(Ee.PLAYBACK_RESIZE,e),this}}])}(Oe);Object.assign(Ue.prototype,Me),Ue.extend=function(e){return Q(Ue,e)},Ue.canPlay=function(e,t){return!1},Ue.VOD="vod",Ue.AOD="aod",Ue.LIVE="live",Ue.NO_OP="no_op",Ue.type="playback";var Be=function(e){function t(e,i,s,r){var n;return p(this,t),(n=g(this,t,[e]))._i18n=s,n.loader=i,n.playerError=r,n}return S(t,e),v(t,[{key:"options",get:function(){return this._options},set:function(e){this._options=e}},{key:"createContainers",value:function(){var e=this;return M.Deferred((function(t){t.resolve(e.options.sources.map((function(t){return e.createContainer(t)})))}))}},{key:"findPlaybackPlugin",value:function(e,t){return this.loader.playbackPlugins.filter((function(i){return i.canPlay(e,t)}))[0]}},{key:"createContainer",value:function(e){var t=null,i=this.options.mimeType;"object"===C(e)?(t=e.source.toString(),e.mimeType&&(i=e.mimeType)):t=e.toString(),t.match(/^\/\//)&&(t=window.location.protocol+t);var s=_(_({},this.options),{},{src:t,mimeType:i}),r=this.findPlaybackPlugin(t,i),n=r?new r(s,this._i18n,this.playerError):new Ue;s=_(_({},s),{},{playback:n});var a=new Ne(s,this._i18n,this.playerError),o=M.Deferred();return o.promise(a),this.addContainerPlugins(a),this.listenToOnce(a,Ee.CONTAINER_READY,(function(){return o.resolve(a)})),a}},{key:"addContainerPlugins",value:function(e){this.loader.containerPlugins.forEach((function(t){e.addPlugin(new t(e))}))}}])}(Te),$e=function(e){function t(e){var i;return p(this,t),(i=g(this,t,[e])).playerError=new xe(e,i),i.configureDomRecycler(),i.firstResize=!0,i.styleRendered=!1,i.plugins=[],i.containers=[],i._boundFullscreenHandler=function(){return i.handleFullscreenChange()},i._boundHandleWindowResize=function(e){return i.handleWindowResize(e)},M(document).bind("fullscreenchange",i._boundFullscreenHandler),M(document).bind("MSFullscreenChange",i._boundFullscreenHandler),M(document).bind("mozfullscreenchange",i._boundFullscreenHandler),K.isMobile&&M(window).bind("resize",i._boundHandleWindowResize),i}return S(t,e),v(t,[{key:"events",get:function(){return{webkitfullscreenchange:"handleFullscreenChange",mousemove:"onMouseMove",mouseleave:"onMouseLeave"}}},{key:"attributes",get:function(){return{"data-player":"",tabindex:9999}}},{key:"isReady",get:function(){return!!this.ready}},{key:"i18n",get:function(){return this.getPlugin("strings")||{t:function(e){return e}}}},{key:"mediaControl",get:function(){return this._mediaControl||(this._mediaControl=this.getPlugin("media_control"))||this.dummyMediaControl}},{key:"dummyMediaControl",get:function(){return this._dummyMediaControl||(this._dummyMediaControl=new Fe(this)),this._dummyMediaControl}},{key:"activeContainer",get:function(){return this._activeContainer},set:function(e){this._activeContainer=e,this.trigger(Ee.CORE_ACTIVE_CONTAINER_CHANGED,this._activeContainer)}},{key:"activePlayback",get:function(){return this.activeContainer&&this.activeContainer.playback}},{key:"activePlaybackEl",get:function(){if(this.activePlayback)return this.activePlayback.$el&&this.activePlayback.$el.find("video")[0]||this.activePlayback.el}},{key:"configureDomRecycler",value:function(){var e=this.options&&this.options.playback&&this.options.playback.recycleVideo;ae.configure({recycleVideo:e})}},{key:"createContainers",value:function(e){this.defer=M.Deferred(),this.defer.promise(this),this.containerFactory=new Be(e,e.loader,this.i18n,this.playerError),this.prepareContainers()}},{key:"prepareContainers",value:function(){var e=this;this.containerFactory.createContainers().then((function(t){return e.setupContainers(t)})).then((function(t){return e.resolveOnContainersReady(t)}))}},{key:"updateSize",value:function(){this.isFullscreen()?this.setFullscreen():this.setPlayerSize()}},{key:"setFullscreen",value:function(){K.isiOS||(this.$el.addClass("fullscreen"),this.$el.removeAttr("style"),this.previousSize={width:this.options.width,height:this.options.height},this.currentSize={width:M(window).width(),height:M(window).height()})}},{key:"setPlayerSize",value:function(){this.$el.removeClass("fullscreen"),this.currentSize=this.previousSize,this.previousSize={width:M(window).width(),height:M(window).height()},this.resize(this.currentSize)}},{key:"onResize",value:function(e){return this.previousSize={width:this.options.width,height:this.options.height},this.options.width=e.width,this.options.height=e.height,this.currentSize=e,this.triggerResize(this.currentSize),this}},{key:"enableResizeObserver",value:function(){var e=this;this.disableResizeObserver();this.resizeObserverInterval=setInterval((function(){var t,i,s=null!==(t=e.el.clientWidth)&&void 0!==t?t:e.options.width,r=null!==(i=e.el.clientHeight)&&void 0!==i?i:e.options.height;e.triggerResize({width:s,height:r})}),500)}},{key:"triggerResize",value:function(e){(this.firstResize||this.oldHeight!==e.height||this.oldWidth!==e.width)&&(this.oldHeight=e.height,this.oldWidth=e.width,this.computedSize=e,this.firstResize=!1,this.trigger(Ee.CORE_RESIZE,e))}},{key:"disableResizeObserver",value:function(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval),this.resizeObserverInterval=null}},{key:"resolveOnContainersReady",value:function(e){var t=this;M.when.apply(M,e).done((function(){t.defer.resolve(t),t.ready=!0,t.trigger(Ee.CORE_READY)}))}},{key:"addPlugin",value:function(e){this.plugins.push(e)}},{key:"hasPlugin",value:function(e){return!!this.getPlugin(e)}},{key:"getPlugin",value:function(e){return this.plugins.filter((function(t){return t.name===e}))[0]}},{key:"load",value:function(e,t){this.options.mimeType=t,e=e&&e.constructor===Array?e:[e],this.options.sources=e,this.containers.forEach((function(e){return e.destroy()})),this.containerFactory.options=M.extend(!0,this.options,{sources:e}),this.prepareContainers()}},{key:"destroy",value:function(){this.disableResizeObserver(),this.containers.forEach((function(e){return e.destroy()})),this.plugins.forEach((function(e){return e.destroy()})),this.$el.remove(),M(document).unbind("fullscreenchange",this._boundFullscreenHandler),M(document).unbind("MSFullscreenChange",this._boundFullscreenHandler),M(document).unbind("mozfullscreenchange",this._boundFullscreenHandler),K.isMobile&&M(window).unbind("resize",this._boundHandleWindowResize),this.stopListening(),this.undelegateEvents()}},{key:"handleFullscreenChange",value:function(){this.trigger(Ee.CORE_FULLSCREEN,this.isFullscreen()),this.updateSize()}},{key:"handleWindowResize",value:function(e){var t,i,s=window.innerWidth>window.innerHeight?"landscape":"portrait";if(this._screenOrientation!==s){this._screenOrientation=s;var r=null!==(t=this.el.clientWidth)&&void 0!==t?t:this.options.width,n=null!==(i=this.el.clientHeight)&&void 0!==i?i:this.options.height;this.triggerResize({width:r,height:n}),this.trigger(Ee.CORE_SCREEN_ORIENTATION_CHANGED,{event:e,orientation:this._screenOrientation})}}},{key:"removeContainer",value:function(e){this.stopListening(e),this.containerFactory.stopListening(e),this.containers=this.containers.filter((function(t){return t!==e}))}},{key:"setupContainer",value:function(e){this.listenTo(e,Ee.CONTAINER_DESTROYED,this.removeContainer),this.containers.push(e)}},{key:"setupContainers",value:function(e){return e.forEach(this.setupContainer.bind(this)),this.trigger(Ee.CORE_CONTAINERS_CREATED),this.renderContainers(),this.activeContainer=e[0],this.render(),this.appendToParent(),this.containers}},{key:"renderContainers",value:function(){var e=this;this.containers.forEach((function(t){return e.el.appendChild(t.render().el)}))}},{key:"createContainer",value:function(e,t){var i=this.containerFactory.createContainer(e,t);return this.setupContainer(i),this.el.appendChild(i.render().el),i}},{key:"getCurrentContainer",value:function(){return this.activeContainer}},{key:"getCurrentPlayback",value:function(){return this.activePlayback}},{key:"getPlaybackType",value:function(){return this.activeContainer&&this.activeContainer.getPlaybackType()}},{key:"isFullscreen",value:function(){var e=Z.fullscreenElement();return e&&e===this.el||e&&e===this.activePlaybackEl||this.activePlaybackEl&&this.activePlaybackEl.webkitDisplayingFullscreen||!1}},{key:"toggleFullscreen",value:function(){var e=this;if(this.isFullscreen()){var t=K.isiOS?this.activePlaybackEl:document;Z.cancelFullscreen(t),!K.isiOS&&this.$el.removeClass("fullscreen nocursor")}else{var i=K.isiOS?this.activePlaybackEl:this.el;if(!i)return;K.isSafari||K.isiOS?Z.requestFullscreen(i):Z.requestFullscreen(i).then((function(e){return e}),(function(t){return setTimeout((function(){if(!e.isFullscreen())throw new ReferenceError(t)}),600)})),!K.isiOS&&this.$el.addClass("fullscreen")}}},{key:"onMouseMove",value:function(e){this.trigger(Ee.CORE_MOUSE_MOVE,e)}},{key:"onMouseLeave",value:function(e){this.trigger(Ee.CORE_MOUSE_LEAVE,e)}},{key:"configure",value:function(e){var t=this,i=M.extend(!0,{},this._options);this.trigger(Ee.CORE_OPTIONS_WILL_CHANGE,i),this._options=M.extend(!0,this._options,e),this.configureDomRecycler();var s=e.source||e.sources;s&&this.load(s,e.mimeType||this.options.mimeType),this.trigger(Ee.CORE_OPTIONS_CHANGE,e),this.containers.forEach((function(e){return e.configure(t.options,i)}))}},{key:"appendToParent",value:function(){!(this.$el.parent()&&this.$el.parent().length)&&this.$el.appendTo(this.options.parentElement)}},{key:"appendStyles",value:function(){if(!this.styleRendered){var e=Ce('[data-player] {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -o-user-select: none;\n user-select: none;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n transform: translate3d(0, 0, 0);\n position: relative;\n margin: 0;\n padding: 0;\n border: 0;\n font-style: normal;\n font-weight: normal;\n text-align: center;\n overflow: hidden;\n font-size: 100%;\n font-family: "Roboto", "Open Sans", Arial, sans-serif;\n text-shadow: 0 0 0;\n box-sizing: border-box; }\n [data-player]:focus {\n outline: 0; }\n [data-player] * {\n box-sizing: inherit; }\n [data-player] > * {\n float: none;\n max-width: none; }\n [data-player] > div {\n display: block; }\n [data-player].fullscreen {\n width: 100% !important;\n height: 100% !important;\n top: 0;\n left: 0; }\n [data-player].nocursor {\n cursor: none; }\n\n.clappr-style {\n display: none !important; }\n'.toString(),{baseUrl:this.options.baseUrl});if(this.$el.append(e[0]),this.options.includeResetStyle){var t=Ce('[data-player] div, [data-player] span, [data-player] applet, [data-player] object, [data-player] iframe,\n[data-player] h1, [data-player] h2, [data-player] h3, [data-player] h4, [data-player] h5, [data-player] h6, [data-player] p, [data-player] blockquote, [data-player] pre,\n[data-player] a, [data-player] abbr, [data-player] acronym, [data-player] address, [data-player] big, [data-player] cite, [data-player] code,\n[data-player] del, [data-player] dfn, [data-player] em, [data-player] img, [data-player] ins, [data-player] kbd, [data-player] q, [data-player] s, [data-player] samp,\n[data-player] small, [data-player] strike, [data-player] strong, [data-player] sub, [data-player] sup, [data-player] tt, [data-player] var,\n[data-player] b, [data-player] u, [data-player] i, [data-player] center,\n[data-player] dl, [data-player] dt, [data-player] dd, [data-player] ol, [data-player] ul, [data-player] li,\n[data-player] fieldset, [data-player] form, [data-player] label, [data-player] legend,\n[data-player] table, [data-player] caption, [data-player] tbody, [data-player] tfoot, [data-player] thead, [data-player] tr, [data-player] th, [data-player] td,\n[data-player] article, [data-player] aside, [data-player] canvas, [data-player] details, [data-player] embed,\n[data-player] figure, [data-player] figcaption, [data-player] footer, [data-player] header, [data-player] hgroup,\n[data-player] menu, [data-player] nav, [data-player] output, [data-player] ruby, [data-player] section, [data-player] summary,\n[data-player] time, [data-player] mark, [data-player] audio, [data-player] video {\n margin: 0;\n padding: 0;\n border: 0;\n font: inherit;\n font-size: 100%;\n vertical-align: baseline; }\n\n[data-player] table {\n border-collapse: collapse;\n border-spacing: 0; }\n\n[data-player] caption, [data-player] th, [data-player] td {\n text-align: left;\n font-weight: normal;\n vertical-align: middle; }\n\n[data-player] q, [data-player] blockquote {\n quotes: none; }\n [data-player] q:before, [data-player] q:after, [data-player] blockquote:before, [data-player] blockquote:after {\n content: "";\n content: none; }\n\n[data-player] a img {\n border: none; }\n'.toString(),{baseUrl:this.options.baseUrl});this.$el.append(t[0])}this.styleRendered=!0}}},{key:"render",value:function(){this.appendStyles(),this.options.width=this.options.width||this.$el.width(),this.options.height=this.options.height||this.$el.height();var e={width:this.options.width,height:this.options.height};return this.previousSize=this.currentSize=this.computedSize=e,this.updateSize(),this.enableResizeObserver(),this}}])}(Oe);Object.assign($e.prototype,Me);var Ge,Ke,Ve=function(e){function t(e){var i;return p(this,t),(i=g(this,t,[e.options])).player=e,i}return S(t,e),v(t,[{key:"loader",get:function(){return this.player.loader}},{key:"create",value:function(){return this.options.loader=this.loader,this.core=new $e(this.options),this.addCorePlugins(),this.core.createContainers(this.options),this.core}},{key:"addCorePlugins",value:function(){var e=this;return this.loader.corePlugins.forEach((function(t){var i=new t(e.core);e.core.addPlugin(i),e.setupExternalInterface(i)})),this.core}},{key:"setupExternalInterface",value:function(e){var t=e.getExternalInterface();for(var i in t)this.player[i]=t[i].bind(e)}}])}(Te),He=/(\d+)(?:\.(\d+))?(?:\.(\d+))?/,Ye=function(){function e(t,i,s){p(this,e),this.major=parseInt(t||0,10),this.minor=parseInt(i||0,10),this.patch=parseInt(s||0,10)}return v(e,[{key:"compare",value:function(e){var t=this.major-e.major;return t=(t=t||this.minor-e.minor)||this.patch-e.patch}},{key:"inc",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"patch";return void 0!==this[e]&&(this[e]+=1),this}},{key:"satisfies",value:function(e,t){return this.compare(e)>=0&&(!t||this.compare(t)<0)}},{key:"toString",value:function(){return"".concat(this.major,".").concat(this.minor,".").concat(this.patch)}}],[{key:"parse",value:function(){var t=R((arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").match(He)||[],4),i=t[1],s=t[2],r=t[3];return void 0===i?null:new e(i,s,r)}}])}(),je=function(e,t){return e&&t?Object.entries(e).filter((function(e){return R(e,2)[1].type===t})).reduce((function(e,t){var i=R(t,2),s=i[0],r=i[1];return e[s]=r,e}),{}):{}},We=(Ge={plugins:{},playbacks:[]},Ke="0.12.0",function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;p(this,e),this.playerId=i,this.playbackPlugins=D(Ge.playbacks);var s=e.registeredPlugins,r=s.core,n=s.container;this.containerPlugins=Object.values(n),this.corePlugins=Object.values(r),Array.isArray(t)||this.validateExternalPluginsType(t),this.addExternalPlugins(t)}return v(e,[{key:"groupPluginsByType",value:function(e){return Array.isArray(e)&&(e=e.reduce((function(e,t){return e[t.type]||(e[t.type]=[]),e[t.type].push(t),e}),{})),e}},{key:"removeDups",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=e.reduceRight((function(e,i){return e[i.prototype.name]&&t||(e[i.prototype.name]&&delete e[i.prototype.name],e[i.prototype.name]=i),e}),Object.create(null)),s=[];for(var r in i)s.unshift(i[r]);return s}},{key:"addExternalPlugins",value:function(t){var i="boolean"!=typeof t.loadExternalPluginsFirst||t.loadExternalPluginsFirst,s="boolean"!=typeof t.loadExternalPlaybacksFirst||t.loadExternalPlaybacksFirst;if((t=this.groupPluginsByType(t)).playback){var r=t.playback.filter((function(t){return e.checkVersionSupport(t),!0}));this.playbackPlugins=s?this.removeDups(r.concat(this.playbackPlugins)):this.removeDups(this.playbackPlugins.concat(r),!0)}if(t.container){var n=t.container.filter((function(t){return e.checkVersionSupport(t),!0}));this.containerPlugins=i?this.removeDups(n.concat(this.containerPlugins)):this.removeDups(this.containerPlugins.concat(n),!0)}if(t.core){var a=t.core.filter((function(t){return e.checkVersionSupport(t),!0}));this.corePlugins=i?this.removeDups(a.concat(this.corePlugins)):this.removeDups(this.corePlugins.concat(a),!0)}}},{key:"validateExternalPluginsType",value:function(e){["playback","container","core"].forEach((function(t){(e[t]||[]).forEach((function(e){var i="external "+e.type+" plugin on "+t+" array";if(e.type!==t)throw new ReferenceError(i)}))}))}}],[{key:"registeredPlaybacks",get:function(){return D(Ge.playbacks)}},{key:"registeredPlugins",get:function(){var e=Ge.plugins;return{core:je(e,"core"),container:je(e,"container")}}},{key:"checkVersionSupport",value:function(e){var t=e.prototype,i=t.supportedVersion,s=t.name;if(!i||!i.min)return pe.warn("Loader","missing version information for ".concat(s)),!1;var r=i.max?Ye.parse(i.max):Ye.parse(i.min).inc("minor"),n=Ye.parse(i.min);return!!Ye.parse(Ke).satisfies(n,r)||(pe.warn("Loader","unsupported plugin ".concat(s,": Clappr version ").concat(Ke," does not match required range [").concat(n,",").concat(r,")")),!1)}},{key:"registerPlugin",value:function(t){if(!t||!t.prototype.name)return pe.warn("Loader","missing information to register plugin: ".concat(t)),!1;e.checkVersionSupport(t);var i=Ge.plugins;if(!i)return!1;var s=i[t.prototype.name];return s&&pe.warn("Loader","overriding plugin entry: ".concat(t.prototype.name," - ").concat(s)),i[t.prototype.name]=t,!0}},{key:"registerPlayback",value:function(t){if(!t||!t.prototype.name)return!1;e.checkVersionSupport(t);var i=Ge.playbacks,s=i.findIndex((function(e){return e.prototype.name===t.prototype.name}));if(s>=0){var r=i[s];i.splice(s,1),pe.warn("Loader","overriding playback entry: ".concat(r.name," - ").concat(r))}return Ge.playbacks=[t].concat(D(i)),!0}},{key:"unregisterPlugin",value:function(e){if(!e)return!1;var t=Ge.plugins;return!!t[e]&&(delete t[e],!0)}},{key:"unregisterPlayback",value:function(e){if(!e)return!1;var t=Ge.playbacks,i=t.findIndex((function(t){return t.prototype.name===e}));return!(i<0||(t.splice(i,1),Ge.playbacks=t,0))}},{key:"clearPlugins",value:function(){Ge.plugins={}}},{key:"clearPlaybacks",value:function(){Ge.playbacks=[]}}])}()),qe=se().replace(/\/[^/]+$/,""),ze=function(e){function t(e){var i;p(this,t),i=g(this,t,[e]);var s={playerId:te(""),persistConfig:!0,width:640,height:360,baseUrl:qe,allowUserInteraction:K.isMobile,includeResetStyle:!0,playback:{recycleVideo:!0}};i._options=M.extend(!0,s,e),i.options.sources=i._normalizeSources(e),i.options.chromeless||(i.options.allowUserInteraction=!0),i.options.allowUserInteraction||(i.options.disableKeyboardShortcuts=!0),i._registerOptionEventListeners(i.options.events),i._coreFactory=new Ve(i);var r=i._getParentElement(i.options);return r&&i.attachTo(r),i}return S(t,e),v(t,[{key:"loader",get:function(){return this._loader||(this._loader=new We(this.options.plugins||{},this.options.playerId)),this._loader},set:function(e){this._loader=e}},{key:"ended",get:function(){return this.core.activeContainer.ended}},{key:"buffering",get:function(){return this.core.activeContainer.buffering}},{key:"isReady",get:function(){return!!this._ready}},{key:"eventsMapping",get:function(){return{onReady:Ee.PLAYER_READY,onResize:Ee.PLAYER_RESIZE,onPlay:Ee.PLAYER_PLAY,onPause:Ee.PLAYER_PAUSE,onStop:Ee.PLAYER_STOP,onEnded:Ee.PLAYER_ENDED,onSeek:Ee.PLAYER_SEEK,onError:Ee.PLAYER_ERROR,onTimeUpdate:Ee.PLAYER_TIMEUPDATE,onVolumeUpdate:Ee.PLAYER_VOLUMEUPDATE,onSubtitleAvailable:Ee.PLAYER_SUBTITLE_AVAILABLE}}},{key:"_getParentElement",value:function(e){var t=e.parentId,i=e.parent;return t?document.querySelector(t):i}},{key:"attachTo",value:function(e){return this.options.parentElement=e,this.core=this._coreFactory.create(),this._addEventListeners(),this}},{key:"_addEventListeners",value:function(){return this.core.isReady?this._onReady():this.listenToOnce(this.core,Ee.CORE_READY,this._onReady),this.listenTo(this.core,Ee.CORE_ACTIVE_CONTAINER_CHANGED,this._containerChanged),this.listenTo(this.core,Ee.CORE_FULLSCREEN,this._onFullscreenChange),this.listenTo(this.core,Ee.CORE_RESIZE,this._onResize),this}},{key:"_addContainerEventListeners",value:function(){var e=this.core.activeContainer;return e&&(this.listenTo(e,Ee.CONTAINER_PLAY,this._onPlay),this.listenTo(e,Ee.CONTAINER_PAUSE,this._onPause),this.listenTo(e,Ee.CONTAINER_STOP,this._onStop),this.listenTo(e,Ee.CONTAINER_ENDED,this._onEnded),this.listenTo(e,Ee.CONTAINER_SEEK,this._onSeek),this.listenTo(e,Ee.CONTAINER_ERROR,this._onError),this.listenTo(e,Ee.CONTAINER_TIMEUPDATE,this._onTimeUpdate),this.listenTo(e,Ee.CONTAINER_VOLUME,this._onVolumeUpdate),this.listenTo(e,Ee.CONTAINER_SUBTITLE_AVAILABLE,this._onSubtitleAvailable)),this}},{key:"_registerOptionEventListeners",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(t).length>0&&Object.keys(i).forEach((function(t){var s=e.eventsMapping[t];s&&e.off(s,i[t])})),Object.keys(t).forEach((function(i){var s=e.eventsMapping[i];if(s){var r=t[i];(r="function"==typeof r&&r)&&e.on(s,r)}})),this}},{key:"_containerChanged",value:function(){this.stopListening(),this._addEventListeners()}},{key:"_onReady",value:function(){this._ready=!0,this._addContainerEventListeners(),this.trigger(Ee.PLAYER_READY)}},{key:"_onFullscreenChange",value:function(e){this.trigger(Ee.PLAYER_FULLSCREEN,e)}},{key:"_onVolumeUpdate",value:function(e){this.trigger(Ee.PLAYER_VOLUMEUPDATE,e)}},{key:"_onSubtitleAvailable",value:function(){this.trigger(Ee.PLAYER_SUBTITLE_AVAILABLE)}},{key:"_onResize",value:function(e){this.trigger(Ee.PLAYER_RESIZE,e)}},{key:"_onPlay",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.trigger(Ee.PLAYER_PLAY,t)}},{key:"_onPause",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.trigger(Ee.PLAYER_PAUSE,t)}},{key:"_onStop",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.trigger(Ee.PLAYER_STOP,this.getCurrentTime(),e)}},{key:"_onEnded",value:function(){this.trigger(Ee.PLAYER_ENDED)}},{key:"_onSeek",value:function(e){this.trigger(Ee.PLAYER_SEEK,e)}},{key:"_onTimeUpdate",value:function(e){this.trigger(Ee.PLAYER_TIMEUPDATE,e)}},{key:"_onError",value:function(e){this.trigger(Ee.PLAYER_ERROR,e)}},{key:"_normalizeSources",value:function(e){var t=e.sources||(void 0!==e.source?[e.source]:[]);return 0===t.length?[{source:"",mimeType:""}]:t}},{key:"resize",value:function(e){return this.core.resize(e),this}},{key:"load",value:function(e,t,i){return void 0!==i&&this.configure({autoPlay:!!i}),this.core.load(e,t),this}},{key:"destroy",value:function(){return this.stopListening(),this.core.destroy(),this}},{key:"consent",value:function(e){this.core.getCurrentPlayback().consent(e)}},{key:"play",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.core.activeContainer.play(e),this}},{key:"pause",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.core.activeContainer.pause(e),this}},{key:"stop",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.core.activeContainer.stop(e),this}},{key:"seek",value:function(e){return this.core.activeContainer.seek(e),this}},{key:"seekPercentage",value:function(e){return this.core.activeContainer.seekPercentage(e),this}},{key:"mute",value:function(){return this.core.activePlayback.mute(),this}},{key:"unmute",value:function(){return this.core.activePlayback.unmute(),this}},{key:"isPlaying",value:function(){return this.core.activeContainer.isPlaying()}},{key:"isDvrEnabled",value:function(){return this.core.activeContainer.isDvrEnabled()}},{key:"isDvrInUse",value:function(){return this.core.activeContainer.isDvrInUse()}},{key:"configure",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this._registerOptionEventListeners(e.events,this.options.events),this.core.configure(e),this}},{key:"getPlugin",value:function(e){return this.core.plugins.concat(this.core.activeContainer.plugins).filter((function(t){return t.name===e}))[0]}},{key:"getCurrentTime",value:function(){return this.core.activeContainer.getCurrentTime()}},{key:"getStartTimeOffset",value:function(){return this.core.activeContainer.getStartTimeOffset()}},{key:"getDuration",value:function(){return this.core.activeContainer.getDuration()}}])}(Te);Object.assign(ze.prototype,Me);var Xe=function(e){function t(e){var i;return p(this,t),(i=g(this,t,[e.options])).container=e,i.enabled=!0,i.bindEvents(),i}return S(t,e),v(t,[{key:"playerError",get:function(){return this.container.playerError}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.enabled=!0)}},{key:"disable",value:function(){this.enabled&&(this.stopListening(),this.enabled=!1)}},{key:"bindEvents",value:function(){}},{key:"destroy",value:function(){this.stopListening()}}])}(Te);Object.assign(Xe.prototype,Me),Xe.extend=function(e){return Q(Xe,e)},Xe.type="container";var Qe=function(e){function t(e){var i;return p(this,t),(i=g(this,t,[e.options])).core=e,i.enabled=!0,i.bindEvents(),i}return S(t,e),v(t,[{key:"playerError",get:function(){return this.core.playerError}},{key:"bindEvents",value:function(){}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.enabled=!0)}},{key:"disable",value:function(){this.enabled&&(this.stopListening(),this.enabled=!1)}},{key:"getExternalInterface",value:function(){return{}}},{key:"destroy",value:function(){this.stopListening()}}])}(Te);Object.assign(Qe.prototype,Me),Qe.extend=function(e){return Q(Qe,e)},Qe.type="core";var Ze=function(e){function t(e){var i;return p(this,t),(i=g(this,t,[e.options])).container=e,i.enabled=!0,i.bindEvents(),i}return S(t,e),v(t,[{key:"playerError",get:function(){return this.container.playerError}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.$el.show(),this.enabled=!0)}},{key:"disable",value:function(){this.stopListening(),this.$el.hide(),this.enabled=!1}},{key:"bindEvents",value:function(){}}])}(Oe);Object.assign(Ze.prototype,Me),Ze.extend=function(e){return Q(Ze,e)},Ze.type="container";var Je={mp4:["avc1.42E01E","avc1.58A01E","avc1.4D401E","avc1.64001E","mp4v.20.8","mp4v.20.240","mp4a.40.2"].map((function(e){return'video/mp4; codecs="'+e+', mp4a.40.2"'})),ogg:['video/ogg; codecs="theora, vorbis"','video/ogg; codecs="dirac"','video/ogg; codecs="theora, speex"'],"3gpp":['video/3gpp; codecs="mp4v.20.8, samr"'],webm:['video/webm; codecs="vp8, vorbis"'],mkv:['video/x-matroska; codecs="theora, vorbis"'],m3u8:["application/x-mpegurl"]};Je.ogv=Je.ogg,Je["3gp"]=Je["3gpp"];var et={wav:["audio/wav"],mp3:["audio/mp3",'audio/mpeg;codecs="mp3"'],aac:['audio/mp4;codecs="mp4a.40.5"'],oga:["audio/ogg"]},tt=Object.keys(et).reduce((function(e,t){return[].concat(D(e),D(et[t]))}),[]),it={code:"unknown",message:"unknown"},st=function(e){function t(){var e;p(this,t);for(var i=arguments.length,s=new Array(i),r=0;r<i;r++)s[r]=arguments[r];(e=g(this,t,[].concat(s)))._destroyed=!1,e._loadStarted=!1,e._isBuffering=!1,e._playheadMoving=!1,e._playheadMovingTimer=null,e._stopped=!1,e._ccTrackId=-1,e._playheadMovingCheckEnabled=!e.options.disablePlayheadMovingCheck,e._setupSrc(e.options.src),e._playheadMovingCheckInterval=e.options.playheadMovingCheckInterval||500,e.options.playback||(e.options.playback=e.options||{}),e.options.playback.disableContextMenu=e.options.playback.disableContextMenu||e.options.disableVideoTagContextMenu,e._minDvrSize=e.isValidMinimumDVRSizeConfig?e.minimumDVRSizeConfig:60;var n,a=e.options.playback,o=a.preload||(K.isSafari?"auto":e.options.preload);return e.options.poster&&("string"==typeof e.options.poster?n=e.options.poster:"string"==typeof e.options.poster.url&&(n=e.options.poster.url)),M.extend(!0,e.el,{muted:e.options.mute,defaultMuted:e.options.mute,loop:e.options.loop,poster:n,preload:o||"metadata",crossOrigin:a.crossOrigin,"x-webkit-playsinline":a.playInline}),(a.controls||e.options.useVideoTagDefaultControls)&&e.$el.attr("controls",""),a.playInline&&e.$el.attr({playsinline:"playsinline"}),a.crossOrigin&&e.$el.attr({crossorigin:a.crossOrigin}),e.settings={default:["seekbar"]},e.settings.left=["playpause","position","duration"],e.settings.right=["fullscreen","volume","hd-indicator"],a.externalTracks&&e._setupExternalTracks(a.externalTracks),e.options.autoPlay&&e.attemptAutoPlay(),e}return S(t,e),v(t,[{key:"name",get:function(){return"html5_video"}},{key:"supportedVersion",get:function(){return{min:"0.12.0"}}},{key:"tagName",get:function(){return this.isAudioOnly?"audio":"video"}},{key:"isAudioOnly",get:function(){var e=this.options.src,i=t._mimeTypesForUrl(e,et,this.options.mimeType);return this.options.playback&&this.options.playback.audioOnly||this.options.audioOnly||tt.indexOf(i[0])>=0}},{key:"attributes",get:function(){return{"data-html5-video":""}}},{key:"events",get:function(){return{canplay:"_onCanPlay",canplaythrough:"_handleBufferingEvents",durationchange:"_onDurationChange",ended:"_onEnded",error:"_onError",loadeddata:"_onLoadedData",loadedmetadata:"_onLoadedMetadata",pause:"_onPause",playing:"_onPlaying",progress:"_onProgress",seeking:"_onSeeking",seeked:"_onSeeked",stalled:"_handleBufferingEvents",timeupdate:"_onTimeUpdate",waiting:"_onWaiting",enterpictureinpicture:"_onEnterPiP",leavepictureinpicture:"_onExitPiP"}}},{key:"ended",get:function(){return this.el.ended}},{key:"buffering",get:function(){return this._isBuffering}},{key:"isPiPActive",get:function(){return this.el===document.pictureInPictureElement}},{key:"isLive",get:function(){return this.getPlaybackType()===Ue.LIVE}},{key:"dvrEnabled",get:function(){return this.getDuration()>=this._minDvrSize&&this.isLive}},{key:"minimumDVRSizeConfig",get:function(){return this.options.playback&&this.options.playback.minimumDvrSize}},{key:"isValidMinimumDVRSizeConfig",get:function(){return void 0!==this.minimumDVRSizeConfig&&"number"==typeof this.minimumDVRSizeConfig}},{key:"sourceMedia",get:function(){return this._src}},{key:"configure",value:function(e){I(t,"configure",this)([e]),this.el.loop=!!e.loop}},{key:"attemptAutoPlay",value:function(){var e=this;this.canAutoPlay((function(t,i){i&&pe.warn(e.name,"autoplay error.",{result:t,error:i}),t&&setTimeout((function(){return!e._destroyed&&e.play()}),0)}))}},{key:"canAutoPlay",value:function(e){if(this.options.disableCanAutoPlay)e(!0,null);else{var t={timeout:this.options.autoPlayTimeout||500,inline:this.options.playback.playInline||!1,muted:this.options.mute||!1};K.isMobile&&ae.options.recycleVideo&&(t.element=this.el),ne(e,t)}}},{key:"_setupExternalTracks",value:function(e){this._externalTracks=e.map((function(e){return{kind:e.kind||"subtitles",label:e.label,lang:e.lang,src:e.src}}))}},{key:"load",value:function(e){this._setupSrc(e)}},{key:"_setupSrc",value:function(e){this.el.src!==e&&(this._ccIsSetup=!1,this.el.src=e,this._src=this.el.src)}},{key:"_onLoadedMetadata",value:function(e){this._handleBufferingEvents(),this.trigger(Ee.PLAYBACK_LOADEDMETADATA,{duration:e.target.duration,data:e}),this._updateSettings();var t=void 0===this._options.autoSeekFromUrl||this._options.autoSeekFromUrl;this.getPlaybackType()!==Ue.LIVE&&t&&this._checkInitialSeek()}},{key:"_onDurationChange",value:function(){this._updateSettings(),this._onTimeUpdate(),this._onProgress()}},{key:"_updateSettings",value:function(){this.getPlaybackType()===Ue.VOD||this.getPlaybackType()===Ue.AOD?this.settings.left=["playpause","position","duration"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(Ee.PLAYBACK_SETTINGSUPDATE)}},{key:"isSeekEnabled",value:function(){return isFinite(this.getDuration())}},{key:"getPlaybackType",value:function(){var e="audio"===this.tagName?Ue.AOD:Ue.VOD;return[0,void 0,1/0].indexOf(this.el.duration)>=0?Ue.LIVE:e}},{key:"isHighDefinitionInUse",value:function(){return!1}},{key:"consent",value:function(e){var i=this;if(this.isPlaying()||this.el._consented)I(t,"consent",this)([e]);else{var s=function(){i.el.removeEventListener("loadedmetadata",s,!1),i.el.removeEventListener("error",s,!1),i.el._consented=!0,I(t,"consent",i)([e])};this.el.addEventListener("loadedmetadata",s,!1),this.el.addEventListener("error",s,!1),this.el.load()}}},{key:"play",value:function(){var e=this;this.trigger(Ee.PLAYBACK_PLAY_INTENT),this._stopped=!1,this._setupSrc(this._src),this._handleBufferingEvents();var t=this.el.play();return t&&t.catch&&t.catch((function(t){return pe.warn(e.name,"HTML5 play failed",t)})),t}},{key:"pause",value:function(){this.el.pause()}},{key:"stop",value:function(){this.pause(),this._stopped=!0,this.el.removeAttribute("src"),this.el.load(),this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(Ee.PLAYBACK_STOP)}},{key:"volume",value:function(e){0===e?(this.$el.attr({muted:"true"}),this.el.muted=!0):(this.$el.attr({muted:null}),this.el.muted=!1,this.el.volume=e/100)}},{key:"mute",value:function(){this.el.muted=!0}},{key:"unmute",value:function(){this.el.muted=!1}},{key:"isMuted",value:function(){return!0===this.el.muted||0===this.el.volume}},{key:"isPlaying",value:function(){return!this.el.paused&&!this.el.ended}},{key:"isReady",get:function(){return this._isReadyState}},{key:"_startPlayheadMovingChecks",value:function(){null===this._playheadMovingTimer&&this._playheadMovingCheckEnabled&&(this._playheadMovingTimeOnCheck=null,this._determineIfPlayheadMoving(),this._playheadMovingTimer=setInterval(this._determineIfPlayheadMoving.bind(this),this._playheadMovingCheckInterval))}},{key:"_stopPlayheadMovingChecks",value:function(){null!==this._playheadMovingTimer&&(clearInterval(this._playheadMovingTimer),this._playheadMovingTimer=null,this._playheadMoving=!1)}},{key:"_determineIfPlayheadMoving",value:function(){var e=this._playheadMovingTimeOnCheck,t=this.el.currentTime;this._playheadMoving=e!==t,this._playheadMovingTimeOnCheck=t,this._handleBufferingEvents()}},{key:"_onWaiting",value:function(){this._loadStarted=!0,this._handleBufferingEvents()}},{key:"_onLoadedData",value:function(){this._loadStarted=!0,this._handleBufferingEvents()}},{key:"_onCanPlay",value:function(){this._handleBufferingEvents()}},{key:"_onPlaying",value:function(){this._checkForClosedCaptions(),this._startPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(Ee.PLAYBACK_PLAY)}},{key:"_onPause",value:function(){this.dvrEnabled&&this._updateDvr(!0),this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(Ee.PLAYBACK_PAUSE)}},{key:"_onSeeking",value:function(){var e=this.getCurrentTime();this.dvrEnabled&&this._updateDvr(e<this.getDuration()-3),this.trigger(Ee.PLAYBACK_SEEK,e),this._handleBufferingEvents()}},{key:"_onSeeked",value:function(){this._handleBufferingEvents(),this.trigger(Ee.PLAYBACK_SEEKED)}},{key:"_onEnded",value:function(){this._handleBufferingEvents(),this.trigger(Ee.PLAYBACK_ENDED,this.name)}},{key:"_onEnterPiP",value:function(){this.trigger(Ee.PLAYBACK_PIP_ENTER,this.name)}},{key:"_onExitPiP",value:function(){this.trigger(Ee.PLAYBACK_PIP_EXIT,this.name)}},{key:"enterPiP",value:function(){var e=this;this.el.requestPictureInPicture().then((function(){pe.info(e.name,"enter PIP success")})).catch((function(t){pe.warn(e.name,"enter PIP failed",t)}))}},{key:"exitPiP",value:function(){var e=this;document.exitPictureInPicture().then((function(){pe.info(e.name,"exit PIP success")})).catch((function(t){pe.warn(e.name,"exit PIP failed",t)}))}},{key:"_handleBufferingEvents",value:function(){var e=this._loadStarted&&!this.el.ended&&!this._stopped,t=this.el.readyState<this.el.HAVE_FUTURE_DATA,i=!this.el.ended&&!this.el.paused&&!this._playheadMoving,s=e&&t;this._playheadMovingCheckEnabled&&(s=s||e&&i),this._isBuffering!==s&&(this._isBuffering=s,s?this.trigger(Ee.PLAYBACK_BUFFERING,this.name):this.trigger(Ee.PLAYBACK_BUFFERFULL,this.name))}},{key:"_onError",value:function(){var e=this.el.error||it,t=e.code,i=e.message,s=t===it.code,r=this.createError({code:t,description:i,raw:this.el.error,level:s?xe.Levels.WARN:xe.Levels.FATAL});s?pe.warn(this.name,"HTML5 unknown error: ",r):this.trigger(Ee.PLAYBACK_ERROR,r)}},{key:"destroy",value:function(){this._destroyed=!0,this._stopPlayheadMovingChecks(),this.handleTextTrackChange&&this.el.textTracks.removeEventListener("change",this.handleTextTrackChange),this.$el.off("contextmenu"),I(t,"destroy",this)([]),this.el.removeAttribute("src"),this.el.load(),this._src=null,ae.garbage(this.el)}},{key:"_updateDvr",value:function(e){this.trigger(Ee.PLAYBACK_DVR,e),this.trigger(Ee.PLAYBACK_STATS_ADD,{dvr:e})}},{key:"seek",value:function(e){e<0&&(pe.warn("Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point."),e=this.getDuration()),e+=this.el.seekable.start(0),this.el.currentTime=e}},{key:"seekPercentage",value:function(e){var t=this.el.duration*(e/100);this.seek(t)}},{key:"_checkInitialSeek",value:function(){var e=ee();0!==e&&this.seek(e)}},{key:"getCurrentTime",value:function(){return this.el.currentTime}},{key:"getDuration",value:function(){if(this.isLive){if(this.el.seekable.length>0)return this.el.seekable.end(0)-this.el.seekable.start(0);this._scheduleUpdateSettingsCheck()}return this.el.duration}},{key:"_scheduleUpdateSettingsCheck",value:function(){var e=this;this._updateSettingsCheckInFlight||(this._updateSettingsCheckInFlight=setTimeout((function(){e._updateSettings(),e._updateSettingsCheckInFlight=null}),1e3))}},{key:"_onTimeUpdate",value:function(){var e=this.isLive?this.getDuration():this.el.duration;this.trigger(Ee.PLAYBACK_TIMEUPDATE,{current:this.el.currentTime,total:e},this.name)}},{key:"_onProgress",value:function(){if(this.el.buffered.length){for(var e=[],t=0,i=0;i<this.el.buffered.length;i++)e=[].concat(D(e),[{start:this.el.buffered.start(i),end:this.el.buffered.end(i)}]),this.el.currentTime>=e[i].start&&this.el.currentTime<=e[i].end&&(t=i);var s={start:e[t].start,current:e[t].end,total:this.el.duration};this.trigger(Ee.PLAYBACK_PROGRESS,s,e)}}},{key:"_typeFor",value:function(e){var i=t._mimeTypesForUrl(e,Je,this.options.mimeType);return 0===i.length&&(i=t._mimeTypesForUrl(e,et,this.options.mimeType)),(i[0]||"").split(";")[0]}},{key:"_ready",value:function(){this._isReadyState||(this._isReadyState=!0,this.trigger(Ee.PLAYBACK_READY,this.name))}},{key:"_checkForClosedCaptions",value:function(){if(this.isHTML5Video&&!this._ccIsSetup){if(this.hasClosedCaptionsTracks){this.trigger(Ee.PLAYBACK_SUBTITLE_AVAILABLE);var e=this.closedCaptionsTrackId;this.closedCaptionsTrackId=e,this.handleTextTrackChange=this._handleTextTrackChange.bind(this),this.el.textTracks.addEventListener("change",this.handleTextTrackChange)}this._ccIsSetup=!0}}},{key:"_handleTextTrackChange",value:function(){var e=this.closedCaptionsTracks.find((function(e){return"showing"===e.track.mode}))||{id:-1};this._ccTrackId!==e.id&&(this._ccTrackId=e.id,this.trigger(Ee.PLAYBACK_SUBTITLE_CHANGED,{id:e.id}))}},{key:"isHTML5Video",get:function(){return this.name===t.prototype.name}},{key:"closedCaptionsTracks",get:function(){var e=0;return(this.el.textTracks?Array.from(this.el.textTracks):[]).filter((function(e){return"subtitles"===e.kind||"captions"===e.kind})).map((function(t){return{id:e++,name:t.label,track:t}}))}},{key:"closedCaptionsTrackId",get:function(){return this._ccTrackId},set:function(e){if(ie(e)){var t,i=this.closedCaptionsTracks;if(-1!==e){if(!(t=i.find((function(t){return t.id===e}))))return;if("showing"===t.track.mode)return}i.filter((function(e){return"hidden"!==e.track.mode})).forEach((function(e){return e.track.mode="hidden"})),t&&(t.track.mode="showing"),this._ccTrackId=e,this.trigger(Ee.PLAYBACK_SUBTITLE_CHANGED,{id:e})}}},{key:"template",get:function(){return Pe('<% for (var i = 0; i < tracks.length; i++) { %>\n <track data-html5-video-track="<%= i %>" kind="<%= tracks[i].kind %>" label="<%= tracks[i].label %>" srclang="<%= tracks[i].lang %>" src="<%= tracks[i].src %>">\n<% }; %>\n')}},{key:"render",value:function(){this.options.playback.disableContextMenu&&this.$el.on("contextmenu",(function(){return!1})),this._externalTracks&&this._externalTracks.length>0&&this.$el.html(this.template({tracks:this._externalTracks})),this._ready();var e=Ce("[data-html5-video] {\n position: absolute;\n height: 100%;\n width: 100%;\n display: block; }\n".toString(),{baseUrl:this.options.baseUrl});return this.$el.append(e[0]),this}}])}(Ue);st._mimeTypesForUrl=function(){var e=arguments.length>1?arguments[1]:void 0,t=arguments.length>2?arguments[2]:void 0,i=((arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").split("?")[0].match(/.*\.(.*)$/)||[])[1],s=t||i&&e[i.toLowerCase()]||[];return s.constructor===Array?s:[s]},st._canPlay=function(e,t,i,s){var r=st._mimeTypesForUrl(i,t,s),n=document.createElement(e);return!!r.filter((function(e){return!!n.canPlayType(e).replace(/no/,"")}))[0]},st.canPlay=function(e,t){return st._canPlay("audio",et,e,t)||st._canPlay("video",Je,e,t)};var rt=function(e){function t(){return p(this,t),g(this,t,arguments)}return S(t,e),v(t,[{key:"name",get:function(){return"html5_audio"}},{key:"supportedVersion",get:function(){return{min:"0.12.0"}}},{key:"tagName",get:function(){return"audio"}},{key:"isAudioOnly",get:function(){return!0}},{key:"updateSettings",value:function(){this.settings.left=["playpause","position","duration"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(Ee.PLAYBACK_SETTINGSUPDATE)}},{key:"getPlaybackType",value:function(){return Ue.AOD}}])}(st);rt.canPlay=function(e,t){return st._canPlay("audio",{wav:["audio/wav"],mp3:["audio/mp3",'audio/mpeg;codecs="mp3"'],aac:['audio/mp4;codecs="mp4a.40.5"'],oga:["audio/ogg"]},e,t)};var nt=function(e){function t(e){var i;return p(this,t),(i=g(this,t,[e])).el.src=e.src,i}return S(t,e),v(t,[{key:"name",get:function(){return"html_img"}},{key:"supportedVersion",get:function(){return{min:"0.12.0"}}},{key:"tagName",get:function(){return"img"}},{key:"attributes",get:function(){return{"data-html-img":""}}},{key:"events",get:function(){return{load:"_onLoad",abort:"_onError",error:"_onError"}}},{key:"getPlaybackType",value:function(){return Ue.NO_OP}},{key:"render",value:function(){var e=Ce("[data-html-img] {\n max-width: 100%;\n max-height: 100%; }\n".toString(),{baseUrl:this.options.baseUrl});return this.$el.append(e[0]),this.trigger(Ee.PLAYBACK_READY,this.name),this}},{key:"_onLoad",value:function(){this.trigger(Ee.PLAYBACK_ENDED,this.name)}},{key:"_onError",value:function(e){var t="error"===e.type?"load error":"loading aborted";this.trigger(Ee.PLAYBACK_ERROR,{message:t},this.name)}}])}(Ue);nt.canPlay=function(e){return/\.(png|jpg|jpeg|gif|bmp|tiff|pgm|pnm|webp)(|\?.*)$/i.test(e)};var at=function(e){function t(){var e;p(this,t);for(var i=arguments.length,s=new Array(i),r=0;r<i;r++)s[r]=arguments[r];return(e=g(this,t,[].concat(s)))._noiseFrameNum=-1,e}return S(t,e),v(t,[{key:"name",get:function(){return"no_op"}},{key:"supportedVersion",get:function(){return{min:"0.12.0"}}},{key:"template",get:function(){return Pe("<canvas data-no-op-canvas></canvas>\n<p data-no-op-msg><%=message%></p><p>\n</p>")}},{key:"attributes",get:function(){return{"data-no-op":""}}},{key:"render",value:function(){var e=this.options.playbackNotSupportedMessage||this.i18n.t("playback_not_supported"),t=Ce("[data-no-op] {\n position: absolute;\n height: 100%;\n width: 100%;\n text-align: center; }\n\n[data-no-op] p[data-no-op-msg] {\n position: absolute;\n text-align: center;\n font-size: 25px;\n left: 0;\n right: 0;\n color: white;\n padding: 10px;\n /* center vertically */\n top: 50%;\n transform: translateY(-50%);\n max-height: 100%;\n overflow: auto; }\n\n[data-no-op] canvas[data-no-op-canvas] {\n background-color: #777;\n height: 100%;\n width: 100%; }\n".toString(),{baseUrl:this.options.baseUrl});this.$el.append(t[0]),this.$el.html(this.template({message:e})),this.trigger(Ee.PLAYBACK_READY,this.name);var i=!(!this.options.poster||!this.options.poster.showForNoOp);return!this.options.autoPlay&&i||this._animate(),this}},{key:"_noise",value:function(){if(this._noiseFrameNum=(this._noiseFrameNum+1)%5,!this._noiseFrameNum){var e,t=this.context.createImageData(this.context.canvas.width,this.context.canvas.height);try{e=new Uint32Array(t.data.buffer)}catch(r){e=new Uint32Array(this.context.canvas.width*this.context.canvas.height*4);for(var i=t.data,s=0;s<i.length;s++)e[s]=i[s]}for(var r=e.length,n=6*Math.random()+4,a=0,o=0,l=0;l<r;){if(a<0)a=n*Math.random(),o=255*Math.pow(Math.random(),.4)<<24;a-=1,e[l++]=o}this.context.putImageData(t,0,0)}}},{key:"_loop",value:function(){var e=this;this._stop||(this._noise(),this._animationHandle=q((function(){return e._loop()})))}},{key:"destroy",value:function(){this._animationHandle&&(z(this._animationHandle),this._stop=!0)}},{key:"_animate",value:function(){this.canvas=this.$el.find("canvas[data-no-op-canvas]")[0],this.context=this.canvas.getContext("2d"),this._loop()}}])}(Ue);at.canPlay=function(e){return!0};var ot=function(e){function t(e){var i;return p(this,t),(i=g(this,t,[e]))._initializeMessages(),i}return S(t,e),v(t,[{key:"name",get:function(){return"strings"}},{key:"supportedVersion",get:function(){return{min:"0.12.0"}}},{key:"t",value:function(e){var t=this._language(),i=this._messages.en;return(t&&this._messages[t]||i)[e]||i[e]||e}},{key:"_language",value:function(){return this.core.options.language||re()}},{key:"_initializeMessages",value:function(){this._messages=M.extend(!0,{en:{live:"live",back_to_live:"back to live",disabled:"Disabled",playback_not_supported:"Your browser does not support the playback of this video. Please try using a different browser.",default_error_title:"Could not play video.",default_error_message:"There was a problem trying to load the video."},de:{live:"Live",back_to_live:"Zurück zum Live-Video",disabled:"Deaktiviert",playback_not_supported:"Ihr Browser unterstützt das Playback Verfahren nicht. Bitte vesuchen Sie es mit einem anderen Browser.",default_error_title:"Video kann nicht abgespielt werden",default_error_message:"Es gab ein Problem beim Laden des Videos"},pt:{live:"ao vivo",back_to_live:"voltar para o ao vivo",disabled:"Desativado",playback_not_supported:"Seu navegador não suporta a reprodução deste video. Por favor, tente usar um navegador diferente.",default_error_title:"Não foi possível reproduzir o vídeo.",default_error_message:"Ocorreu um problema ao tentar carregar o vídeo."},es_am:{live:"vivo",back_to_live:"volver en vivo",disabled:"No disponible",playback_not_supported:"Su navegador no soporta la reproducción de este video. Por favor, utilice un navegador diferente.",default_error_title:"No se puede reproducir el video.",default_error_message:"Se ha producido un error al cargar el video."},es:{live:"en directo",back_to_live:"volver al directo",disabled:"No disponible",playback_not_supported:"Este navegador no es compatible para reproducir este vídeo. Utilice un navegador diferente.",default_error_title:"No se puede reproducir el vídeo.",default_error_message:"Se ha producido un problema al cargar el vídeo."},ru:{live:"прямой эфир",back_to_live:"к прямому эфиру",disabled:"Отключено",playback_not_supported:"Ваш браузер не поддерживает воспроизведение этого видео. Пожалуйста, попробуйте другой браузер."},bg:{live:"на живо",back_to_live:"Върни на живо",disabled:"Изключено",playback_not_supported:"Вашият браузър не поддържа възпроизвеждането на това видео. Моля, пробвайте с друг браузър.",default_error_title:"Видеото не може да се възпроизведе.",default_error_message:"Възникна проблем при зареждането на видеото."},fr:{live:"en direct",back_to_live:"retour au direct",disabled:"Désactivé",playback_not_supported:"Votre navigateur ne supporte pas la lecture de cette vidéo. Merci de tenter sur un autre navigateur.",default_error_title:"Impossible de lire la vidéo.",default_error_message:"Un problème est survenu lors du chargement de la vidéo."},tr:{live:"canlı",back_to_live:"canlı yayına dön",disabled:"Engelli",playback_not_supported:"Tarayıcınız bu videoyu oynatma desteğine sahip değil. Lütfen farklı bir tarayıcı ile deneyin."},et:{live:"Otseülekanne",back_to_live:"Tagasi otseülekande juurde",disabled:"Keelatud",playback_not_supported:"Teie brauser ei toeta selle video taasesitust. Proovige kasutada muud brauserit."},ar:{live:"مباشر",back_to_live:"الرجوع إلى المباشر",disabled:"معطّل",playback_not_supported:"المتصفح الذي تستخدمه لا يدعم تشغيل هذا الفيديو. الرجاء إستخدام متصفح آخر.",default_error_title:"غير قادر الى التشغيل.",default_error_message:"حدثت مشكلة أثناء تحميل الفيديو."},zh:{live:"直播",back_to_live:"返回直播",disabled:"已禁用",playback_not_supported:"您的浏览器不支持该视频的播放。请尝试使用另一个浏览器。",default_error_title:"无法播放视频。",default_error_message:"在尝试加载视频时出现了问题。"}},this.core.options.strings||{}),this._messages["de-DE"]=this._messages.de,this._messages["pt-BR"]=this._messages.pt,this._messages["en-US"]=this._messages.en,this._messages["bg-BG"]=this._messages.bg,this._messages["es-419"]=this._messages.es_am,this._messages["es-ES"]=this._messages.es,this._messages["fr-FR"]=this._messages.fr,this._messages["tr-TR"]=this._messages.tr,this._messages["et-EE"]=this._messages.et,this._messages["ar-IQ"]=this._messages.ar,this._messages["zh-CN"]=this._messages.zh}}])}(Qe),lt=function(e){function t(){return p(this,t),g(this,t,arguments)}return S(t,e),v(t,[{key:"name",get:function(){return"sources"}},{key:"supportedVersion",get:function(){return{min:"0.12.0"}}},{key:"bindEvents",value:function(){this.listenTo(this.core,Ee.CORE_CONTAINERS_CREATED,this.onContainersCreated)}},{key:"onContainersCreated",value:function(){var e=this.core.containers.filter((function(e){return"no_op"!==e.playback.name}))[0]||this.core.containers[0];e&&this.core.containers.forEach((function(t){t!==e&&t.destroy()}))}}])}(Qe);We.registerPlugin(ot),We.registerPlugin(lt),We.registerPlayback(at),We.registerPlayback(nt),We.registerPlayback(rt),We.registerPlayback(st);const ht=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},ut=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=ct},ct=Number.MAX_SAFE_INTEGER||9007199254740991;let dt=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ft=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),gt=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var pt="manifest",mt="level",vt="audioTrack",yt="subtitleTrack",At="main",Et="audio",Tt="subtitle";class St{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class bt{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new St(e),this.fast_=new St(t),this.defaultTTFB_=s,this.ttfb_=new St(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new St(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new St(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new St(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,s=8*t/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function Lt(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function _t(){return _t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},_t.apply(null,arguments)}function kt(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function Rt(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?kt(Object(i),!0).forEach((function(t){Lt(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):kt(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class It{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${e}]:`;this.trace=Dt,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}const Dt=function(){},Pt={trace:Dt,debug:Dt,log:Dt,warn:Dt,info:Dt,error:Dt};function Ct(){return _t({},Pt)}function wt(e,t,i){return t[e]?t[e].bind(t):function(e,t){const i=self.console[e];return i?i.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Dt}(e,i)}const Ot=Ct();const xt=Ot;function Mt(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ft(e,t){const i=Object.keys(e),s=Object.keys(t),r=i.length,n=s.length;return!r||!n||r===n&&!i.some((e=>-1===s.indexOf(e)))}function Nt(e,t=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(e);if(t){const e=i.indexOf("\0");return-1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}const i=e.length;let s,r,n,a="",o=0;for(;o<i;){if(s=e[o++],0===s&&t)return a;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((31&s)<<6|63&r);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((15&s)<<12|(63&r)<<6|63&n)}}return a}const Ut=function(e){let t="";for(let i=0;i<e.length;i++){let s=e[i].toString(16);s.length<2&&(s="0"+s),t+=s}return t};function Bt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $t,Gt={exports:{}};var Kt,Vt,Ht,Yt,jt,Wt=($t||($t=1,Kt=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,Vt=/^(?=([^\/?#]*))\1([^]*)$/,Ht=/(?:\/|^)\.(?=\/)/g,Yt=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,Gt.exports=jt={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var s=jt.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=jt.normalizePath(s.path),jt.buildURLFromParts(s)}var r=jt.parseURL(t);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return i.alwaysNormalize?(r.path=jt.normalizePath(r.path),jt.buildURLFromParts(r)):t;var n=jt.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=Vt.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(o.netLoc=n.netLoc,"/"!==r.path[0]))if(r.path){var l=n.path,h=l.substring(0,l.lastIndexOf("/")+1)+r.path;o.path=jt.normalizePath(h)}else o.path=n.path,r.params||(o.params=n.params,r.query||(o.query=n.query));return null===o.path&&(o.path=i.alwaysNormalize?jt.normalizePath(r.path):r.path),jt.buildURLFromParts(o)},parseURL:function(e){var t=Kt.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(Ht,"");e.length!==(e=e.replace(Yt,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}}),Gt.exports);class qt{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 zt="audio",Xt="video",Qt="audiovideo";class Zt{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const i=ii(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let s;s=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[zt]:null,[Xt]:null,[Qt]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new qt),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Wt.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[zt]=null,e[Xt]=null,e[Qt]=null}}function Jt(e){return"initSegment"!==e.sn}class ei extends Zt{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange){const e=this.byteRange[0],t=this.byteRange[1];if(ht(e)&&ht(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=ht(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){ht(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Jt(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:n}}}class ti extends Zt{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function ii(e,t){const i=Object.getPrototypeOf(e);if(i){const e=Object.getOwnPropertyDescriptor(i,t);return e||ii(i,t)}}const si=Math.pow(2,32)-1,ri=[].push,ni={video:1,audio:2,id3:3,text:4};function ai(e){return String.fromCharCode.apply(null,e)}function oi(e,t){const i=e[t]<<8|e[t+1];return i<0?65536+i:i}function li(e,t){const i=ui(e,t);return i<0?4294967296+i:i}function hi(e,t){let i=li(e,t);return i*=Math.pow(2,32),i+=li(e,t+4),i}function ui(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ci(e,t,i){e[t]=i>>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function di(e,t){const i=[];if(!t.length)return i;const s=e.byteLength;for(let r=0;r<s;){const n=li(e,r),a=n>1?r+n:s;if(ai(e.subarray(r+4,r+8))===t[0])if(1===t.length)i.push(e.subarray(r+8,a));else{const s=di(e.subarray(r+8,a),t.slice(1));s.length&&ri.apply(i,s)}r=a}return i}function fi(e){const t=[],i=e[0];let s=8;const r=li(e,s);s+=4;let n=0,a=0;0===i?(n=li(e,s),a=li(e,s+4),s+=8):(n=hi(e,s),a=hi(e,s+8),s+=16),s+=2;let o=e.length+a;const l=oi(e,s);s+=2;for(let i=0;i<l;i++){let i=s;const n=li(e,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return xt.warn("SIDX has hierarchical references (not supported)"),null;const l=li(e,i);i+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:t}}function gi(e){const t=[],i=di(e,["moov","trak"]);for(let e=0;e<i.length;e++){const s=i[e],r=di(s,["tkhd"])[0];if(r){let e=r[0];const i=li(r,0===e?12:20),n=di(s,["mdia","mdhd"])[0];if(n){e=n[0];const r=li(n,0===e?12:20),a=di(s,["mdia","hdlr"])[0];if(a){const e=ai(a.subarray(8,12)),n={soun:zt,vide:Xt}[e],o=pi(di(s,["mdia","minf","stbl","stsd"])[0]);n?(t[i]={timescale:r,type:n,stsd:o},t[n]=Rt({timescale:r,id:i},o)):t[i]={timescale:r,type:e,stsd:o}}}}}return di(e,["moov","mvex","trex"]).forEach((e=>{const i=li(e,4),s=t[i];s&&(s.default={duration:li(e,12),flags:li(e,20)})})),t}function pi(e){const t=e.subarray(8),i=t.subarray(86),s=ai(t.subarray(4,8));let r,n=s;const a="enca"===s||"encv"===s;if(a){const e=di(t,[s])[0];di(e.subarray("enca"===s?28:78),["sinf"]).forEach((e=>{const t=di(e,["schm"])[0];if(t){const i=ai(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=di(e,["frma"])[0];t&&(n=ai(t))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=di(i,["avcC"])[0];e&&e.length>3&&(n+="."+yi(e[1])+yi(e[2])+yi(e[3]),r=mi("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const e=di(t,[s])[0],i=di(e.subarray(28),["esds"])[0];if(i&&i.length>7){let e=4;if(3!==i[e++])break;e=vi(i,e),e+=2;const t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=vi(i,e);const s=i[e++];if(64!==s)break;if(n+="."+yi(s),e+=12,5!==i[e++])break;e=vi(i,e);const r=i[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=di(i,["hvcC"])[0];if(e&&e.length>12){const t=e[1],i=["","A","B","C"][t>>6],s=31&t,r=li(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+i+s,n+="."+r.toString(16).toUpperCase(),n+="."+a+o;let h="";for(let e=l.length;e--;){const t=l[e];if(t||h){h="."+t.toString(16).toUpperCase()+h}}n+=h}r=mi("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=mi(n,i)||n;break;case"vp09":{const e=di(i,["vpcC"])[0];if(e&&e.length>6){const t=e[4],i=e[5],s=e[6]>>4&15;n+="."+Ai(t)+"."+Ai(i)+"."+Ai(s)}break}case"av01":{const e=di(i,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,s=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,h=2===t&&o?l?12:10:o?10:8,u=(16&e[2])>>4,c=(8&e[2])>>3,d=(4&e[2])>>2,f=3&e[2],g=1,p=1,m=1,v=0;n+="."+t+"."+Ai(s)+a+"."+Ai(h)+"."+u+"."+c+d+f+"."+Ai(g)+"."+Ai(p)+"."+Ai(m)+"."+v,r=mi("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:r}}function mi(e,t){const i=di(t,["dvvC"]),s=i.length?i[0]:di(t,["dvcC"])[0];if(s){const t=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return e+"."+Ai(t)+"."+Ai(i)}}function vi(e,t){const i=t+5;for(;128&e[t++]&&t<i;);return t}function yi(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Ai(e){return(e<10?"0":"")+e}function Ei(e){const t=di(e,["schm"])[0];if(t){const i=ai(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return di(e,["schi","tenc"])[0]}return null}function Ti(e){const t=li(e,0);let i=8;1&t&&(i+=4),4&t&&(i+=4);let s=0;const r=li(e,4);for(let n=0;n<r;n++){if(256&t){s+=li(e,i),i+=4}512&t&&(i+=4),1024&t&&(i+=4),2048&t&&(i+=4)}return s}function Si(e,t){const i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function bi(e,t){const i=[],s=t.samples,r=t.timescale,n=t.id;let a=!1;return di(s,["moof"]).map((o=>{const l=o.byteOffset-8;di(o,["traf"]).map((o=>{const h=di(o,["tfdt"]).map((e=>{const t=e[0];let i=li(e,4);return 1===t&&(i*=Math.pow(2,32),i+=li(e,8)),i/r}))[0];return void 0!==h&&(e=h),di(o,["tfhd"]).map((h=>{const u=li(h,4),c=16777215&li(h,0);let d=0;const f=!!(16&c);let g=0;const p=!!(32&c);let m=8;u===n&&(!!(1&c)&&(m+=8),!!(2&c)&&(m+=4),!!(8&c)&&(d=li(h,m),m+=4),f&&(g=li(h,m),m+=4),p&&(m+=4),"video"===t.type&&(a=Li(t.codec)),di(o,["trun"]).map((n=>{const o=n[0],h=16777215&li(n,0),u=!!(1&h);let c=0;const f=!!(4&h),p=!!(256&h);let m=0;const v=!!(512&h);let y=0;const A=!!(1024&h),E=!!(2048&h);let T=0;const S=li(n,4);let b=8;u&&(c=li(n,b),b+=4),f&&(b+=4);let L=c+l;for(let l=0;l<S;l++){if(p?(m=li(n,b),b+=4):m=d,v?(y=li(n,b),b+=4):y=g,A&&(b+=4),E&&(T=0===o?li(n,b):ui(n,b),b+=4),t.type===Xt){let t=0;for(;t<y;){const n=li(s,L);if(L+=4,_i(a,s[L])){ki(s.subarray(L,L+n),a?2:1,e+T/r,i)}L+=n,t+=n+4}}e+=m/r}})))}))}))})),i}function Li(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function _i(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function ki(e,t,i,s){const r=Ri(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){xt.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=oi(r,t);if(t+=2,49===e){const e=li(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e<l;e++)h[e]=r[t++]}s.push({type:e,payloadType:a,pts:i,bytes:h})}}}}}else if(5===a&&o>16){const e=[];for(let i=0;i<16;i++){const s=r[t++].toString(16);e.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=r[t++];s.push({payloadType:a,pts:i,uuid:e.join(""),userData:Nt(l),userDataBytes:l})}}}function Ri(e){const t=e.byteLength,i=[];let s=1;for(;s<t-2;)0===e[s]&&0===e[s+1]&&3===e[s+2]?(i.push(s+2),s+=2):s++;if(0===i.length)return e;const r=t-i.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===i[0]&&(a++,i.shift()),n[s]=e[a];return n}function Ii(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");let s,r,n;s=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){const i=t.length;let s=8,r=i;for(;r--;)s+=t[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),r=0,s=8;r<i;r++)n.set(t[r],s),s+=t[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,i||new Uint8Array)}function Di(e){const t=e.getUint32(0),i=e.byteOffset,s=e.byteLength;if(s<t)return{offset:i,size:s};if(1886614376!==e.getUint32(4))return{offset:i,size:t};const r=e.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:t};const n=e.buffer,a=Ut(new Uint8Array(n,i+12,16)),o=e.getUint32(28);let l=null,h=null;if(0===r){if(t-32<o||o<22)return{offset:i,size:t};h=new Uint8Array(n,i+32,o)}else if(1===r){if(!o||s<i+32+16*o+16)return{offset:i,size:t};l=[];for(let e=0;e<o;e++)l.push(new Uint8Array(n,i+32+16*e,16))}return{version:r,systemId:a,kids:l,data:h,offset:i,size:t}}const Pi=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ci={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 wi(e,t){const i=Ci[t];return!!i&&!!i[e.slice(0,4)]}function Oi(e,t,i=!0){return!e.split(",").some((e=>!xi(e,t,i)))}function xi(e,t,i=!0){var s;const r=Mt(i);return null!=(s=null==r?void 0:r.isTypeSupported(Mi(e,t)))&&s}function Mi(e,t){return`${t}/mp4;codecs=${e}`}function Fi(e){if(e){const t=e.substring(0,4);return Ci.video[t]}return 2}function Ni(e){const t=Pi();return e.split(",").reduce(((e,i)=>{const s=t&&Li(i)?9:Ci.video[i];return s?(2*s+e)/(e?3:2):(Ci.audio[i]+e)/(e?2:1)}),0)}const Ui={};const Bi=/flac|opus|mp4a\.40\.34/i;function $i(e,t=!0){return e.replace(Bi,(e=>function(e,t=!0){if(Ui[e])return Ui[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<i.length;r++){var s;if(xi(i[r],"audio",t))return Ui[e]=i[r],i[r];if("mp3"===i[r]&&null!=(s=Mt(t))&&s.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)))}function Gi(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)))return e;if(t){const i=t.split(",");if(i.length>1){if(e)for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t];return i[0]}}return t||e}function Ki(e){if(e.startsWith("av01.")){const t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}function Vi(e){const t=Mt(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Hi(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Yi={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function ji(e,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:e}}const Wi={};function qi(e,t,i,s,r,n){const a=e.audioCodec?e.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let u=null;if(null!=a&&a.length)try{u=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce(((e,i)=>{if(i){const s=t.groups[i];if(!s)throw new Error(`Audio track group ${i} not found`);Object.keys(s.channels).forEach((t=>{e[t]=(e[t]||0)+s.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(s,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(r,8e6))||!!u&&ht(h)&&Object.keys(u).some((e=>parseInt(e)>h))}function zi(e,t,i){const s=e.videoCodec,r=e.audioCodec;if(!s&&!r||!i)return Promise.resolve(Yi);const n=[];if(s){const t={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},i=e.videoRange;"SDR"!==i&&(t.transferFunction=i.toLowerCase());const r=s.split(","),a=navigator.userAgent;if(r.some((e=>Li(e)))&&Pi())return Promise.resolve(ji(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${a})`),n));n.push.apply(n,r.map((e=>({type:"media-source",video:Rt(Rt({},t),{},{contentType:Mi(Ki(e),"video")})}))))}return r&&e.audioGroups&&e.audioGroups.forEach((e=>{var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((t=>{if(t.groupId===e){const e=t.channels||"",i=parseFloat(e);ht(i)&&i>2&&n.push.apply(n,r.split(",").map((e=>({type:"media-source",audio:{contentType:Mi(e,"audio"),channels:""+i}}))))}})))})),Promise.all(n.map((e=>{const t=function(e){const{audio:t,video:i}=e,s=i||t;if(s){const e=Hi(s.contentType);if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${e}_${Math.ceil(i.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${e}`}return""}(e);return Wi[t]||(Wi[t]=i.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:n,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e})))}const Xi=["NONE","TYPE-0","TYPE-1",null];const Qi=["SDR","PQ","HLG"];var Zi="",Ji="YES",es="v2";function ts(e){const{canSkipUntil:t,canSkipDateRanges:i,age:s}=e;return t&&s<t/2?i?es:Ji:Zi}class is{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class ss{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>!!e)).map((e=>e.substring(0,4))).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return rs(this._audioGroups,e)}hasSubtitleGroup(e){return rs(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function rs(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function ns(e,t){let i=!1,s=[];if(e&&(i="SDR"!==e,s=[e]),t){s=t.allowedVideoRanges||Qi.slice(0);const e="SDR"!==s.join("")&&!t.videoCodec;i=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}const as=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(i,s)=>{if(e&&(s=e(i,s)),"object"==typeof s&&null!==s){if(t.has(s))return;t.add(s)}return s}})(t));function os(e,t){xt.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function ls(e){return e.reduce(((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function hs(e){if(!e)return e;const{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}=e;return{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function us(e,t,i){if("attrs"in e){const i=t.indexOf(e);if(-1!==i)return i}for(let s=0;s<t.length;s++){if(cs(e,t[s],i))return s}return-1}function cs(e,t,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===s||t.groupId===s)&&(void 0===r||t.name===r)&&(void 0===n||function(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const i=e.split(","),s=t.split(",");return i.length===s.length&&!i.some((e=>-1===s.indexOf(e)))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function ds(e,t){const{audioCodec:i,channels:s}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(t.channels||"2"))}function fs(e,t,i){for(let s=t;s>-1;s--)if(i(e[s]))return s;for(let s=t+1;s<e.length;s++)if(i(e[s]))return s;return-1}function gs(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}const ps=function(e,t){let i=0,s=e.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=e[r];const a=t(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function ms(e,t,i=0,s=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const s=e.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===vs(i,s,n)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const s=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),i);return e.start<=s}return!1}(n,e,Math.min(r,s))))return n;const a=ps(t,vs.bind(null,i,s));return!a||a===e&&n?n:a}function vs(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=e?1:i.start-s>e&&i.start?-1:0}function ys(e,t,i){const s=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>e}function As(e,t){return ps(e,(e=>e.cc<t?1:e.cc>t?-1:0))}function Es(e){switch(e.details){case ft.FRAG_LOAD_TIMEOUT:case ft.KEY_LOAD_TIMEOUT:case ft.LEVEL_LOAD_TIMEOUT:case ft.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ts(e,t){const i=Es(t);return e.default[(i?"timeout":"error")+"Retry"]}function Ss(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function bs(e){return Rt(Rt({},e),{errorRetry:null,timeoutRetry:null})}function Ls(e,t,i,s){if(!e)return!1;const r=null==s?void 0:s.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(r)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,s,n):n}var _s=0,ks=2,Rs=3,Is=5,Ds=0,Ps=1,Cs=2;function ws(e){const t={action:_s,flags:Ds};return e&&(t.resolved=!0),t}var Os="NOT_LOADED",xs="APPENDING",Ms="PARTIAL",Fs="OK";class Ns{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.BUFFER_APPENDED,this.onBufferAppended,this),e.on(gt.FRAG_BUFFERED,this.onFragBuffered,this),e.on(gt.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.BUFFER_APPENDED,this.onBufferAppended,this),e.off(gt.FRAG_BUFFERED,this.onFragBuffered,this),e.off(gt.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let t=i.length;t--;){const s=i[t];if(!s)break;const r=s.end;if(s.start<=e&&null!==r&&e<=r)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){const a=s[r[n]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,s,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach((s=>{const a=this.fragments[s];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===i&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some((e=>{const i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(a.body),i})):this.removeFragment(a.body))}))}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const i=e.frag,s=Bs(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const n=!i.relurl;if(Object.keys(t).forEach((s=>{const a=i.elementaryStreams[s];if(!a)return;const o=t[s],l=n||!0===a.partial;r.range[s]=this.getBufferedTimes(i,e.part,l,o)})),r.loaded=null,Object.keys(r.range).length){r.buffered=!0;(r.body.endList=i.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),Us(r)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(r.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=$s(i,(t=>t.fragment.sn>=e)))}fragBuffered(e,t){const i=Bs(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const r={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<s.length;e++){const t=s.start(e)-this.bufferPadding,i=s.end(e)+this.bufferPadding;if(l>=t&&o<=i){r.time.push({startPTS:Math.max(n,s.start(e)),endPTS:Math.min(a,s.end(e))});break}if(n<i&&a>t){const t=Math.max(n,s.start(e)),i=Math.min(a,s.end(e));i>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:i}))}else if(a<=t)break}return r}getPartialFragment(e){let t,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&Us(h)&&(i=h.body.start-a,s=h.body.end+a,e>=i&&e<=s&&(t=Math.min(e-i,s-e),n<=t&&(r=h.body,n=t)))})),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||Us(t))}getState(e){const t=Bs(e),i=this.fragments[t];return i?i.buffered?Us(i)?Ms:Fs:xs:Os}isTimeBuffered(e,t,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,r=Bs(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:r,type:n}=t;if("initSegment"===i.sn)return;const a=i.type;if(s){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(s)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Bs(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){const r=t[i[s]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)}))}removeFragment(e){const t=Bs(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const t=e.sn;this.activePartLists[e.type]=$s(i,(e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const i=null==(e=this.hls)||null==(t=e.latestLevelDetails)?void 0:t.partList;i&&i.forEach((e=>e.clearElementaryStreamInfo()))}}function Us(e){var t,i,s;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(s=e.range.audiovideo)?void 0:s.partial))}function Bs(e){return`${e.type}_${e.level}_${e.sn}`}function $s(e,t){return e.filter((e=>{const i=t(e);return i||e.clearElementaryStreamInfo(),i}))}var Gs=0,Ks=1;class Vs{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case Gs:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ks:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Hs{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],u=o[2],c=o[3],d=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)d[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;const o=d[f],p=d[o],m=d[p];let v=257*d[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*m^65537*p^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,u[i]=v<<8|v>>>24,c[i]=v,f?(f=o^d[d[d[m^o]]],g^=d[d[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),u=this.sBox,c=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],m=d[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=t[a]:(y=v,a%r==0?(y=y<<8|y>>>24,y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[255&y],y^=c[a/r|0]<<24):r>6&&a%r==4&&(y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[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],h[o]=o<4||a<=4?y:f[u[y>>>24]]^g[u[y>>>16&255]]^p[u[y>>>8&255]]^m[u[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],u=a[3],c=this.uint8ArrayToUint32Array_(i);let d=c[0],f=c[1],g=c[2],p=c[3];const m=new Int32Array(e),v=new Int32Array(m.length);let y,A,E,T,S,b,L,_,k,R,I,D,P,C;const w=this.networkToHostOrderSwap;for(;t<m.length;){for(k=w(m[t]),R=w(m[t+1]),I=w(m[t+2]),D=w(m[t+3]),S=k^r[0],b=D^r[1],L=I^r[2],_=R^r[3],P=4,C=1;C<s;C++)y=o[S>>>24]^l[b>>16&255]^h[L>>8&255]^u[255&_]^r[P],A=o[b>>>24]^l[L>>16&255]^h[_>>8&255]^u[255&S]^r[P+1],E=o[L>>>24]^l[_>>16&255]^h[S>>8&255]^u[255&b]^r[P+2],T=o[_>>>24]^l[S>>16&255]^h[b>>8&255]^u[255&L]^r[P+3],S=y,b=A,L=E,_=T,P+=4;y=n[S>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&_]^r[P],A=n[b>>>24]<<24^n[L>>16&255]<<16^n[_>>8&255]<<8^n[255&S]^r[P+1],E=n[L>>>24]<<24^n[_>>16&255]<<16^n[S>>8&255]<<8^n[255&b]^r[P+2],T=n[_>>>24]<<24^n[S>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^r[P+3],v[t]=w(y^d),v[t+1]=w(T^f),v[t+2]=w(E^g),v[t+3]=w(A^p),d=k,f=R,g=I,p=D,t+=4}return v.buffer}}class Ys{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=function(e){switch(e){case Gs:return"AES-CBC";case Ks:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class js{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?e.slice(0,t-i):e}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s){return this.useSoftware?new Promise(((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==Gs||16!==t.byteLength)return xt.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Si(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Hs),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new Ys(this.subtle,t,s)}return this.fastAesKey.expandKey().then((t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Vs(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,t)})).catch((r=>(xt.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,s))))}onWebCryptoError(e,t,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(xt.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Ws=Math.pow(2,17);class qs{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Qs({type:dt.NETWORK_ERROR,details:ft.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(Xs(e));e.gap=!1}const l=this.loader=r?new r(s):new n(s),h=zs(e);e.loader=l;const u=bs(s.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Ws};e.stats=l.stats;const d={onSuccess:(t,i,s,r)=>{this.resetLoader(e,l);let n=t.data;s.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,s,r,n)=>{this.resetLoader(e,l),o(new Qs({type:dt.NETWORK_ERROR,details:ft.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Rt({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:n}))},onAbort:(t,i,s)=>{this.resetLoader(e,l),o(new Qs({type:dt.NETWORK_ERROR,details:ft.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:(t,i,s)=>{this.resetLoader(e,l),o(new Qs({type:dt.NETWORK_ERROR,details:ft.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:s,stats:t}))}};t&&(d.onProgress=(i,s,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})),l.load(h,c,d)}))}loadPart(e,t,i){this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Xs(e,t));const l=this.loader=r?new r(s):new n(s),h=zs(e,t);e.loader=l;const u=bs(s.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ws};t.stats=l.stats,l.load(h,c,{onSuccess:(s,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:s.data,networkDetails:o};i(h),a(h)},onError:(i,s,r,n)=>{this.resetLoader(e,l),o(new Qs({type:dt.NETWORK_ERROR,details:ft.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Rt({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:r,stats:n}))},onAbort:(i,s,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Qs({type:dt.NETWORK_ERROR,details:ft.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:i}))},onTimeout:(i,s,r)=>{this.resetLoader(e,l),o(new Qs({type:dt.NETWORK_ERROR,details:ft.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:i}))}})}))}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(e.duration/t.duration),n=Math.min(Math.round(i.loaded/r),s),a=(s-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function zs(e,t=null){const i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(ht(r)&&ht(n)){var a;let t=r,i=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-r;e%16&&(i=n+(16-e%16)),0!==r&&(s.resetIV=!0,t=r-16)}s.rangeStart=t,s.rangeEnd=i}var o;return s}function Xs(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:dt.MEDIA_ERROR,details:ft.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(s.part=t),(t||e).stats.aborted=!0,new Qs(s)}class Qs extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Zs extends It{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Js{constructor(e,t,i,s=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=n}}const er={length:0,start:()=>0,end:()=>0};class tr{static isBuffered(e,t){if(e){const i=tr.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=tr.getBuffered(e);return tr.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const s=tr.bufferedRanges(e);if(s.length)return tr.bufferedInfo(s,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort(((e,t)=>e.start-t.start||t.end-e.end));let s=-1,r=[];if(i)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(s=n);const a=r.length;if(a){const t=r[a-1].end;e[n].start-t<i?e[n].end>t&&(r[a-1].end=e[n].end):r.push(e[n])}else r.push(e[n])}else r=e;let n,a=0,o=t,l=t;for(let e=0;e<r.length;e++){const h=r[e].start,u=r[e].end;if(-1===s&&t>=h&&t<=u&&(s=e),t+i>=h&&t<u)o=h,l=u,a=l-t;else if(t+i<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||er}catch(e){return xt.log("failed to get media.buffered",e),er}}}const ir=/\{\$([a-zA-Z0-9-_]+)\}/g;function sr(e){return ir.test(e)}function rr(e,t){if(null!==e.variableList||e.hasVariableRefs){const i=e.variableList;return t.replace(ir,(t=>{const s=t.substring(2,t.length-1),r=null==i?void 0:i[s];return void 0===r?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),t):r}))}return t}function nr(e,t,i){let s,r,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){s=t.QUERYPARAM;try{const e=new self.URL(i).searchParams;if(!e.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=e.get(s)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else s=t.NAME,r=t.VALUE;s in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function ar(e,t,i){const s=t.IMPORT;if(i&&s in i){let t=e.variableList;t||(e.variableList=t={}),t[s]=i[s]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const or=/^(\d+)x(\d+)$/,lr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class hr{constructor(e,t){"string"==typeof e&&(e=hr.parseAttrList(e,t)),_t(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce(((e,t)=>(e[t.toLowerCase()]=!0,e)),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=or.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const s={};for(lr.lastIndex=0;null!==(i=lr.exec(e));){const r=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=rr(t,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":xt.warn(`${e}: attribute ${r} is missing quotes`)}s[r]=n}return s}}function ur(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class cr{constructor(e,t,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(s=null==t?void 0:t.tagOrder)?s:i,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){xt.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=_t(new hr({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);ht(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(xt.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(ht(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&ht(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 dr{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}get hasProgramDateTime(){return!!this.fragments.length&&ht(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function fr(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function gr(e){switch(e){case"AES-128":case"AES-256":return Gs;case"AES-256-CTR":return Ks;default:throw new Error(`invalid full segment method ${e}`)}}function pr(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function mr(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}function vr(e){const t=e.split(":");let i=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),s=e[e.length-1].split(",");if(2===s.length){const t="base64"===s[0],r=s[1];t?(e.splice(-1,1),i=pr(r)):i=function(e){const t=mr(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(r)}}return i}const yr="undefined"!=typeof self?self:void 0;var Ar={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Er="org.w3.clearkey",Tr="com.apple.streamingkeydelivery",Sr="com.microsoft.playready",br="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Lr(e){switch(e){case Tr:return Ar.FAIRPLAY;case Sr:return Ar.PLAYREADY;case br:return Ar.WIDEVINE;case Er:return Ar.CLEARKEY}}var _r="1077efecc0b24d02ace33c1e52e2fb4b",kr="e2719d58a985b3c9781ab030af78d30e",Rr="9a04f07998404286ab92e65be0885f95",Ir="edef8ba979d64acea3c827dcd51d21ed";function Dr(e){return e===Ir?Ar.WIDEVINE:e===Rr?Ar.PLAYREADY:e===_r||e===kr?Ar.CLEARKEY:void 0}function Pr(e){switch(e){case Ar.FAIRPLAY:return Tr;case Ar.PLAYREADY:return Sr;case Ar.WIDEVINE:return br;case Ar.CLEARKEY:return Er}}function Cr(e){const{drmSystems:t,widevineLicenseUrl:i}=e,s=t?[Ar.FAIRPLAY,Ar.WIDEVINE,Ar.PLAYREADY,Ar.CLEARKEY].filter((e=>!!t[e])):[];return!s[Ar.WIDEVINE]&&i&&s.push(Ar.WIDEVINE),s}const wr=null!=yr&&null!=(Or=yr.navigator)&&Or.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Or;function xr(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),s=i.substring(i.indexOf("<"),i.length),r=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(e){const t=pr(e).subarray(0,16);return function(e){const t=function(e,t,i){const s=e[t];e[t]=e[i],e[i]=s};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),t}}return null}let Mr={};class Fr{static clearKeyUriToKeyIdMap(){Mr={}}constructor(e,t,i,s=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!fr(e)}isSupported(){if(this.method){if(fr(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Tr:case br:case Sr:case Er:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(fr(this.method)&&this.uri&&!this.iv){"number"!=typeof e&&(xt.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=function(e){const t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e);return new Fr(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=vr(this.uri);if(t)switch(this.keyFormat){case br:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Sr:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ii(e,0,t),this.keyId=xr(t);break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=Mr[this.uri];if(!e){const t=Object.keys(Mr).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),Mr[this.uri]=e}this.keyId=e}return this}}const Nr=/#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,Ur=/#EXT-X-MEDIA:(.*)/g,Br=/^#EXT(?:INF|-X-TARGETDURATION):/m,$r=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Gr=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 Kr{static findGroup(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.id===t)return s}}static resolve(e,t){return Wt.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Br.test(e)}static parseMasterPlaylist(e,t){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:sr(e)},s=[];let r;for(Nr.lastIndex=0;null!=(r=Nr.exec(e));)if(r[1]){var n;const e=new hr(r[1],i),a=rr(i,r[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Kr.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Wr(e.CODECS,o);const h=e["SUPPLEMENTAL-CODECS"];h&&(o.supplemental={},Wr(h,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||s.push(o),i.levels.push(o)}else if(r[3]){const e=r[3],s=r[4];switch(e){case"SESSION-DATA":{const e=new hr(s,i),t=e["DATA-ID"];t&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[t]=e);break}case"SESSION-KEY":{const e=Yr(s,t,i);e.encrypted&&e.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(e)):xt.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${s}"`);break}case"DEFINE":nr(i,new hr(s,i),t);break;case"CONTENT-STEERING":{const e=new hr(s,i);i.contentSteering={uri:Kr.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=jr(s)}}const a=s.length>0&&s.length<i.levels.length;return i.levels=a?s:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,i){let s;const r={},n=i.levels,a={AUDIO:n.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Ur.lastIndex=0;null!==(s=Ur.exec(e));){const e=new hr(s[1],i),n=e.TYPE;if(n){const i=a[n],s=r[n]||[];r[n]=s;const l=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],u=e.CHANNELS,c=e.CHARACTERISTICS,d=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?Kr.resolve(e.URI,t):""};if(h&&(f.assocLang=h),u&&(f.channels=u),c&&(f.characteristics=c),d&&(f.instreamId=d),null!=i&&i.length){const e=Kr.findGroup(i,f.groupId)||i[0];qr(f,e,"audioCodec"),qr(f,e,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(e,t,i,s,r,n){var a;const o={url:t},l=new dr(t),h=l.fragments,u=[];let c,d,f,g,p=null,m=0,v=0,y=0,A=0,E=0,T=null,S=new ei(s,o),b=-1,L=!1,_=null;if($r.lastIndex=0,l.m3u8=e,l.hasVariableRefs=sr(e),"#EXTM3U"!==(null==(a=$r.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=$r.exec(e));){L&&(L=!1,S=new ei(s,o),S.playlistOffset=y,S.start=y,S.sn=m,S.cc=A,E&&(S.bitrate=E),S.level=i,p&&(S.initSegment=p,p.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),_&&(S.setByteRange(_),_=null)));const e=c[1];if(e){S.duration=parseFloat(e);const t=(" "+c[2]).slice(1);S.title=t||null,S.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(ht(S.duration)){S.playlistOffset=y,S.start=y,f&&Qr(S,f,l),S.sn=m,S.level=i,S.cc=A,h.push(S);const e=(" "+c[3]).slice(1);S.relurl=rr(l,e),zr(S,T,u),T=S,y+=S.duration,m++,v=0,L=!0}}else{if(c=c[0].match(Gr),!c){xt.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d<c.length&&void 0===c[d];d++);const e=(" "+c[d]).slice(1),r=(" "+c[d+1]).slice(1),a=c[d+2]?(" "+c[d+2]).slice(1):null;switch(e){case"BYTERANGE":T?S.setByteRange(r,T):S.setByteRange(r);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=r,S.tagList.push(["PROGRAM-DATE-TIME",r]),-1===b&&(b=h.length);break;case"PLAYLIST-TYPE":l.type&&Zr(l,e,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Zr(l,e,c):h.length>0&&Jr(l,e,c),m=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&Zr(l,e,c);const t=new hr(r,l),i=t.decimalInteger("SKIPPED-SEGMENTS");if(ht(i)){l.skippedSegments+=i;for(let e=i;e--;)h.push(null);m+=i}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Zr(l,e,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&Zr(l,e,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Zr(l,e,c),l.live=!1;break;case"#":(r||a)&&S.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":A++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([e]);break;case"BITRATE":S.tagList.push([e,r]),E=1e3*parseInt(r),ht(E)?S.bitrate=E:E=0;break;case"DATERANGE":{const e=new hr(r,l),t=new cr(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:xt.warn(`Ignoring invalid DATERANGE tag: "${r}"`),S.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const e=new hr(r,l);"IMPORT"in e?ar(l,e,n):nr(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?Zr(l,e,c):h.length>0&&Jr(l,e,c),l.startCC=A=parseInt(r);break;case"KEY":{const e=Yr(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={}),f[e.keyFormat]&&(f=_t({},f)),f[e.keyFormat]=e}else xt.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=jr(r);break;case"MAP":{const e=new hr(r,l);if(S.duration){const t=new ei(s,o);Xr(t,e,i,f),p=t,S.initSegment=p,p.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime)}else{const t=S.byteRangeEndOffset;if(t){const e=S.byteRangeStartOffset;_=`${t-e}@${e}`}else _=null;Xr(S,e,i,f),p=S,L=!0}p.cc=A;break}case"SERVER-CONTROL":g&&Zr(l,e,c),g=new hr(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Zr(l,e,c);const t=new hr(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,i=v++,s=new hr(r,l),n=new ti(s,S,o,i,t);e.push(n),S.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new hr(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new hr(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:xt.warn(`line parsed but not handled: ${c}`)}}}T&&!T.relurl?(h.pop(),y-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(zr(S,T,u),S.cc=A,l.fragmentHint=S,f&&Qr(S,f,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const k=h.length,R=h[0],I=h[k-1];if(y+=l.skippedSegments*l.targetduration,y>0&&k&&I){l.averagetargetduration=y/k;const e=I.sn;l.endSN="initSegment"!==e?e:0,l.live||(I.endList=!0),R&&void 0===l.startCC&&(l.startCC=R.cc),b>0&&(!function(e,t){let i=e[t];for(let s=t;s--;){const t=e[s];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(h,b),R&&u.unshift(R))}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,u.length&&l.dateRangeTagCount&&R&&Vr(u,l),l.endCC=A,l}}function Vr(e,t){const i=e.length,s=e[i-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let a=n.length;a--;){const o=t.dateRanges[n[a]],l=o.startDate.getTime();o.tagAnchor=s.ref;for(let s=i;s--;){const i=Hr(t,l,e,s,r);if(-1!==i){o.tagAnchor=t.fragments[i].ref;break}}}}function Hr(e,t,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(t>=o||0===s){var a;if(t<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||r)-n.start)){const r=i[s].sn-e.startSN,n=e.fragments;if(n.length>i.length){for(let a=(i[s+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return r}}}return-1}function Yr(e,t,i){var s,r;const n=new hr(e,i),a=null!=(s=n.METHOD)?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,u=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&xt.error(`Invalid IV: ${n.IV}`);const c=o?Kr.resolve(o,t):"",d=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Fr(a,c,u,d,l)}function jr(e){const t=new hr(e).decimalFloatingPoint("TIME-OFFSET");return ht(t)?t:null}function Wr(e,t){let i=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const s=i.filter((t=>wi(t,e)));s.length&&(t[`${e}Codec`]=s.map((e=>e.split("/")[0])).join(","),i=i.filter((e=>-1===s.indexOf(e))))})),t.unknownCodecs=i}function qr(e,t,i){const s=t[i];s&&(e[i]=s)}function zr(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Xr(e,t,i,s){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",s&&(e.levelkeys=s),e.initSegment=null}function Qr(e,t,i){e.levelkeys=t;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||s.push(e)}function Zr(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function Jr(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function en(e,t){const i=t.startPTS;if(ht(i)){let s,r=0;t.sn>e.sn?(r=i-e.start,s=e):(r=e.start-i,s=t),s.duration!==r&&s.setDuration(r)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function tn(e,t,i,s,r,n){s-i<=0&&(xt.warn("Fragment should have a positive duration",t),s=i+t.duration,n=r+t.duration);let a=i,o=s;const l=t.startPTS,h=t.endPTS;if(ht(l)){const e=Math.abs(l-i);ht(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(i,l),i=Math.min(i,l),r=Math.min(r,t.startDTS),o=Math.min(s,h),s=Math.max(s,h),n=Math.max(n,t.endDTS)}const u=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(s-t.start),t.startPTS=i,t.maxStartPTS=a,t.startDTS=r,t.endPTS=s,t.minEndPTS=o,t.endDTS=n;const c=t.sn;if(!e||c<e.startSN||c>e.endSN)return 0;let d;const f=c-e.startSN,g=e.fragments;for(g[f]=t,d=f;d>0;d--)en(g[d],g[d-1]);for(d=f;d<g.length-1;d++)en(g[d],g[d+1]);return e.fragmentHint&&en(g[g.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function sn(e,t){if(e===t)return;let i=null;const s=e.fragments;for(let e=s.length-1;e>=0;e--){const t=s[e].initSegment;if(t){i=t;break}}let r;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){const s=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(s?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let h=r;h<=n;h++){const r=l[a+h];let n=o[h];if(s&&!n&&r&&(n=t.fragments[h]=r),r&&n){if(i(r,n,h,o),r.url&&r.url!==n.url)return void(t.playlistParsingError=rn(`media sequence mismatch ${n.sn}:`,e,t,r,n));if(r.cc!==n.cc)return void(t.playlistParsingError=rn(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,e,t,r,n))}}}(e,t,((s,n,a,o)=>{if(!t.startCC&&n.cc!==s.cc){var l,h;const i=s.cc-n.cc;for(let e=a;e<o.length;e++)o[e].cc+=i;t.startCC=null!=(l=null==(h=ln(e,t.startSN-1))?void 0:h.cc)?l:o[0].cc,t.endCC=o[o.length-1].cc}ht(s.startPTS)&&ht(s.endPTS)&&(n.setStart(n.startPTS=s.startPTS),n.startDTS=s.startDTS,n.maxStartPTS=s.maxStartPTS,n.endPTS=s.endPTS,n.endDTS=s.endDTS,n.minEndPTS=s.minEndPTS,n.setDuration(s.endPTS-s.startPTS),n.duration&&(r=n),t.PTSKnown=t.alignedSliding=!0),s.hasStreams&&(n.elementaryStreams=s.elementaryStreams),n.loader=s.loader,s.hasStats&&(n.stats=s.stats),s.initSegment&&(n.initSegment=s.initSegment,i=s.initSegment)}));const n=t.fragments,a=t.fragmentHint?n.concat(t.fragmentHint):n;if(i&&a.forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)})),t.skippedSegments)if(t.deltaUpdateFailed=n.some((e=>!e)),t.deltaUpdateFailed){xt.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)n.shift();t.startSN=n[0].sn}else{t.endCC=n[n.length-1].cc,t.canSkipDateRanges&&(t.dateRanges=function(e,t){const{dateRanges:i,recentlyRemovedDateranges:s}=t,r=_t({},e);s&&s.forEach((e=>{delete r[e]}));const n=Object.keys(r).length;n&&Object.keys(i).forEach((e=>{const t=r[e],s=new cr(i[e].attr,t);s.isValid?(r[e]=s,t||(s.tagOrder+=n)):xt.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${as(i[e].attr)}"`)}));return r}(e.dateRanges,t));const i=e.fragments.filter((e=>e.rawProgramDateTime));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<a.length;e++)null===a[e].programDateTime&&zr(a[e],a[e-1],i);Vr(i,t)}!function(e,t,i){if(e&&t){let s=0;for(let r=0,n=e.length;r<=n;r++){const n=e[r],a=t[r+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):s--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),r?tn(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):nn(e,t),n.length&&(t.totalduration=t.edge-n[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function rn(e,t,i,s,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function nn(e,t,i=!0){const s=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+s*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}an(t,a)}function an(e,t){if(t){const i=e.fragments;for(let s=e.skippedSegments;s<i.length;s++)i[s].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function on(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const s=e.fragments,r=4;if(s.length&&i*r>t){const e=1e3*s[s.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}function ln(e,t,i){if(!e)return null;let s=e.fragments[t-e.startSN];return s||(s=e.fragmentHint,s&&s.sn===t?s:t<e.startSN&&i&&i.sn===t?i:null)}function hn(e,t,i){return e?un(e.partList,t,i):null}function un(e,t,i){if(e)for(let s=e.length;s--;){const r=e[s];if(r.index===i&&r.fragment.sn===t)return r}return null}function cn(e){e.forEach(((e,t)=>{var i;null==(i=e.details)||i.fragments.forEach((e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function dn(e,t){for(let s=0,r=e.length;s<r;s++){var i;if((null==(i=e[s])?void 0:i.cc)===t)return e[s]}return null}function fn(e,t){if(e){const i=e.start+t;e.start=e.startPTS=i,e.endPTS=i+e.duration}}function gn(e,t){const i=t.fragments;for(let t=0,s=i.length;t<s;t++)fn(i[t],e);t.fragmentHint&&fn(t.fragmentHint,e),t.alignedSliding=!0}function pn(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const i=Math.min(t.endCC,e.endCC),s=dn(t.fragments,i),r=dn(e.fragments,i);if(!s||!r)return;xt.log(`Aligning playlist at start of dicontinuity sequence ${i}`);gn(s.start-r.start,e)}function mn(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,s=t.fragments;if(!i.length||!s.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=dn(s,a),n=dn(i,a)),r&&n||(r=s[Math.floor(s.length/2)],n=dn(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;gn((l-o)/1e3-(n.start-r.start),e)}const vn=function(e){let t="";const i=e.length;for(let s=0;s<i;s++)t+=`[${e.start(s).toFixed(3)}-${e.end(s).toFixed(3)}]`;return t},yn="STOPPED",An="IDLE",En="KEY_LOADING",Tn="FRAG_LOADING",Sn="FRAG_LOADING_WAITING_RETRY",bn="WAITING_TRACK",Ln="PARSING",_n="PARSED",kn="ENDED",Rn="ERROR",In="WAITING_INIT_PTS",Dn="WAITING_LEVEL";class Pn extends Zs{constructor(e,t,i,s,r){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=yn,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:r}=this,n=i?i.currentTime:0,a=tr.bufferInfo(s||i,n,e.maxBufferHole);if(this.log(`media seeking to ${ht(n)?n.toFixed(3):n}, state: ${r}`),this.state===kn)this.resetLoadingState();else if(t){const i=e.maxFragLookUpTolerance,s=t.start-i,r=t.start+t.duration+i;if(!a.len||r<a.start||s>a.end){const e=n>r;(n<s||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||a.len||(this.log(`setting startPosition to ${n} because of seek before start`),this.nextLoadPosition=this.startPosition=n),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new qs(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new js(e.config)}registerListeners(){const{hls:e}=this;e.on(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(gt.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(gt.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===yn)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=yn}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=e.nextStart;if(r&&r>s&&r<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const n=t.partList;if(null!=n&&n.length){const e=n[n.length-1];return tr.isBuffered(this.media,e.start+e.duration/2)}const a=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(a)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===yn&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(null!==s){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),s.removeEventListener("seeking",this.onMediaSeeking),s.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=yn,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){this._doFragLoad(e,t,i,(e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const t=this.state,i=e.frag;this.fragContextChanged(i)?(t===Tn||!this.fragCurrent&&t===Ln)&&(this.fragmentTracker.removeFragment(i),this.state=An):("payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(gt.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((t=>{this.state!==yn&&this.state!==Rn&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===xs){const t=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,s?s.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ms&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(gt.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:t}=this,{frag:i,payload:s}=e,r=i.decryptdata;if(s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&fr(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,gr(r.method)).catch((e=>{throw t.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((s=>{const r=self.performance.now();return t.trigger(gt.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:n,tdecrypt:r}}),e.payload=s,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((t=>{this.state!==yn&&this.state!==Rn&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==yn&&(this.state=An),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?vn(tr.getBuffered(i)):"(detached)"})`),Jt(e)){var s;if(e.type!==Tt){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=An)}const t=null==(s=this.levels)?void 0:s[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=An}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:r}=e,n=!r||0===r.length||r.some((e=>!e)),a=new Js(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var r;this.fragCurrent=e;const n=null==t?void 0:t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;!e.encrypted||null!=(r=e.decryptdata)&&r.key?!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=En,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(gt.KEY_LOADED,e),this.state===En&&(this.state=An),e})),this.hls.trigger(gt.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));const o=this.fragPrevious;if(Jt(e)&&(!o||e.sn!==o.sn)){const i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts&&Jt(e)){const r=n.partList;if(r&&s){i>e.end&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(r,e,i);if(o>-1){const l=r[o];let h;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Tn,h=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,s))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,s).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(gt.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(r,i))return Promise.resolve(null)}}if(Jt(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${n?"["+n.startSN+"-"+n.endSN+"]":""}, target: ${parseFloat(i.toFixed(3))}`),ht(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Tn;const l=this.config.progressive;let h;return h=l&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,s))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,l?s:void 0),a]).then((([e])=>(!l&&e&&s&&s(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(gt.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,i,s){return new Promise(((r,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,s).then((s=>{o[t.index]=s;const n=s.part;this.hls.trigger(gt.FRAG_LOADED,s);const a=hn(i.details,e.sn,t.index+1)||un(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});h(a)})).catch(n)};h(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===ft.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(gt.ERROR,t)}else this.hls.trigger(gt.ERROR,{type:dt.OTHER_ERROR,details:ft.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Ln)return void(this.fragCurrent||this.state===yn||this.state===Rn||(this.state=An));const{frag:i,part:s,level:r}=t,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,s,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(null!=e&&e.partList){var i;const r=e.partList[0];if(t>=r.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)){var s;if((this.hls.hasEnoughToStart?(null==(s=this.media)?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:n}=e;if(null==t||!t[s])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=t[s],o=a.details,l=n>-1?hn(o,r,n):null,h=l?l.fragment:ln(o,r,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(e,t,i,s,r){var n;if(!e||this.state!==Ln)return;const{data1:a,data2:o}=e;let l=a;if(a&&o&&(l=Si(a,o)),null==(n=l)||!n.length)return;const h={type:e.type,frag:t,part:i,chunkMeta:s,parent:t.type,data:l};if(this.hls.trigger(gt.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!tr.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const i=t.currentTime,s=tr.bufferInfo(t,i,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,s.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const s=this.getLoadPosition();if(!ht(s))return null;const r=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,r)}getFwdBufferInfoAtPos(e,t,i,s){const r=tr.bufferInfo(e,t,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(r.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(r.nextStart,n.end)-t,s);return tr.bufferInfo(e,t,i)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return i=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-3*t,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=At){var i;const s=null==(i=this.fragmentTracker)?void 0:i.getAppendedFrag(e,t);return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=i[0].start,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const h=r.initialLiveManifestSize;if(s<h)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${h})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t,i);const s=this.hls.startPosition,r=this.hls.liveSyncPosition,h=o?(-1!==s&&s>=n?s:r)||o.start:e;this.log(`Setting startPosition to ${h} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${r} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=h}}else e<=n&&(o=i[0]);if(!o){const i=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,i,t)}let h=this.filterReplacedPrimary(o,t);if(!h&&o){const e=o.sn-t.startSN;h=this.filterReplacedPrimary(i[e+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Fs||i===Ms&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&i.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==e&&i.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Cn(this.hls.config)){var e,t;if(null==(e=this.hls.interstitialsManager)||null==(t=e.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Cn(this.hls.config)&&e.type!==Tt){const i=this.hls.interstitialsManager,s=null==i?void 0:i.bufferingItem;if(s){const i=s.event;if(i){if(i.appendInPlace||Math.abs(e.start-s.start)>1||0===s.start)return null}else{if(e.end<=s.start&&!1===(null==t?void 0:t.live))return null;if(e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}}const r=null==i?void 0:i.playerQueue;if(r)for(let t=r.length;t--;){const i=r[t].interstitial;if(i.appendInPlace&&e.start>=i.startTime&&e.end<=i.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let s=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,s>-1&&i<o.start)break;const l=o.loaded;l?s=-1:(r||o.independent||n)&&o.fragment===t&&(s=a),r=l}return s}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!ht(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(let s=0;s<e.length;++s){const r=e[s];if(ys(t,i,r))return r}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=As(t,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(s=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,h=i.partList,u=!!(this.loadingParts&&null!=h&&h.length&&o);let c;if(u&&o&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var d;c=ms(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(d=this.media)&&d.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const e=c.sn-i.startSN,t=this.fragmentTracker.getState(c);if((t===Fs||t===Ms&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!u||h[0].fragment.sn>c.sn||!i.live&&!u)){if(r&&c.level===r.level){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Fs?t:null}}}return c}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&ht(r);if(n||!a&&!r){!function(e,t){e&&(pn(t,e),!t.alignedSliding&&e&&mn(t,e),t.alignedSliding||!e||t.skippedSegments||nn(e,t,!1))}(i,e);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const s=this.timelineOffset;if(-1===i){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;null!==n&&ht(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;const{media:t}=this;let i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Jt(e)&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Sn)||(this.state=An)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;var s;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(s=this.fragCurrent)?void 0:s.url}`);const r=t.details===ft.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(i,!0);const n=t.errorAction,{action:a,flags:o,retryCount:l=0,retryConfig:h}=n||{},u=!!n&&!!h,c=u&&a===Is,d=u&&!n.resolved&&o===Ps;if(!c&&d&&Jt(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),n.resolved=!0;else if((c||d)&&l<h.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const s=Ss(h,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${h.maxNumRetry} in ${s}ms`),n.resolved=!0,this.retryDate=self.performance.now()+s,this.state=Sn}else if(h&&n){if(this.resetFragmentErrors(e),!(l<h.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${l})`);r||a===Rs||(n.resolved=!0)}else this.state=a===ks?Dn:Rn;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===Ln||this.state===_n){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==t?void 0:t.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===Et&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==yn&&(this.state=An)}afterBufferFlushed(e,t,i){if(!e)return;const s=tr.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===kn&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==yn&&(this.state=An)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){const r=i.details;if(!r)return void this.warn("level.details undefined");var n;if(!Object.keys(e.elementaryStreams).reduce(((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=s?0:tn(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(gt.LEVEL_PTS_UPDATED,{details:r,level:i,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(n=this.transmuxer)?void 0:n.error))){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=_n,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(gt.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===At?"level":"track"}fragInfo(e,t=!0,i){var s,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(null!=(s=t&&!i?e.startPTS:(i||e).start)?s:NaN).toFixed(3)}-${(null!=(r=t&&!i?e.endPTS:(i||e).end)?r:NaN).toFixed(3)}]${i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Cn(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class wn{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;return e.length?(i=1===e.length?e[0]:function(e,t){const i=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}(e,t),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var On,xn={exports:{}};var Mn=(On||(On=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,s,r=[];if(0===this._eventsCount)return r;for(s in e=this._events)t.call(e,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=i?i+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r<n;r++)a[r]=s[r].fn;return a},o.prototype.listenerCount=function(e){var t=i?i+e:e,s=this._events[t];return s?s.fn?1:s.length:0},o.prototype.emit=function(e,t,s,r,n,a){var o=i?i+e:e;if(!this._events[o])return!1;var l,h,u=this._events[o],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,s),!0;case 4:return u.fn.call(u.context,t,s,r),!0;case 5:return u.fn.call(u.context,t,s,r,n),!0;case 6:return u.fn.call(u.context,t,s,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];u.fn.apply(u.context,l)}else{var d,f=u.length;for(h=0;h<f;h++)switch(u[h].once&&this.removeListener(e,u[h].fn,void 0,!0),c){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,t);break;case 3:u[h].fn.call(u[h].context,t,s);break;case 4:u[h].fn.call(u[h].context,t,s,r);break;default:if(!l)for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];u[h].fn.apply(u[h].context,l)}}return!0},o.prototype.on=function(e,t,i){return n(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return n(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,s,r){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||s&&o.context!==s||a(this,n);else{for(var l=0,h=[],u=o.length;l<u;l++)(o[l].fn!==t||r&&!o[l].once||s&&o[l].context!==s)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(xn)),xn.exports),Fn=Bt(Mn);const Nn="1.6.2",Un={};function Bn(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function $n(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Gn(e,t){let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i}function Kn(e,t){const i=t;let s=0;for(;$n(e,t);){s+=10;s+=Gn(e,t+6),Bn(e,t+10)&&(s+=10),t+=s}if(s>0)return e.subarray(i,i+s)}function Vn(e,t){return 255===e[t]&&240==(246&e[t+1])}function Hn(e,t){return 1&e[t+1]?7:9}function Yn(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function jn(e,t){return t+1<e.length&&Vn(e,t)}function Wn(e,t){if(jn(e,t)){const i=Hn(e,t);if(t+i>=e.length)return!1;const s=Yn(e,t);if(s<=i)return!1;const r=t+s;return r===e.length||jn(e,r)}return!1}function qn(e,t,i,s,r){if(!e.samplerate){const n=function(e,t,i,s){const r=t[i+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(gt.ERROR,gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[i+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let u=n;5!==a&&29!==a||(u-=3);const c=[a<<3|(14&u)>>1,(1&u)<<7|o<<3];return xt.log(`manifest codec:${s}, parsed codec:${l}, channels:${o}, rate:${h} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:s}}(t,i,s,r);if(!n)return;_t(e,n)}}function zn(e){return 9216e4/e}function Xn(e,t,i,s,r){const n=s+r*zn(e.samplerate),a=function(e,t){const i=Hn(e,t);if(t+i<=e.length){const s=Yn(e,t)-i;if(s>0)return{headerLength:i,frameLength:s}}}(t,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,h=Math.max(0,i+l-t.length);h?(o=new Uint8Array(l-r),o.set(t.subarray(i+r,t.length),0)):o=t.subarray(i+r,i+l);const u={unit:o,pts:n};return h||e.samples.push(u),{sample:u,length:l,missing:h}}const l=t.length-i;o=new Uint8Array(l),o.set(t.subarray(i,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Qn(e,t){return $n(e,t)&&Gn(e,t+6)+10<=e.length-t}function Zn(e,t){if(e<0)return-Zn(-e,t);const i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){const t=Math.floor(e*i);return(t%2==0?t:t+1)/i}return Math.round(e*i)/i}function Jn(e,t=0,i=1/0){return function(e,t,i,s){const r=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=(c=e,c&&c.buffer instanceof ArrayBuffer&&void 0!==c.byteLength&&void 0!==c.byteOffset?e.byteOffset:0),o=(a+e.byteLength)/n,l=(a+t)/n,h=Math.floor(Math.max(0,Math.min(l,o))),u=Math.floor(Math.min(h+Math.max(i,0),o));var c;return new s(r,h,u-h)}(e,t,i,Uint8Array)}function ea(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=e.data.subarray(1).indexOf(0);if(-1===i)return;const s=Nt(Jn(e.data,1,i)),r=e.data[2+i],n=e.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=Nt(Jn(e.data,3+i,n));let o;return o="--\x3e"===s?Nt(Jn(e.data,4+i+n)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+i+n)),t.mimeType=s,t.pictureType=r,t.description=a,t.data=o,t}function ta(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=Nt(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const i=Nt(e.data.subarray(t),!0);t+=i.length+1;const s=Nt(e.data.subarray(t));return{key:e.type,info:i,data:s}}const t=Nt(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?ea(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const i=Nt(e.data.subarray(t),!0);t+=i.length+1;const s=Nt(e.data.subarray(t));return{key:e.type,info:i,data:s}}const t=Nt(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function ia(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Gn(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}function sa(e){let t=0;const i=[];for(;$n(e,t);){const s=Gn(e,t+6);e[t+5]>>6&1&&(t+=10),t+=10;const r=t+s;for(;t+10<r;){const s=ia(e.subarray(t)),r=ta(s);r&&i.push(r),t+=s.size+10}Bn(e,t)&&(t+=10)}return i}function ra(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function na(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),i=1&t[3];let s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}function aa(e){const t=sa(e);for(let e=0;e<t.length;e++){const i=t[e];if(ra(i))return na(i)}}let oa=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function la(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class ha{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Si(this.cachedData,e),this.cachedData=null);let i,s=Kn(e,0),r=s?s.length:0;const n=this._audioTrack,a=this._id3Track,o=s?aa(s):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&ht(o))&&(this.basePTS=ua(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:oa.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=l}else Qn(e,r)?(s=Kn(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:oa.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,i=r):r++;if(r===l&&i!==l){const t=e.slice(i);this.cachedData?this.cachedData=Si(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:la(),id3Track:a,textTrack:la()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:la(),id3Track:this._id3Track,textTrack:la()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const ua=(e,t,i)=>{if(ht(e))return 90*e;return 9e4*t+(i?9e4*i.baseTime/i.timescale:0)};let ca=null;const da=[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],fa=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ga=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],pa=[0,1,1,4];function ma(e,t,i,s,r){if(i+24>t.length)return;const n=va(t,i);if(n&&i+n.frameLength<=t.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function va(e,t){const i=e[t+1]>>3&3,s=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*da[14*(3===i?3-s:3===s?3:4)+r-1],h=fa[3*(3===i?0:2===i?1:2)+n],u=3===o?1:2,c=ga[i][s],d=pa[s],f=8*c*d,g=Math.floor(c*l/h+a)*d;if(null===ca){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ca=e?parseInt(e[1]):0}return!!ca&&ca<=87&&2===s&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:u,frameLength:g,samplesPerFrame:f}}}function ya(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Aa(e,t){return t+1<e.length&&ya(e,t)}function Ea(e,t){if(t+1<e.length&&ya(e,t)){const i=4,s=va(e,t);let r=i;null!=s&&s.frameLength&&(r=s.frameLength);const n=t+r;return n===e.length||Aa(e,n)}return!1}const Ta=(e,t)=>{let i=0,s=5;t+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=e[t];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,i=i?i<<o|r[0]:r[0],t+=1,s-=o}return i};class Sa extends ha{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const s=ba(e,t,i,this.basePTS,this.frameIndex);if(-1!==s){return{sample:e.samples[e.samples.length-1],length:s,missing:0}}}static probe(e){if(!e)return!1;const t=Kn(e,0);if(!t)return!1;const i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==aa(t)&&Ta(e,i)<16}}function ba(e,t,i,s,r){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>t.length)return-1;const h=t[i+6]>>5;let u=0;2===h?u+=2:(1&h&&1!==h&&(u+=2),4&h&&(u+=2));const c=(t[i+6]<<8|t[i+7])>>12-u&1,d=[2,1,2,3,3,4,4,5][h]+c,f=t[i+5]>>3,g=7&t[i+5],p=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),m=s+r*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=p,e.channelCount=d,e.samplerate=a,e.samples.push({unit:v,pts:m}),l}const La=/\/emsg[-/]ID3/i;function _a(e,t){return ht(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class ka{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new js(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Gs)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((r=>{const n=new Uint8Array(r);s.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}))}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t);let s=0;for(let t=32;t<e.length-16;t+=160,s+=16)i.set(e.subarray(t,t+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let t=32;t<e.length-16;t+=160,s+=16)e.set(i.subarray(s,s+16),t);return e}decryptAvcSample(e,t,i,s,r){const n=Ri(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}))}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void s();const r=e[t].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,s,n),this.decrypter.isSync())))return}}}}class Ra{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i,s=this.VideoSample;if(s&&0!==s.units.length||(s=e[e.length-1]),null!=(t=s)&&t.units){const e=s.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const i=t.samples,s=i.length;if(!s)return void t.dropped++;{const t=i[s-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o,l,h,u=0,c=-1,d=0;for(-1===r&&(c=0,d=this.getNALuType(t,0),r=0,u=1);u<s;)if(o=t[u++],r)if(1!==r)if(o)if(1===o){if(l=u-r-1,c>=0){const e={data:t.subarray(c,l),type:d};a.push(e)}else{const i=this.getLastNalUnit(e.samples);i&&(n&&u<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=Si(i.data,t.subarray(0,l)),i.state=0))}u<s?(h=this.getNALuType(t,u),c=u,d=h,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(c>=0&&r>=0){const e={data:t.subarray(c,s),type:d,state:r};a.push(e)}if(0===a.length){const i=this.getLastNalUnit(e.samples);i&&(i.data=Si(i.data,t))}return e.naluState=r,a}}class Ia{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&xt.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Da extends Ra{parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach((s=>{var r,l;switch(s.type){case 1:{let t=!1;n=!0;const r=s.data;if(o&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var h;if(t)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,ki(s.data,1,i.pts,t.samples);break;case 7:{var u,c;n=!0,o=!0;const t=s.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(u=e.pixelRatio)?void 0:u[0])!==i.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];const s=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:n=!0,e.pps=[s.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(s)}})),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Ia(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i,s=8,r=8;for(let n=0;n<e;n++)0!==r&&(i=t.readEG(),r=(s+i+256)%256),s=0===r?s:r}readSPS(e){const t=new Ia(e);let i,s,r,n=0,a=0,o=0,l=0;const h=t.readUByte.bind(t),u=t.readBits.bind(t),c=t.readUEG.bind(t),d=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),p=t.skipUEG.bind(t),m=this.skipScalingList.bind(this);h();const v=h();if(u(5),f(3),h(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=c();if(3===e&&f(1),p(),p(),f(1),d())for(s=3!==e?8:12,r=0;r<s;r++)d()&&m(r<6?16:64,t)}p();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),i=c(),r=0;r<i;r++)g();p(),f(1);const A=c(),E=c(),T=u(1);0===T&&f(1),f(1),d()&&(n=c(),a=c(),o=c(),l=c());let S=[1,1];if(d()&&d()){switch(h()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(A+1)-2*n-2*a),height:(2-T)*(E+1)*16-(T?2:4)*(o+l),pixelRatio:S}}}class Pa extends Ra{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach((s=>{var r,l;switch(s.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var h;if(n=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,ki(s.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=_t(e.params,this.readVPS(s.data)),this.initVPS=s.data),e.vps=[s.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],s.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(s.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const i in t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,s.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(s.data);for(const i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,s.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}if(a&&n){a.units.push(s)}})),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s<e.byteLength;s++)s>=2&&3===e[s]&&0===e[s-1]&&0===e[s-2]||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Ia(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new Ia(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),m=t.readUByte(),v=[],y=[];for(let e=0;e<i;e++)v.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e<i;e++)v[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[e]&&t.readUByte();t.readUEG();const A=t.readUEG();3==A&&t.skipBits(1);const E=t.readUEG(),T=t.readUEG(),S=t.readBoolean();let b=0,L=0,_=0,k=0;S&&(b+=t.readUEG(),L+=t.readUEG(),_+=t.readUEG(),k+=t.readUEG());const R=t.readUEG(),I=t.readUEG(),D=t.readUEG();for(let e=t.readBoolean()?0:i;e<=i;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++){if(t.readBoolean()){const i=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<i;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const P=t.readUEG();let C=0;for(let e=0;e<P;e++){let i=!1;if(0!==e&&(i=t.readBoolean()),i){e===P&&t.readUEG(),t.readBoolean(),t.readUEG();let i=0;for(let e=0;e<=C;e++){const e=t.readBoolean();let s=!1;e||(s=t.readBoolean()),(e||s)&&i++}C=i}else{const e=t.readUEG(),i=t.readUEG();C=e+i;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let e=0;e<i;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let i=0;i<e;i++){for(let e=0;e<D+4;e++)t.readBits(1);t.readBits(1)}}let w=0,O=1,x=1,M=!0,F=1,N=0;t.readBoolean(),t.readBoolean();let U=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(O=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],x=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(O=t.readBits(16),x=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(t.readBoolean()){t.readBits(3),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())}t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),U=t.readBoolean(),U&&(b+=t.readUEG(),L+=t.readUEG(),_+=t.readUEG(),k+=t.readUEG());if(t.readBoolean()){F=t.readBits(32),N=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),s=t.readBoolean();let r=!1;(e||s)&&(r=t.readBoolean(),r&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),r&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=i;n++){M=t.readBoolean();let i=!1;M||t.readBoolean()?t.readEG():i=t.readBoolean();const n=i?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(s)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),w=t.readUEG())}let B=E,$=T;if(S||U){let e=1,t=1;1===A?e=t=2:2==A&&(e=2),B=E-e*L-e*b,$=T-t*k-t*_}const G=s?["A","B","C"][s]:"",K=a<<24|o<<16|l<<8|h;let V=0;for(let e=0;e<32;e++)V=(V|(K>>e&1)<<31-e)>>>0;let H=V.toString(16);1===n&&"2"===H&&(H="6");return{codecString:`hvc1.${G}${n}.${H}.${r?"H":"L"}${m}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[u,c,d,f,g,p],general_level_idc:m,bit_depth:R+8,bit_depth_luma_minus8:R,bit_depth_chroma_minus8:I,min_spatial_segmentation_idc:w,chroma_format_idc:A,frame_rate:{fixed:M,fps:N/F}},width:B,height:$,pixelRatio:[O,x]}}readPPS(e){const t=new Ia(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2);t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),s=t.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Ca=188;class wa{constructor(e,t,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){const i=wa.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){const t=e.length;let i=Math.min(940,t-Ca)+1,s=0;for(;s<i;){let r=!1,n=-1,a=0;for(let o=s;o<t;o+=Ca){if(71!==e[o]||t-o!==Ca&&71!==e[o+Ca]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,e.length-Ca)+1)),r||(r=0===Oa(e,o)),r&&a>1&&(0===n&&a>2||o+Ca>i))return n}s++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:ni[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=wa.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=wa.createTrack("audio",s),this._id3Track=wa.createTrack("id3"),this._txtTrack=wa.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,s=!1){let r;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,u=n.pesData,c=a.pid,d=o.pid,f=a.pesData,g=o.pesData,p=null,m=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=Si(this.remainderData,e)).length,this.remainderData=null),y<Ca&&!s)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const A=Math.max(0,wa.syncOffset(e));y-=(y-A)%Ca,y<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let E=0;for(let t=A;t<y;t+=Ca)if(71===e[t]){const s=!!(64&e[t+1]),y=Oa(e,t);let E;if((48&e[t+3])>>4>1){if(E=t+5+e[t+4],E===t+Ca)continue}else E=t+4;switch(y){case h:if(s){if(u&&(r=Ua(u,this.logger))){if(null===this.videoParser)switch(n.segmentCodec){case"avc":this.videoParser=new Da;break;case"hevc":this.videoParser=new Pa}null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)}u={data:[],size:0}}u&&(u.data.push(e.subarray(E,t+Ca)),u.size+=t+Ca-E);break;case c:if(s){if(f&&(r=Ua(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(e.subarray(E,t+Ca)),f.size+=t+Ca-E);break;case d:s&&(g&&(r=Ua(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(E,t+Ca)),g.size+=t+Ca-E);break;case 0:s&&(E+=e[E]+1),v=this._pmtId=xa(e,E);break;case v:{s&&(E+=e[E]+1);const r=Ma(e,E,this.typeSupported,i,this.observer,this.logger);h=r.videoPid,h>0&&(n.pid=h,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),d=r.id3Pid,d>0&&(o.pid=d),null===p||m||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${p}'. Backtracking to sync byte @${A} to parse all TS packets.`),p=null,t=A-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=y}}else E++;E>0&&Fa(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=u,a.pesData=f,o.pesData=g;const T={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return s&&this.extractRemainingSamples(T),T}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:r}=e,n=i.pesData,a=t.pesData,o=s.pesData;let l;if(n&&(l=Ua(n,this.logger))){if(null===this.videoParser)switch(i.segmentCodec){case"avc":this.videoParser=new Da;break;case"hevc":this.videoParser=new Pa}null!==this.videoParser&&(this.videoParser.parsePES(i,r,l,!0),i.pesData=null)}else i.pesData=n;if(a&&(l=Ua(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Ua(o,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=o}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new ka(this.observer,this.config,t);return this.decrypt(s,r)}decrypt(e,t){return new Promise((i=>{const{audioTrack:s,videoTrack:r}=e;s.samples&&"aac"===s.segmentCodec?t.decryptAacSamples(s.samples,0,(()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,(()=>{i(e)})):i(e)})):r.samples&&t.decryptAvcSamples(r.samples,0,0,(()=>{i(e)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let r,n,a,o=t.data;if(s){this.aacOverFlow=null;const t=s.missing,r=s.sample.unit.byteLength;if(-1===t)o=Si(s.sample.unit,o);else{const n=r-t;s.sample.unit.set(o.subarray(0,t),n),e.samples.push(s.sample),i=s.missing}}for(r=i,n=o.length;r<n-1&&!jn(o,r);r++);if(r!==i){let e;const t=r<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",Fa(this.observer,new Error(e),t,this.logger),!t)return}if(qn(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=zn(e.samplerate);a=s.sample.pts+t}}let l,h=0;for(;r<n;){if(l=Xn(e,o,r,a,h),r+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;r<n-1&&!jn(o,r);r++);}}parseMPEGPES(e,t){const i=t.data,s=i.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<s;)if(Aa(i,n)){const t=ma(e,i,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const i=t.data,s=t.pts;if(void 0===s)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=i.length;let n,a=0,o=0;for(;o<r&&(n=ba(e,i,o,s,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=_t({},t,{type:this._videoTrack?oa.emsg:oa.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Oa(e,t){return((31&e[t+1])<<8)+e[t+2]}function xa(e,t){return(31&e[t+10])<<8|e[t+11]}function Ma(e,t,i,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=Oa(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!s){Na("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){Na("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){Na("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let s=t+5,r=l;for(;r>2;){if(106===e[s])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[s+1]+2;s+=t,r-=t}}break;case 194:case 135:return Fa(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=l+5}return a}function Fa(e,t,i,s){s.warn(`parsing error: ${t.message}`),e.emit(gt.ERROR,gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function Na(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Ua(e,t){let i,s,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Si(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>e.size-6)return null;const h=i[7];192&h&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=i[8];let u=r+9;if(e.size<=u)return null;e.size-=u;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){i=l[e];let t=i.byteLength;if(u){if(u>t){u-=t;continue}i=i.subarray(u),t-=u,u=0}c.set(i,o),o+=t}return s&&(s-=r+3),{data:c,pts:n,dts:a,len:s}}return null}class Ba{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const $a=Math.pow(2,32)-1;class Ga{static init(){let e;for(e in Ga.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:[]},Ga.types)Ga.types.hasOwnProperty(e)&&(Ga.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Ga.HDLR_TYPES={video:t,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Ga.STTS=Ga.STSC=Ga.STCO=r,Ga.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ga.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ga.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Ga.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]);Ga.FTYP=Ga.box(Ga.types.ftyp,n,o,n,a),Ga.DINF=Ga.box(Ga.types.dinf,Ga.box(Ga.types.dref,s))}static box(e,...t){let i=8,s=t.length;const r=s;for(;s--;)i+=t[s].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),s=0,i=8;s<r;s++)n.set(t[s],i),i+=t[s].byteLength;return n}static hdlr(e){return Ga.box(Ga.types.hdlr,Ga.HDLR_TYPES[e])}static mdat(e){return Ga.box(Ga.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/($a+1)),s=Math.floor(t%($a+1));return Ga.box(Ga.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(e){return Ga.box(Ga.types.mdia,Ga.mdhd(e.timescale||0,e.duration||0),Ga.hdlr(e.type),Ga.minf(e))}static mfhd(e){return Ga.box(Ga.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Ga.box(Ga.types.minf,Ga.box(Ga.types.smhd,Ga.SMHD),Ga.DINF,Ga.stbl(e)):Ga.box(Ga.types.minf,Ga.box(Ga.types.vmhd,Ga.VMHD),Ga.DINF,Ga.stbl(e))}static moof(e,t,i){return Ga.box(Ga.types.moof,Ga.mfhd(e),Ga.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Ga.trak(e[t]);return Ga.box.apply(null,[Ga.types.moov,Ga.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(Ga.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Ga.trex(e[t]);return Ga.box.apply(null,[Ga.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/($a+1)),s=Math.floor(t%($a+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Ga.box(Ga.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,r;for(s=0;s<t.length;s++)r=t[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Ga.box(Ga.types.sdtp,i)}static stbl(e){return Ga.box(Ga.types.stbl,Ga.stsd(e),Ga.box(Ga.types.stts,Ga.STTS),Ga.box(Ga.types.stsc,Ga.STSC),Ga.box(Ga.types.stsz,Ga.STSZ),Ga.box(Ga.types.stco,Ga.STCO))}static avc1(e){let t,i,s,r=[],n=[];for(t=0;t<e.sps.length;t++)i=e.sps[t],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(t=0;t<e.pps.length;t++)i=e.pps[t],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=Ga.box(Ga.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return Ga.box(Ga.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,Ga.box(Ga.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ga.box(Ga.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,u>>24,u>>16&255,u>>8&255,255&u])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return Ga.box(Ga.types.mp4a,Ga.audioStsd(e),Ga.box(Ga.types.esds,Ga.esds(e)))}static mp3(e){return Ga.box(Ga.types[".mp3"],Ga.audioStsd(e))}static ac3(e){return Ga.box(Ga.types["ac-3"],Ga.audioStsd(e),Ga.box(Ga.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return Ga.box(Ga.types.stsd,Ga.STSD,Ga.mp4a(e));if("ac3"===t&&e.config)return Ga.box(Ga.types.stsd,Ga.STSD,Ga.ac3(e));if("mp3"===t&&"mp3"===e.codec)return Ga.box(Ga.types.stsd,Ga.STSD,Ga.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return Ga.box(Ga.types.stsd,Ga.STSD,Ga.avc1(e));if("hevc"===t&&e.vps)return Ga.box(Ga.types.stsd,Ga.STSD,Ga.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,r=e.height||0,n=Math.floor(i/($a+1)),a=Math.floor(i%($a+1));return Ga.box(Ga.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,255&s,0,0,r>>8&255,255&r,0,0]))}static traf(e,t){const i=Ga.sdtp(e),s=e.id,r=Math.floor(t/($a+1)),n=Math.floor(t%($a+1));return Ga.box(Ga.types.traf,Ga.box(Ga.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Ga.box(Ga.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])),Ga.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Ga.box(Ga.types.trak,Ga.tkhd(e),Ga.mdia(e))}static trex(e){const t=e.id;return Ga.box(Ga.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r);let a,o,l,h,u,c;for(t+=8+r,n.set(["video"===e.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<s;a++)o=i[a],l=o.duration,h=o.size,u=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,61440&u.degradPrio,15&u.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Ga.box(Ga.types.trun,n)}static initSegment(e){Ga.types||Ga.init();const t=Ga.moov(e);return Si(Ga.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],s=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let r=s.length;for(let e=0;e<i.length;e+=1){r+=3;for(let t=0;t<i[e].length;t+=1)r+=2+i[e][t].length}const n=new Uint8Array(r);n.set(s,0),r=s.length;const a=i.length-1;for(let e=0;e<i.length;e+=1){n.set(new Uint8Array([32+e|(e===a?128:0),0,i[e].length]),r),r+=3;for(let t=0;t<i[e].length;t+=1)n.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),r),r+=2,n.set(i[e][t],r),r+=i[e][t].length}const o=Ga.box(Ga.types.hvcC,n),l=e.width,h=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return Ga.box(Ga.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,h>>8&255,255&h,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,Ga.box(Ga.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ga.box(Ga.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))}}Ga.types=void 0,Ga.HDLR_TYPES=void 0,Ga.STTS=void 0,Ga.STSC=void 0,Ga.STCO=void 0,Ga.STSZ=void 0,Ga.VMHD=void 0,Ga.SMHD=void 0,Ga.STSD=void 0,Ga.FTYP=void 0,Ga.DINF=void 0;function Ka(e,t,i=1,s=!1){const r=e*t*i;return s?Math.round(r):r}function Va(e,t=!1){return Ka(e,1e3,1/9e4,t)}let Ha,Ya=null,ja=null;function Wa(e,t,i,s){return{duration:t,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class qa{constructor(e,t,i,s){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.ISGenerated=!1,null===Ya){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ya=e?parseInt(e[1]):0}if(null===ja){const e=navigator.userAgent.match(/Safari\/(\d+)/i);ja=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,s=e.reduce(((e,s)=>{let r=s.pts,n=r-e;return n<-4294967296&&(t=!0,r=za(r,i),n=r-e),n>0?e:r}),i);return t&&this.logger.debug("PTS rollover detected"),s}remux(e,t,i,s,r,n,a,o){let l,h,u,c,d,f,g=r,p=r;const m=e.pid>-1,v=t.pid>-1,y=t.samples.length,A=e.samples.length>0,E=a&&y>0||y>1;if((!m||A)&&(!v||E)||this.ISGenerated||a){if(this.ISGenerated){var T,S,b,L;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(S=e.pixelRatio)?void 0:S[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(L=e.pixelRatio)?void 0:L[1]))||!e&&E||null===this.nextAudioPts&&A)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,n));const i=this.isVideoContiguous;let s,a=-1;if(E&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.logger.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,p+=(t.samples[0].pts-e)/t.inputTimeScale,s=p}else-1===a&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(A&&E){const i=this.getVideoStartPts(t.samples),s=(za(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,s),p+=Math.max(0,-s)}if(A){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||E||o===Et?p:void 0),E){const s=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,p,i,s)}}else E&&(l=this.remuxVideo(t,p,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(d=Xa(i,r,this._initPTS,this._initDTS)),s.samples.length&&(c=Qa(s,r,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:c,id3:d}}generateIS(e,t,i,s){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h,u,c,d=!l||s,f="audio/mp4";if(d&&(h=u=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Ga.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(c=e.inputTimeScale,l&&c===l.timescale?d=!1:h=u=r[0].pts-Math.round(c*i))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ga.initSegment([t]),metadata:{width:t.width,height:t.height}},d)if(c=t.inputTimeScale,l&&c===l.timescale)d=!1;else{const e=this.getVideoStartPts(n),t=Math.round(c*i);u=Math.min(u,za(n[0].dts,e)-t),h=Math.min(h,e-t)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:h,timescale:c},this._initDTS={baseTime:u,timescale:c}):h=c=void 0,{tracks:o,initPTS:h,timescale:c}}remuxVideo(e,t,i,s){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS;let h,u,c=this.nextAvcDts,d=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,m=!1;if(!i||null===c){const e=t*r,s=n[0].pts-za(n[0].dts,n[0].pts);Ya&&null!==c&&Math.abs(e-s-c)<15e3?i=!0:c=e-s}const v=l.baseTime*r/l.timescale;for(let e=0;e<o;e++){const t=n[e];t.pts=za(t.pts-v,c),t.dts=za(t.dts-v,c),t.dts<n[e>0?e-1:e].dts&&(m=!0)}m&&n.sort((function(e,t){const i=e.dts-t.dts,s=e.pts-t.pts;return i||s})),h=n[0].dts,u=n[n.length-1].dts;const y=u-h,A=y?Math.round(y/(o-1)):f||e.inputTimeScale/30;if(i){const i=h-c,s=i>A,r=i<-1;if((s||r)&&(s?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Va(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Va(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||c>=n[0].pts||Ya)){h=c;const e=n[0].pts-i;if(s)n[0].dts=h,n[0].pts=e;else{let t=!0;for(let s=0;s<n.length&&!(n[s].dts>e&&t);s++){const e=n[s].pts;if(n[s].dts-=i,n[s].pts-=i,s<n.length-1){const i=n[s+1].pts;t=i<=n[s].pts==i<=e}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${Va(e,!0)}/${Va(h,!0)}, delta: ${Va(i,!0)} ms`)}}h=Math.max(0,h);let E=0,T=0,S=h;for(let e=0;e<o;e++){const t=n[e],i=t.units,s=i.length;let r=0;for(let e=0;e<s;e++)r+=i[e].data.length;T+=r,E+=s,t.length=r,t.dts<S?(t.dts=S,S+=A/4|0||1):S=t.dts,g=Math.min(t.pts,g),p=Math.max(t.pts,p)}u=n[o-1].dts;const b=T+4*E+8;let L;try{L=new Uint8Array(b)}catch(e){return void this.observer.emit(gt.ERROR,gt.ERROR,{type:dt.MUX_ERROR,details:ft.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:b,reason:`fail allocating video mdat ${b}`})}const _=new DataView(L.buffer);_.setUint32(0,b),L.set(Ga.types.mdat,4);let k=!1,R=Number.POSITIVE_INFINITY,I=Number.POSITIVE_INFINITY,D=Number.NEGATIVE_INFINITY,P=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=n[e],i=t.units;let l,h=0;for(let e=0,t=i.length;e<t;e++){const t=i[e],s=t.data,r=t.data.byteLength;_.setUint32(d,r),d+=4,L.set(s,d),d+=r,h+=4+r}if(e<o-1)f=n[e+1].dts-t.dts,l=n[e+1].pts-t.pts;else{const i=this.config,a=e>0?t.dts-n[e-1].dts:A;if(l=e>0?t.pts-n[e-1].pts:A,i.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(i.maxBufferHole*r),n=(s?g+s*r:this.nextAudioPts)-t.pts;n>e?(f=n-a,f<0?f=a:k=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const u=Math.round(t.pts-t.dts);R=Math.min(R,f),D=Math.max(D,f),I=Math.min(I,l),P=Math.max(P,l),a.push(Wa(t.key,f,h,u))}if(a.length)if(Ya){if(Ya<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(ja&&P-I<D-R&&A/D<.025&&0===a[0].cts){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=h;for(let t=0,i=a.length;t<i;t++){const s=e+a[t].duration,r=e+a[t].cts;if(t<i-1){const e=s+a[t+1].cts;a[t].duration=e-r}else a[t].duration=t?a[t-1].duration:A;a[t].cts=0,e=s}}f=k||!f?A:f,this.nextAvcDts=c=u+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const C={data1:Ga.moof(e.sequenceNumber++,h,_t(e,{samples:a})),data2:L,startPTS:g/r,endPTS:(p+f)/r,startDTS:h/r,endDTS:c/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,C}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,i,s,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,h=this._initPTS,u="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],d=void 0!==r;let f=e.samples,g=u?0:8,p=this.nextAudioPts||-1;const m=t*n,v=h.baseTime*n/h.timescale;if(this.isAudioContiguous=i=i||f.length&&p>0&&(s&&Math.abs(m-p)<9e3||Math.abs(za(f[0].pts-v,m)-p)<20*l),f.forEach((function(e){e.pts=za(e.pts-v,m)})),!i||p<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;p=0===r?0:s&&!d?Math.max(0,m):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let i=0,s=p;i<f.length;i++){const r=f[i],a=r.pts,o=a-s,h=Math.abs(1e3*o/n);if(o<=-t*l&&d)0===i&&(this.logger.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=p=s=a);else if(o>=t*l&&h<1e4&&d){let t=Math.round(o/l);s=a-t*l,s<0&&(t--,s+=l),0===i&&(this.nextAudioPts=p=s),this.logger.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(s/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){const t=Math.max(s,0);let n=Ba.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);n||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=r.unit.subarray()),f.splice(i,0,{unit:n,pts:t}),s+=l,i++}}r.pts=s,s+=l}}let y,A=null,E=null,T=0,S=f.length;for(;S--;)T+=f[S].unit.byteLength;for(let t=0,s=f.length;t<s;t++){const s=f[t],r=s.unit;let n=s.pts;if(null!==E){c[t-1].duration=Math.round((n-E)/a)}else{if(i&&"aac"===e.segmentCodec&&(n=p),A=n,!(T>0))return;T+=g;try{y=new Uint8Array(T)}catch(e){return void this.observer.emit(gt.ERROR,gt.ERROR,{type:dt.MUX_ERROR,details:ft.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:T,reason:`fail allocating audio mdat ${T}`})}if(!u){new DataView(y.buffer).setUint32(0,T),y.set(Ga.types.mdat,4)}}y.set(r,g);const l=r.byteLength;g+=l,c.push(Wa(!0,o,l,0)),E=n}const b=c.length;if(!b)return;const L=c[c.length-1];this.nextAudioPts=p=E+a*L.duration;const _=u?new Uint8Array(0):Ga.moof(e.sequenceNumber++,A/a,_t({},e,{samples:c}));e.samples=[];const k=A/n,R=p/n,I={data1:_,data2:y,startPTS:k,endPTS:R,startDTS:k,endDTS:R,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,I}}function za(e,t){let i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function Xa(e,t,i,s){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let a=0;a<r;a++){const r=e.samples[a];r.pts=za(r.pts-i.baseTime*n/i.timescale,t*n)/n,r.dts=za(r.dts-s.baseTime*n/s.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function Qa(e,t,i){const s=e.samples.length;if(!s)return;const r=e.inputTimeScale;for(let n=0;n<s;n++){const s=e.samples[n];s.pts=za(s.pts-i.baseTime*r/i.timescale,t*r)/r}e.samples.sort(((e,t)=>e.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}function Za(e,t){const i=null==e?void 0:e.codec;if(i&&i.length>4)return i;if(t===zt){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return $i(i,!1)}return xt.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return xt.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1"}try{Ha=self.performance.now.bind(self.performance)}catch(e){Ha=Date.now}const Ja=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const r=this.videoTrack=la("video",1),n=this.audioTrack=la("audio",1),a=this.txtTrack=la("text",1);if(this.id3Track=la("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=gi(e);if(o.video){const{id:e,timescale:t,codec:i,supplemental:s}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=i,r.supplemental=s}if(o.audio){const{id:e,timescale:t,codec:i}=o.audio;n.id=e,n.timescale=t,n.codec=i}a.id=ni.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let i=0;i<t;){const s=li(e,i);if(s>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=s>1?i+s:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Si(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},i=di(e,["moof"]);if(i.length<2)return t.remainder=e,t;const s=i[i.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}(i);this.remainderData=t.remainder,s.samples=t.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,t);return r.samples=bi(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=bi(e,t),{videoTrack:t,audioTrack:la(),id3Track:s,textTrack:la()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=di(e.samples,["emsg"]);s&&s.forEach((e=>{const s=function(e){const t=e[0];let i="",s="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==ai(e.subarray(h,h+1));)i+=ai(e.subarray(h,h+1)),h+=1;for(i+=ai(e.subarray(h,h+1)),h+=1;"\0"!==ai(e.subarray(h,h+1));)s+=ai(e.subarray(h,h+1)),h+=1;s+=ai(e.subarray(h,h+1)),h+=1,r=li(e,12),n=li(e,16),o=li(e,20),l=li(e,24),h=28}else if(1===t){h+=4,r=li(e,h),h+=4;const t=li(e,h);h+=4;const n=li(e,h);for(h+=4,a=2**32*t+n,ut(a)||(a=Number.MAX_SAFE_INTEGER,xt.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=li(e,h),h+=4,l=li(e,h),h+=4;"\0"!==ai(e.subarray(h,h+1));)i+=ai(e.subarray(h,h+1)),h+=1;for(i+=ai(e.subarray(h,h+1)),h+=1;"\0"!==ai(e.subarray(h,h+1));)s+=ai(e.subarray(h,h+1)),h+=1;s+=ai(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(La.test(s.schemeIdUri)){const e=_a(s,t);let r=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=s.payload;i.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:oa.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=_a(s,t);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:e,pts:e,type:oa.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class{constructor(e,t,i,s){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.logger=s}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(function(e,t){if(!e||!t)return e;const i=t.keyId;i&&t.isCommonEncryption&&di(e,["moov","trak"]).forEach((e=>{const t=di(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let s=di(t,["enca"]);const r=s.length>0;r||(s=di(t,["encv"])),s.forEach((e=>{di(r?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=Ei(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(xt.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${Ut(e)} -> ${Ut(i)}`),t.set(i,8))}}))}))}));return e}(e,s)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const s=this.initData=gi(e);s.audio&&(t=Za(s.audio,zt)),s.video&&(i=Za(s.video,Xt));const r={};s.audio&&s.video?r.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:s.video.supplemental,initSegment:e,id:"main"}:s.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:s.video?r.video={container:"video/mp4",codec:i,supplemental:s.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,i,s,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};ht(h)||(h=this.lastEndTime=r||0);const c=t.samples;if(null==c||!c.length)return u;const d={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t){let i=0,s=0,r=0;const n=di(e,["moof","traf"]);for(let e=0;e<n.length;e++){const a=n[e],o=di(a,["tfhd"])[0],l=t[li(o,4)];if(!l)continue;const h=l.default,u=li(o,0)|(null==h?void 0:h.flags);let c=null==h?void 0:h.duration;8&u&&(c=li(o,2&u?12:8));const d=l.timescale||9e4,f=di(a,["trun"]);for(let e=0;e<f.length;e++)i=Ti(f[e]),!i&&c&&(i=c*li(f[e],4)),l.type===Xt?s+=i/d:l.type===zt&&(r+=i/d)}if(0===s&&0===r){let t=1/0,i=0,s=0;const r=di(e,["sidx"]);for(let e=0;e<r.length;e++){const n=fi(r[e]);if(null!=n&&n.references){t=Math.min(t,n.earliestPresentationTime/n.timescale);const e=n.references.reduce(((e,t)=>e+t.info.duration||0),0);i=Math.max(i,e+n.earliestPresentationTime/n.timescale),s=i-t}}if(s&&ht(s))return s}return s||r}(c,f),p=function(e,t){return di(t,["moof","traf"]).reduce(((t,i)=>{const s=di(i,["tfdt"])[0],r=s[0],n=di(i,["tfhd"]).reduce(((t,i)=>{const n=li(i,4),a=e[n];if(a){let e=li(s,4);if(1===r){if(e===si)return xt.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=si+1,e+=li(s,8)}const i=e/(a.timescale||9e4);if(ht(i)&&(null===t||i<t))return i}return t}),null);return null!==n&&ht(n)&&(null===t||n<t)?n:t}),null)}(f,c),m=null===p?r:p;!n&&l||!function(e,t,i,s){if(null===e)return!0;const r=Math.max(s,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>r}(l,m,r,g)&&d.timescale===l.timescale||(d.initPTS=m-r,l&&1===l.timescale&&this.logger.warn(`Adjusting initPTS @${r} from ${l.baseTime/l.timescale} to ${d.initPTS}`),this.initPTS=l={baseTime:d.initPTS,timescale:1});const v=e?m-l.baseTime/l.timescale:h,y=v+g;!function(e,t,i){di(t,["moof","traf"]).forEach((t=>{di(t,["tfhd"]).forEach((s=>{const r=li(s,4),n=e[r];if(!n)return;const a=n.timescale||9e4;di(t,["tfdt"]).forEach((e=>{const t=e[0],s=i*a;if(s){let i=li(e,4);if(0===t)i-=s,i=Math.max(i,0),ci(e,4,i);else{i*=Math.pow(2,32),i+=li(e,8),i-=s,i=Math.max(i,0);const t=Math.floor(i/(si+1)),r=Math.floor(i%(si+1));ci(e,4,t),ci(e,8,r)}}}))}))}))}(f,c,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const A=!!f.audio,E=!!f.video;let T="";A&&(T+="audio"),E&&(T+="video");const S={data1:c,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:T,hasAudio:A,hasVideo:E,nb:1,dropped:0};return u.audio="audio"===S.type?S:void 0,u.video="audio"!==S.type?S:void 0,u.initSegment=d,u.id3=Xa(i,r,l,l),s.samples.length&&(u.text=Qa(s,r,l)),u}}},{demux:wa,remux:qa},{demux:class extends ha{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Kn(e,0);let s=(null==i?void 0:i.length)||0;if(Ea(e,s))return!1;for(let i=e.length;s<i;s++)if(Wn(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Vn(e,t)&&Yn(e,t)<=e.length-t}(e,t)}appendFrame(e,t,i){qn(e,this.observer,t,i,e.manifestCodec);const s=Xn(e,t,i,this.basePTS,this.frameIndex);if(s&&0===s.missing)return s}},remux:qa},{demux:class extends ha{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Kn(e,0);let i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==aa(t)&&Ta(e,i)<=16)return!1;for(let t=e.length;i<t;i++)if(Ea(e,i))return xt.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return ya(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,i){if(null!==this.basePTS)return ma(e,t,i,this.basePTS,this.frameIndex)}},remux:qa}];Ja.splice(2,0,{demux:Sa,remux:qa});class eo{constructor(e,t,i,s,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const r=i.transmuxing;r.executeStart=Ha();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:h,trackSwitch:u,accurateTimeOffset:c,timeOffset:d,initSegmentChange:f}=s||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:v,initSegmentData:y}=o,A=function(e,t){let i=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(n,t);if(A&&fr(A.method)){const e=this.getDecrypter(),t=gr(A.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,A.key.buffer,A.iv.buffer,t).then((e=>{const t=this.push(e,null,i);return this.decryptionPromise=null,t})),this.decryptionPromise;{let s=e.softwareDecrypt(n,A.key.buffer,A.iv.buffer,t);if(i.part>-1){const t=e.flush();s=t?t.buffer:t}if(!s)return r.executeEnd=Ha(),to(i);n=new Uint8Array(s)}}const E=this.needsProbing(h,u);if(E){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(gt.ERROR,gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=Ha(),to(i)}(h||u||f||E)&&this.resetInitSegment(y,g,p,v,t),(h||f||E)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const T=this.transmux(n,A,d,c,i);this.asyncResult=io(T);const S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,r.executeEnd=Ha(),T}flush(e){const t=e.transmuxing;t.executeStart=Ha();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then((()=>this.flush(e)));const n=[],{timeOffset:a}=s;if(i){const t=i.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=Ha();const i=[to(e)];return this.asyncResult?Promise.resolve(i):i}const h=o.flush(a);return io(h)?(this.asyncResult=!0,h.then((t=>(this.flushRemux(n,t,e),n)))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===At?"level":"track"} ${i.level}`);const h=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Ha()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,i,s),a.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,r){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,s,r):this.transmuxUnencrypted(e,i,s,r),n}transmuxUnencrypted(e,t,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer.demuxSampleAes(e,t,i).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,s,!1,this.id),chunkMeta:r})))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;let r;for(let t=0,i=Ja.length;t<i;t++){var n;if(null!=(n=Ja[t].demux)&&n.probe(e,this.logger)){r=Ja[t];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,h=r.demux;o&&o instanceof l||(this.remuxer=new l(i,t,s,this.logger)),a&&a instanceof h||(this.demuxer=new h(i,t,s,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new js(this.config)),e}}const to=e=>({remuxResult:{},chunkMeta:e});function io(e){return"then"in e&&e.then instanceof Function}class so{constructor(e,t,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class ro{constructor(e,t,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}let no=0;class ao{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=no++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,i=this.hls;if(i&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var s;const e=null==(s=this.workerContext)?void 0:s.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(gt.ERROR,{type:dt.OTHER_ERROR,details:ft.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===gt.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new Fn,this.observer.on(gt.FRAG_DECRYPTED,n),this.observer.on(gt.ERROR,n);const a=Vi(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(i.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=Un[e];if(t)return t.clientCount++,t;const i=new self.URL(e,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Un[e]=s,s}(r.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=Un[Nn];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return Un[Nn]=s,s}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:as(r)})}catch(s){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new eo(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new eo(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=no++;const t=this.hls.config,i=Vi(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:as(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=Un[e||Nn];if(t&&1==t.clientCount--){const{worker:i,objectURL:s}=t;delete Un[e||Nn],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,r,n,a,o,l,h){var u,c;l.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,g=n?n.start:r.start,p=r.decryptdata,m=this.frag,v=!(m&&r.cc===m.cc),y=!(m&&l.level===m.level),A=m?l.sn-m.sn:-1,E=this.part?l.part-this.part.index:-1,T=0===A&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!y&&(1===A||0===A&&(1===E||T&&E<=0)),b=self.performance.now();(y||A||0===r.stats.parsing.start)&&(r.stats.parsing.start=b),!n||!E&&S||(n.stats.parsing.start=b);const L=!(m&&(null==(u=r.initSegment)?void 0:u.url)===(null==(c=m.initSegment)?void 0:c.url)),_=new ro(v,S,o,y,g,L);if(!S||v||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===At?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${L}`);const e=new so(i,s,t,a,h);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:_},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,p,l,_);io(t)?t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const t=i.flush(e);io(t)?t.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")})):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class oo extends It{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=null==t?void 0:t.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=i;break}a===e.substring(0,a.length)&&(r=i)}if(-1!==r){const e=s[r],n=parseInt(e["LAST-MSN"])||(null==t?void 0:t.lastPartSn);let a=parseInt(e["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=i&&ts(i);return new is(n,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;s.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==s.appliedTimelineOffset){const e=Math.max(o||0,0);s.appliedTimelineOffset=e,s.fragments.forEach((t=>{t.start=t.playlistOffset+e}))}if(s.live||null!=i&&i.live){const o="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){sn(i,s);const e=s.playlistParsingError;if(e){this.warn(e);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void i.trigger(gt.ERROR,{type:dt.NETWORK_ERROR,details:ft.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=s.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,u=h?h.end-h.len:0,c=on(s,1e3*(s.edge-u));if(s.requestScheduled+c<n?s.requestScheduled=n:s.requestScheduled+=c,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let d,f,g;if(s.canBlockReload&&s.endSN&&s.advanced){const e=this.hls.config.lowLatencyMode,r=s.lastPartSn,a=s.endSN,l=s.lastPartIndex,h=r===a;-1!==l?h?(f=a+1,g=e?0:l):(f=r,g=e?l+1:s.maxPartIndex):f=a+1;const u=s.age,c=u+s.ageHeader;let p=Math.min(c-s.partTarget,1.5*s.targetduration);if(p>0){if(c>3*s.targetduration)this.log(`Playlist last advanced ${u.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=i&&i.tuneInGoal&&c-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${p} with playlist age: ${s.age}`),p=0;else{const e=Math.floor(p/s.targetduration);if(f+=e,void 0!==g){g+=Math.round(p%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${p} skip sn ${e} to part ${g}`)}s.tuneInGoal=p}if(d=this.getDeliveryDirectives(s,t.deliveryDirectives,f,g),e||!h)return s.requestScheduled=n,void this.loadingPlaylist(o,d)}else(s.canBlockReload||s.canSkipUntil)&&(d=this.getDeliveryDirectives(s,t.deliveryDirectives,f,g));d&&void 0!==f&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,d,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=s.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(e,t)),a)}getDeliveryDirectives(e,t,i,s){let r=ts(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=Zi),new is(i,s,r)}checkRetry(e){const t=e.details,i=Es(e),s=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===Is||!s.resolved&&r===ks);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Ss(a,n);this.clearTimer(),this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,s.resolved=!0}return o}}function lo(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!ho(e[i].attrs,t[i].attrs))return!1;return!0}function ho(e,t,i){const s=e["STABLE-RENDITION-ID"];return s&&!i?s===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((i=>e[i]!==t[i]))}function uo(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class co{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(null===this.queues||null===this.tracks)return;const s=this.queues[t];s.push(e),1!==s.length||i||this.executeNext(t)}appendBlocker(e){return new Promise((t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)}))}prependBlocker(e){return new Promise((t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((e=>{var t;const i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))}))}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(t){var i;if(s.onError(t),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[e])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=null==(t=this.tracks)?void 0:t[e],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map((e=>e.label)).join(", "))||""}}const fo=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,go="HlsJsTrackRemovedError";class po extends Error{constructor(e){super(e),this.name=go}}function mo(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}function vo(e){return"audio"===e?1:0}class yo{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(gt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.on(gt.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(gt.BUFFER_CODECS,this.onBufferCodecs,this),e.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(gt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.off(gt.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(gt.BUFFER_CODECS,this.onBufferCodecs,this),e.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&ht(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter(((t,i)=>this.isLevelAllowed(t)&&i<=e));return this.clientRect=null,yo.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;let s=e.length-1;const r=Math.max(t,i);for(let t=0;t<e.length;t+=1){const i=e[t];if((i.width>=r||i.height>=r)&&(n=i,!(a=e[t+1])||n.width!==a.width||n.height!==a.height)){s=t;break}}var n,a;return s}}const Ao={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Eo={HLS:"h"},To="CMCD-Object",So="CMCD-Request",bo="CMCD-Session",Lo="CMCD-Status",_o={[To]:["br","d","ot","tb"],[So]:["bl","dl","mtp","nor","nrr","su"],[bo]:["cid","pr","sf","sid","st","v"],[Lo]:["bs","rtp"]};class ko{constructor(e,t){Array.isArray(e)&&(e=e.map((e=>e instanceof ko?e:new ko(e)))),this.value=e,this.params=t}}function Ro(e,t,i,s){return new Error(`failed to ${e} "${r=t,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${i}`,{cause:s});var r}function Io(e,t,i){return Ro("serialize",e,t,i)}class Do{constructor(e){this.description=e}}const Po="Bare Item";function Co(e){if(!1===ArrayBuffer.isView(e))throw Io(e,"Byte Sequence");return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function wo(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Io(e,"Integer");return e.toString()}function Oo(e){const t=Zn(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Io(e,"Decimal");const i=t.toString();return i.includes(".")?i:`${i}.0`}const xo=/[\x00-\x1f\x7f]+/;function Mo(e){const t=(i=e).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Io(t,"Token");return t}function Fo(e){switch(typeof e){case"number":if(!ht(e))throw Io(e,Po);return Number.isInteger(e)?wo(e):Oo(e);case"string":return function(e){if(xo.test(e))throw Io(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Mo(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Io(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${wo(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return Co(e);if(e instanceof Do)return Mo(e);default:throw Io(e,Po)}}function No(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Io(e,"Key");return e}function Uo(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${No(e)}`:`;${No(e)}=${Fo(t)}`)).join("")}function Bo(e){return e instanceof ko?`${Fo(e.value)}${Uo(e.params)}`:Fo(e)}function $o(e,t={whitespace:!0}){if("object"!=typeof e)throw Io(e,"Dict");const i=e instanceof Map?e.entries():Object.entries(e),s=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map((([e,t])=>{t instanceof ko==!1&&(t=new ko(t));let i=No(e);var s;return!0===t.value?i+=Uo(t.params):(i+="=",Array.isArray(t.value)?i+=`(${(s=t).value.map(Bo).join(" ")})${Uo(s.params)}`:i+=Bo(t)),i})).join(`,${s}`)}const Go=e=>Math.round(e),Ko=e=>100*Go(e/100),Vo={br:Go,d:Go,bl:Ko,dl:Ko,mtp:Ko,nor:(e,t)=>((null==t?void 0:t.baseUrl)&&(e=function(e,t){const i=new URL(e),s=new URL(t);if(i.origin!==s.origin)return e;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}(e,t.baseUrl)),encodeURIComponent(e)),rtp:Ko,tb:Go};function Ho(e,t){const i={};if(null==e||"object"!=typeof e)return i;const s=Object.keys(e).sort(),r=_t({},Vo,null==t?void 0:t.formatters),n=null==t?void 0:t.filter;return s.forEach((s=>{if(null==n?void 0:n(s))return;let a=e[s];const o=r[s];o&&(a=o(a,t)),"v"===s&&1===a||"pr"==s&&1===a||function(e){return"number"==typeof e?ht(e):null!=e&&""!==e&&!1!==e}(a)&&(function(e){return"ot"===e||"sf"===e||"st"===e}(s)&&"string"==typeof a&&(a=new Do(a)),i[s]=a)})),i}function Yo(e,t={}){return e?function(e,t){return $o(e,t)}(Ho(e,t),_t({whitespace:!1},t)):""}function jo(e,t,i){return _t(e,function(e,t={}){const i={};if(!e)return i;const s=Object.entries(e),r=Object.entries(_o).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),n=s.reduce(((e,t)=>{var i,s;const[n,a]=t,o=(null===(i=r.find((e=>e[1].includes(n))))||void 0===i?void 0:i[0])||So;return null!==(s=e[o])&&void 0!==s||(e[o]={}),e[o][n]=a,e}),{});return Object.entries(n).reduce(((e,[i,s])=>(e[i]=Yo(s,t),e)),i)}(t,i))}const Wo=/CMCD=[^&#]+/;function qo(e,t,i){const s=function(e,t={}){if(!e)return"";const i=Yo(e,t);return`CMCD=${encodeURIComponent(i)}`}(t,i);if(!s)return e;if(Wo.test(e))return e.replace(Wo,s);const r=e.includes("?")?"&":"?";return`${e}${r}${s}`}function zo(e,t,i,s){e&&Object.keys(t).forEach((r=>{const n=e.filter((e=>e.groupId===r)).map((e=>{const n=_t({},e);return n.details=void 0,n.attrs=new hr(n.attrs),n.url=n.attrs.URI=Xo(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=s,n}));e.push(...n)}))}function Xo(e,t,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}class Qo extends It{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Qo.CDMCleanupPromise?[Qo.CDMCleanupPromise]:[],this.onMediaEncrypted=e=>{const{initDataType:t,initData:i}=e,s=`"${e.type}" event: init data type: "${t}"`;if(this.debug(s),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Cr(this.config));const t=e.map(Pr).filter((e=>!!e));this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then((r=>{const n=Lr(r);let a,o;if("sinf"===t){if(n!==Ar.FAIRPLAY)return void this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);const r=ai(new Uint8Array(i));try{const e=Ei(pr(JSON.parse(r).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(e.subarray(8,24)),o=Ar.FAIRPLAY}catch(e){return void this.warn(`${s} Failed to parse sinf: ${e}`)}}else{if(n!==Ar.WIDEVINE&&n!==Ar.PLAYREADY)return void this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);const r=function(e){const t=[];if(e instanceof ArrayBuffer){const i=e.byteLength;let s=0;for(;s+32<i;){const i=Di(new DataView(e,s));t.push(i),s+=i.size}}return t}(i),l=r.filter((e=>!!e.systemId&&Dr(e.systemId)===n));l.length>1&&this.warn(`${s} Using first of ${l.length} pssh found for selected key-system ${n}`);const h=l[0];if(!h)return void(0===r.length||r.some((e=>!e.systemId))?this.warn(`${s} contains incomplete or invalid pssh data`):this.log(`ignoring ${s} for ${r.map((e=>Dr(e.systemId))).join(",")} pssh data in favor of playlist keys`));if(o=Dr(h.systemId),0===h.version&&h.data)if(o===Ar.WIDEVINE){const e=h.data.length-22;a=new Uint8Array(h.data.subarray(e,e+16))}else o===Ar.PLAYREADY&&(a=xr(h.data))}if(!o||!a)return;const l=Ut(a),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let c=h[l];for(let e=0;e<u.length;e++){const s=u[e],r=s.decryptdata;if(!r.keyId)continue;const n=Ut(r.keyId);if(l===n||-1!==r.uri.replace(/-/g,"").indexOf(l)){if(c=h[n],r.pssh)break;delete h[n],r.pssh=new Uint8Array(i),r.keyId=a,c=h[l]=c.then((()=>this.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-key-match"))),c.catch((e=>this.handleError(e)));break}}if(!c){if(o!==n)return void this.log(`Ignoring "${e.type}" event with ${o} init data for selected key-system ${n}`);c=h[l]=this.getKeySystemSelectionPromise([o]).then((({keySystem:e,mediaKeys:s})=>{var r;this.throwIfDestroyed();const n=new Fr("ISO-23001-7",l,null!=(r=Pr(e))?r:"");return n.pssh=new Uint8Array(i),n.keyId=a,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:n,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(r,t,i,"encrypted-event-no-match")}))})),c.catch((e=>this.handleError(e)))}}))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){const e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);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(gt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(gt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(gt.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(gt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(gt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(gt.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t[e];return s?s.licenseUrl:e===Ar.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,s=t.map((e=>e.audioCodec)).filter(i),r=t.map((e=>e.videoCodec)).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise(((t,i)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,s,r).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?n(e):i(t instanceof Zo?t:new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};n(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===wr&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){const s=function(e,t,i,s){let r;switch(e){case Ar.FAIRPLAY:r=["cenc","sinf"];break;case Ar.WIDEVINE:case Ar.PLAYREADY:r=["cenc"];break;case Ar.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,s){return[{initDataTypes:e,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs=${e}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null}))),videoCapabilities:i.map((e=>({contentType:`video/mp4; codecs=${e}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null})))}]}(r,t,i,s)}(e,t,i,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let n=null==r?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${as(s)}`),n=this.requestMediaKeySystemAccess(e,s);const t=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),n.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=i.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),s.then((i=>i?this.setMediaKeysServerCertificate(t,e,i):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return n.then((()=>r.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Ut(e.keyId||[])}`);const s=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Ut(e.keyId)}updateKeySession(e,t){var i;const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${Ut((null==(i=e.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),s.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,i)=>{const s=Cr(this.config),r=e.map(Lr).filter((e=>!!e&&-1!==s.indexOf(e)));return this.getKeySystemSelectionPromise(r).then((({keySystem:e})=>{const s=Pr(e);s?t(s):i(new Error(`Unable to find format for key-system "${e}"`))})).catch(i)}))}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),s=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);let r=this.keyIdToKeySessionPromise[i];if(!r){r=this.getKeySystemForKeyPromise(t).then((({keySystem:i,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(i,r).then((()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:r,decryptdata:t})))))));(this.keyIdToKeySessionPromise[i]=r.then((e=>{const i=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")}))).catch((e=>this.handleError(e)))}return r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Zo?this.hls.trigger(gt.ERROR,e.data):this.hls.trigger(gt.ERROR,{type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const t=Lr(e.keyFormat),i=t?[t]:Cr(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Cr(this.config)),0===e.length)throw new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${as({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=Promise.all(i).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(s),s.then((()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===i.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,i,s){var r,n;const a=null==(r=this.config.drmSystems)||null==(n=r[e.keySystem])?void 0:n.generateRequest;if(a)try{const s=a.call(this.hls,t,i,e);if(!s)throw new Error("Invalid response from configured generateRequest filter");t=s.initDataType,i=s.initData?s.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${l} (init data type: ${t} length: ${i?i.byteLength:null})`);const h=new Fn,u=e._onmessage=t=>{const i=e.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));const{messageType:s,message:r}=t;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(e,r).catch((e=>{h.eventNames().length?h.emit("error",e):this.handleError(e)})):"license-release"===s?e.keySystem===Ar.FAIRPLAY&&(this.updateKeySession(e,mr("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${s}"`)},c=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const i=e.keyStatus;h.emit("keyStatus",i),"expired"===i&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",u),e.mediaKeysSession.addEventListener("keystatuseschange",c);const d=new Promise(((e,t)=>{h.on("error",t),h.on("keyStatus",(i=>{i.startsWith("usable")?e():"output-restricted"===i?t(new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return e.mediaKeysSession.generateRequest(t,i).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>d)).catch((t=>{throw h.removeAllListeners(),this.removeSession(e),t})).then((()=>(h.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,i)=>{if("string"==typeof i&&"object"==typeof t){const e=i;i=t,t=e}this.log(`key status change "${t}" for keyStatuses keyId: ${Ut("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Ut(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,i=new(0,t.loader)(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise(((r,n)=>{const a={responseType:"arraybuffer",url:s},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,s)=>{r(e.data)},onError:(t,i,r,o)=>{n(new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:Rt({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${s}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,r)=>{n(new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(e,t,i)=>{n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise(((s,r)=>{e.setServerCertificate(i).then((r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${t}"`),s(e)})).catch((e=>{r(new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const s=(new DOMParser).parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let t;for(let i=0,s=r.length;i<s;i++){var n,a;t=r[i];const s=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;s&&o&&e.setRequestHeader(s,o)}}const o=s.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return mr(atob(l))}setupLicenseXHR(e,t,i,s){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,s)})).catch((n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,i,s)})).then((i=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:i||s}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise(((s,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,a,n,e)}catch(e){this.error(e)}s(t)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new Zo({type:dt.KEY_SYSTEM_ERROR,details:ft.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(s,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then((({xhr:t,licenseChallenge:i})=>{e.keySystem==Ar.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(e){var t;const i=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Fr.clearKeyUriToKeyIdMap();const s=i.length;Qo.CDMCleanupPromise=Promise.all(i.map((e=>this.removeSession(e))).concat(null==e||null==(t=e.setMediaKeys(null))?void 0:t.catch((e=>{var t;this.log(`Could not clear media keys: ${e}`),null==(t=this.hls)||t.trigger(gt.ERROR,{type:dt.OTHER_ERROR,details:ft.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})})))).then((()=>{s&&(this.log("finished closing key sessions and clearing media keys"),i.length=0)})).catch((e=>{var t;this.log(`Could not close sessions and clear media keys: ${e}`),null==(t=this.hls)||t.trigger(gt.ERROR,{type:dt.OTHER_ERROR,details:ft.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);const{drmSystemOptions:r}=this.config,n=function(e){var t;return"persistent-license"===e.sessionType||!(null==(t=e.sessionTypes)||!t.some((e=>"persistent-license"===e)))}(r)?new Promise(((e,i)=>{self.setTimeout((()=>i(new Error("MediaKeySession.remove() timeout"))),8e3),t.remove().then(e)})):Promise.resolve();return n.catch((e=>{var t;this.log(`Could not remove session: ${e}`),null==(t=this.hls)||t.trigger(gt.ERROR,{type:dt.OTHER_ERROR,details:ft.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})})).then((()=>t.close())).catch((e=>{var t;this.log(`Could not close session: ${e}`),null==(t=this.hls)||t.trigger(gt.ERROR,{type:dt.OTHER_ERROR,details:ft.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})}))}}}Qo.CDMCleanupPromise=void 0;class Zo extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Jo(e,t){let i;try{i=new Event("addtrack")}catch(e){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function el(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){xt.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){xt.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function tl(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===i&&(e.mode=i)}function il(e,t,i,s){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,i){const s=[],r=function(e,t){if(t<=e[0].startTime)return 0;const i=e.length-1;if(t>e[i].endTime)return-1;let s,r=0,n=i;for(;r<=n;)if(s=Math.floor((n+r)/2),t<e[s].startTime)n=s-1;else{if(!(t>e[s].startTime&&r<i))return s;r=s+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(e.cues,t,i);for(let t=0;t<r.length;t++)s&&!s(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function sl(e){const t=[];for(let i=0;i<e.length;i++){const s=e[i];"subtitles"!==s.kind&&"captions"!==s.kind||!s.label||t.push(e[i])}return t}function rl(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}const nl=.025;let al=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function ol(e,t,i){return`${e.identifier}-${i+1}-${rl(t)}`}class ll{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>=this.assetList.length)return!0;const t=this.playoutLimit;if(e<=0||isNaN(t))return!1;return this.assetList[e].startOffset>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return hl(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-hl(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=ht(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return hl(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<nl))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?al.Range:al.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function hl(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<nl)?t.start:t.start+t.duration}function ul(e,t,i){const s=new self.URL(e,i);return"data:"!==s.protocol&&s.searchParams.set("_HLS_primary_id",t),s}function cl(e){const t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}class dl{constructor(e,t,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{const e=this.interstitial.playoutLimit,t=this.currentTime;this.startOffset+t>=e&&this.hls.trigger(gt.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=s;let n=s.uri;try{n=ul(n,r.sessionId).href}catch(e){}r.loadSource(n);const a=()=>{this.hasDetails=!0};r.once(gt.LEVEL_LOADED,a),r.once(gt.AUDIO_TRACK_LOADED,a),r.once(gt.SUBTITLE_TRACK_LOADED,a),r.on(gt.MEDIA_ATTACHING,((e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&t.addEventListener("timeupdate",this.checkPlayout)}))}bufferedInPlaceToEnd(e){var t;if(!this.interstitial.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;const i=this.timelineOffset,s=tr.bufferInfo(e,i,0);return this.getAssetTime(s.end)>=this._bufferedEosTime-.02}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=tr.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;return e||0}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){this.hls.attachMedia(e)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(e,t,i){this.hls.on(e,t)}once(e,t,i){this.hls.once(e,t)}off(e,t,i){this.hls.off(e,t)}toString(){var e,t;return`HlsAssetPlayer: ${cl(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${null!=(t=this.interstitial)&&t.appendInPlace?"append-in-place":""}`}}class fl extends It{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((e=>e.reset())),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce(((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i),0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(t&&"primary"!==t&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return s}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){const e=i[s].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return s}return-1}findEventIndex(e){const t=this.items;if(t)for(let s=t.length;s--;){var i;if((null==(i=t[s].event)?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){const i=e.assetList,s=i.length;if(s>1)for(let e=0;e<s;e++){const s=i[e];if(!s.error){const i=s.timelineStart;if(t===i||t>i&&t<i+(s.duration||0))return e}}return 0}get assetIdAtEnd(){var e,t;const i=null==(e=this.items)||null==(t=e[this.length-1])?void 0:t.event;if(i){const e=i.assetList,t=e[e.length-1];if(t)return t.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:s}=i,r=this.events,n=this.parseDateRanges(s,{url:i.url},t),a=Object.keys(s),o=r?r.filter((e=>!a.includes(e.identifier))):[];n.length&&n.sort(((e,t)=>{const i=e.cue.pre,s=e.cue.post,r=t.cue.pre,n=t.cue.post;if(i&&!r)return-1;if(r&&!i)return 1;if(s&&!n)return 1;if(n&&!s)return-1;if(!(i||r||s||n)){const i=e.startTime,s=t.startTime;if(i!==s)return i-s}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=n,o.forEach((e=>{this.removeEvent(e)})),this.updateSchedule(e,o)}updateSchedule(e,t=[]){const i=this.events||[];if(i.length||t.length||this.length<2){const s=this.items,r=this.parseSchedule(i,e);(t.length||(null==s?void 0:s.length)!==r.length||r.some(((e,t)=>Math.abs(e.playout.start-s[t].playout.start)>.005||Math.abs(e.playout.end-s[t].playout.end)>.005)))&&(this.items=r,this.onScheduleUpdate(t,s))}}parseDateRanges(e,t,i){const s=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new ll(o,t),this.eventMap[a]=e,!1===i&&(e.appendInPlace=i)),s.push(e)}}return s}parseSchedule(e,t){const i=[],s=t.main.details,r=s.live?1/0:s.edge;let n=0;if((e=e.filter((e=>!(e.error||e.cue.once&&e.hasPlayed)))).length){this.resolveOffsets(e,t);let s=0,o=0;if(e.forEach(((t,a)=>{const l=t.cue.pre,h=t.cue.post,u=e[a-1]||null,c=t.appendInPlace,d=h?r:t.startOffset,f=t.duration,g=t.timelineOccupancy===al.Range?f:0,p=t.resumptionOffset,m=(null==u?void 0:u.startTime)===d,v=d+t.cumulativeDuration;let y=c?v+f:d+p;if(l||!h&&d<=0){const e=o;o+=g,t.timelineStart=v;const s=n;n+=f,i.push({event:t,start:v,end:y,playout:{start:s,end:n},integrated:{start:e,end:o}})}else{if(!(d<=r))return;{if(!m){const r=d-s;if(r>.033){const l=s,h=o;o+=r;const u=n;n+=r;const c={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+r,playout:{start:u,end:n},integrated:{start:h,end:o}};i.push(c)}else r>0&&u&&(u.cumulativeDuration+=r,i[i.length-1].end=d)}h&&(y=v),t.timelineStart=v;const r=o;o+=g;const l=n;n+=f,i.push({event:t,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const A=t.resumeTime;s=h||A>r?r:A})),s<r){var a;const e=s,t=o,l=r-s;o+=l;const h=n;n+=l,i.push({previousEvent:(null==(a=i[i.length-1])?void 0:a.event)||null,nextEvent:null,start:s,end:e+l,playout:{start:h,end:n},integrated:{start:t,end:o}})}this.setDurations(r,n,o)}else{const e=0;i.push({previousEvent:null,nextEvent:null,start:e,end:r,playout:{start:e,end:r},integrated:{start:e,end:r}}),this.setDurations(r,r,r)}return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,s=i.live?1/0:i.edge;let r=0,n=-1;e.forEach(((a,o)=>{const l=a.cue.pre,h=a.cue.post,u=l?0:h?s:a.startTime;this.updateAssetDurations(a);if(n===u?a.cumulativeDuration=r:(r=0,n=u),!h&&a.snapOptions.in&&(a.resumeAnchor=ms(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const c=ht(a.resumeOffset)?a.resumeOffset:a.duration;r+=c}))}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,s=e.startTime+e.resumptionOffset;if(Math.abs(i-s)>nl)return this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1;if(!t)return this.log(`"${e.identifier}" resumption ${i} can not be aligned with media (none selected)`),!1;return!Object.keys(t).some((s=>{const r=t[s].details,n=r.edge;if(i>=n)return this.log(`"${e.identifier}" resumption ${i} past ${s} playlist end ${n}`),!1;const a=ms(null,r.fragments,i);if(!a)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===s?.175:0;return!(Math.abs(a.start-i)<nl+o||Math.abs(a.end-i)<nl+o)&&(this.log(`"${e.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)}))}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,s=!1,r=!1;e.assetList.forEach(((e,n)=>{const a=t+i;e.startOffset=i,e.timelineStart=a,s||(s=null===e.duration),r||(r=!!e.error);const o=e.error?0:e.duration||0;i+=o})),e.duration=s&&!r?Math.max(i,e.duration):i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function gl(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class pl{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=ul(i,this.hls.sessionId,e.baseUrl)}catch(t){const s=this.assignAssetListError(e,ft.ASSET_LIST_LOAD_ERROR,t,i);return void this.hls.trigger(gt.ERROR,s)}t&&"data:"!==s.protocol&&s.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:s.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,i,s,r)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(Array.isArray(a))e.assetListResponse=n,this.hls.trigger(gt.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:r});else{const t=this.assignAssetListError(e,ft.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,r);this.hls.trigger(gt.ERROR,t)}},onError:(t,i,s,r)=>{const n=this.assignAssetListError(e,ft.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,r,s);this.hls.trigger(gt.ERROR,n)},onTimeout:(t,i,s)=>{const r=this.assignAssetListError(e,ft.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,s);this.hls.trigger(gt.ERROR,r)}};return n.load(a,l,h),this.hls.trigger(gt.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,i,s,r,n){return e.error=i,{type:dt.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:n,stats:r}}}function ml(e,t,i){vl(e,t,i),e.addEventListener(t,i)}function vl(e,t,i){e.removeEventListener(t,i)}function yl(e){null==e||e.play().catch((()=>{}))}class Al{constructor(e){this.buffered=void 0;const t=(t,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}const El={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},Tl=e=>String.fromCharCode(El[e]||e),Sl=15,bl=100,Ll={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},_l={17:2,18:4,21:6,22:8,23:10,19:13,20:15},kl={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Rl={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Il=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Dl{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i="function"==typeof t?t():t;xt.log(`${this.time} [${e}] ${i}`)}}}const Pl=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class Cl{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class wl{constructor(){this.uchar=" ",this.penState=new Cl}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Ol{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Cl,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<bl;e++)this.chars.push(new wl);this.logger=e}equals(e){for(let t=0;t<bl;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<bl;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<bl;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>bl&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=bl)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Tl(e);this.pos>=bl?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<bl;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<bl;i++){const s=this.chars[i].uchar;" "!==s&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class xl{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Sl;t++)this.rows.push(new Ol(e));this.logger=e}reset(){for(let e=0;e<Sl;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<Sl;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<Sl;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Sl;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+as(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<Sl;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[e].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[t-this.nrRollUpRows+s+1].copy(i.rows[e+s])}}this.currRow=t;const i=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,s=Math.max(t-1,0);i.setCursor(e.indent),e.color=i.chars[s].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+as(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",s=-1;for(let i=0;i<Sl;i++){const r=this.rows[i].getTextString();r&&(s=i+1,e?t.push("Row "+s+": '"+r+"'"):t.push(r.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class Ml{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new xl(i),this.nonDisplayedMemory=new xl(i),this.lastOutputScreen=new xl(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+as(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Fl{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new Dl;this.channels=[null,new Ml(e,t,s),new Ml(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const i=127&t[e],s=127&t[e+1];let r=!1,n=null;if(0===i&&0===s)continue;this.logger.log(3,(()=>"["+Pl([t[e],t[e+1]])+"] -> ("+Pl([i,s])+")"));const a=this.cmdHistory;if(i>=16&&i<=31){if(Ul(i,s,a)){Nl(null,null,a),this.logger.log(3,(()=>"Repeated command ("+Pl([i,s])+") is dropped"));continue}Nl(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 Nl(null,null,a);if(!r&&(n=this.parseChars(i,s),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+Pl([i,s])+" orig: "+Pl([t[e],t[e+1]])))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const i=20===e||21===e||23===e?1:2,s=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return!!s&&(s.ccMIDROW(t),this.logger.log(3,(()=>"MIDROW ("+Pl([e,t])+")")),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const s=e<=23?1:2;i=t>=64&&t<=95?1===s?Ll[e]:kl[e]:1===s?_l[e]:Rl[e];const r=this.channels[s];return!!r&&(r.setPAC(this.interpretPAC(i,t)),this.currentChannel=s,!0)}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,s.underline=!(1&~i),i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=4*Math.floor((i-16)/2),s}parseChars(e,t){let i,s=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let e;e=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,(()=>"Special char '"+Tl(e)+"' in channel "+i)),s=[e]}else e>=32&&e<=127&&(s=0===t?[e]:[e,t]);return s&&this.logger.log(3,(()=>"Char codes = "+Pl(s).join(","))),s}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let i;const s={};16===e||24===e?(i=Math.floor((t-32)/2),s.background=Il[i],t%2==1&&(s.background=s.background+"_semi")):45===t?s.background="transparent":(s.foreground="black",47===t&&(s.underline=!0));const r=e<=23?1:2;return this.channels[r].setBkgData(s),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Nl(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function Nl(e,t,i){i.a=e,i.b=t}function Ul(e,t,i){return i.a===e&&i.b===t}var Bl=function(){if(null!=yr&&yr.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const i=t.toLowerCase();return!!~e.indexOf(i)&&i}function s(e){return i(t,e)}function r(e,...t){let i=1;for(;i<arguments.length;i++){const t=arguments[i];for(const i in t)e[i]=t[i]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",u=!1,c=t,d=n,f=a,g=null,p="",m=!0,v="auto",y="start",A=50,E="middle",T=50,S="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return u},set:function(e){u=!!e}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return p},set:function(t){const s=function(t){return i(e,t)}(t);if(!1===s)throw new SyntaxError("An invalid or illegal string was specified.");p=s,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return A},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");A=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return E},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return S},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class $l{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Gl(e){function t(e,t,i,s){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(s||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class Kl{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function Vl(e,t,i,s){const r=s?e.split(s):[e];for(const e in r){if("string"!=typeof r[e])continue;const s=r[e].split(i);if(2!==s.length)continue;t(s[0],s[1])}}const Hl=new Bl(0,0,""),Yl="middle"===Hl.align?"middle":"center";function jl(e,t,i){const s=e;function r(){const t=Gl(e);if(null===t)throw new Error("Malformed timestamp: "+s);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=r(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);e=e.slice(3),n(),t.endTime=r(),n(),function(e,t){const s=new Kl;Vl(e,(function(e,t){let r;switch(e){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===t){s.set(e,i[r].region);break}break;case"vertical":s.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),s.integer(e,r[0]),s.percent(e,r[0])&&s.set("snapToLines",!1),s.alt(e,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",Yl,"end"]);break;case"position":r=t.split(","),s.percent(e,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",Yl,"end","line-left","line-right","auto"]);break;case"size":s.percent(e,t);break;case"align":s.alt(e,t,["start",Yl,"end","left","right"])}}),/:/,/\s/),t.region=s.get("region",null),t.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===Hl.line&&(r=-1),t.line=r,t.lineAlign=s.get("lineAlign","start"),t.snapToLines=s.get("snapToLines",!0),t.size=s.get("size",100),t.align=s.get("align",Yl);let n=s.get("position","auto");"auto"===n&&50===Hl.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function Wl(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class ql{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new $l,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function i(){let e=t.buffer,i=0;for(e=Wl(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;const s=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),s}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=i();const s=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let s=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:e=i(),t.state){case"HEADER":/:/.test(e)?Vl(e,(function(e,t){}),/:/):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new Bl(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{jl(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==e.indexOf("--\x3e");if(!e||i&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const zl=/\r\n|\n\r|\n|\r/g,Xl=function(e,t,i=0){return e.slice(i,i+t.length)===t};function Ql(e,t,i){return rl(e.toString())+rl(t.toString())+rl(i)}function Zl(e,t,i,s,r,n,a){const o=new ql,l=Nt(new Uint8Array(e)).trim().replace(zl,"\n").split("\n"),h=[],u=t?function(e,t=1){return Ka(e,9e4,1/t)}(t.baseTime,t.timescale):0;let c,d="00:00.000",f=0,g=0,p=!0;o.oncue=function(e){const n=i[s];let a=i.ccOffset;const o=(f-u)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(e,t,i){let s=e[t],r=e[s.prevCC];if(!r||!r.new&&s.new)return e.ccOffset=e.presentationOffset=s.start,void(s.new=!1);for(;null!=(n=r)&&n.new;){var n;e.ccOffset+=s.start-r.start,s.new=!1,s=r,r=e[s.prevCC]}e.presentationOffset=i}(i,s,o)),o){if(!t)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=e.endTime-e.startTime,d=za(9e4*(e.startTime+a-g),9e4*r)/9e4;e.startTime=Math.max(d,0),e.endTime=Math.max(d+l,0);const p=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(p)),e.id||(e.id=Ql(e.startTime,e.endTime,p)),e.endTime>0&&h.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(h)},l.forEach((e=>{if(p){if(Xl(e,"X-TIMESTAMP-MAP=")){p=!1,e.slice(16).split(",").forEach((e=>{Xl(e,"LOCAL:")?d=e.slice(6):Xl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{g=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(ht(t)&&ht(i)&&ht(s)&&ht(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*s,t+=36e5*r,t}(d)/1e3}catch(e){c=e}return}""===e&&(p=!1)}o.parse(e+"\n")})),o.flush()}const Jl="stpp.ttml.im1t",eh=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,th=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ih={left:"start",center:"center",right:"end",start:"start",end:"end"};function sh(e,t,i,s){const r=di(new Uint8Array(e),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map((e=>Nt(e))),a=function(e,t,i=1,s=!1){return Ka(e,t,1/i,s)}(t.baseTime,1,t.timescale);try{n.forEach((e=>i(function(e,t){const i=(new DOMParser).parseFromString(e,"text/xml"),s=i.getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce(((e,t)=>(e[t]=s.getAttribute(`ttp:${t}`)||r[t],e)),{}),a="preserve"!==s.getAttribute("xml:space"),o=nh(rh(s,"styling","style")),l=nh(rh(s,"layout","region")),h=rh(s,"body","[begin]");return[].map.call(h,(e=>{const i=ah(e,a);if(!i||!e.hasAttribute("begin"))return null;const s=hh(e.getAttribute("begin"),n),r=hh(e.getAttribute("dur"),n);let h=hh(e.getAttribute("end"),n);if(null===s)throw lh(e);if(null===h){if(null===r)throw lh(e);h=s+r}const u=new Bl(s-t,h-t,i);u.id=Ql(u.startTime,u.endTime,u.text);const c=function(e,t,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce(((i,n)=>{const a=oh(t,s,n)||oh(e,s,n)||oh(r,s,n);return a&&(i[n]=a),i}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:d}=c;if(d){const e=ih[d];e&&(u.lineAlign=e),u.align=d}return _t(u,c),u})).filter((e=>null!==e))}(e,a))))}catch(e){s(e)}}function rh(e,t,i){const s=e.getElementsByTagName(t)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function nh(e){return e.reduce(((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function ah(e,t){return[].slice.call(e.childNodes).reduce(((e,i,s)=>{var r;return"br"===i.nodeName&&s?e+"\n":null!=(r=i.childNodes)&&r.length?ah(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function oh(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function lh(e){return new Error(`Could not parse ttml timestamp ${e}`)}function hh(e,t){if(!e)return null;let i=Gl(e);return null===i&&(eh.test(e)?i=function(e,t){const i=eh.exec(e),s=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/t.frameRate}(e,t):th.test(e)&&(i=function(e,t){const i=th.exec(e),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return 1e3*s;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}(e,t))),i}class uh{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function ch(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function dh(e,t){return!!e&&e.kind===ch(t)&&uo(t,e)}const fh=/\s/,gh={newCue(e,t,i,s){const r=[];let n,a,o,l,h;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(n=s.rows[d],o=!0,l=0,h="",!n.isEmpty()){var c;for(let e=0;e<n.chars.length;e++)fh.test(n.chars[e].uchar)&&o?l++:(h+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;const s=Wl(h.trim()),f=Ql(t,i,s);null!=e&&null!=(c=e.cues)&&c.getCueById(f)||(a=new u(t,i,s),a.id=f,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return e&&r.length&&(r.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),r.forEach((t=>el(e,t)))),r}};const ph=/(\d+)-(\d+)\/(\d+)/;class mh{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||vh,this.controller=new self.AbortController,this.stats=new qt}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(_t({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&ht(o)?o:l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))}),t.timeout);(io(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((i=>{var r;this.response=this.loader=i;const a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))}),l-(a-s.loading.start)),!i.ok){const{status:e,statusText:t}=i;throw new yh(t||"fetch, bad network response",e,i)}s.loading.first=a,s.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=ph.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(ht(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(i.headers)||s.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&ht(t.highWaterMark)?this.loadProgressively(i,s,e,t.highWaterMark,o):n?i.arrayBuffer():"json"===e.responseType?i.json():i.text()})).then((i=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[a];l&&(s.loaded=s.total=l);const h={url:o.url,data:i,code:o.status},u=null==(r=this.callbacks)?void 0:r.onProgress;u&&!ht(t.highWaterMark)&&u(s,e,i,o),null==(n=this.callbacks)||n.onSuccess(h,s,e,o)})).catch((t=>{var i;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=t&&t.code||0,n=t?t.message:null;null==(i=this.callbacks)||i.onError({code:r,text:n},e,t?t.details:null,s)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,r){const n=new wn,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&r(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h<s||n.dataLength?(n.push(l),n.dataLength>=s&&r(t,i,n.flush().buffer,e)):r(t,i,l.buffer,e),o()})).catch((()=>Promise.reject()));return o()}}function vh(e,t){return new self.Request(e.url,t)}class yh extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Ah=/^age:\s*[\d.]+\s*$/im;class Eh{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new qt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return r(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),r(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:e.message},t,i,s)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(const t in s)e.setRequestHeader(t,s[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&ht(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,r=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const s=t.status,l="text"===t.responseType?t.responseText:null;if(s>=200&&s<300){const r=null!=l?l:t.response;if(null!=r){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,e,r,t);const h={url:t.responseURL,data:r,code:s};return void(null==(a=this.callbacks)||a.onSuccess(h,i,e,t))}}const h=r.loadPolicy.errorRetry;var o;if(Ls(h,i.retry,!1,{url:e.url,data:void 0,code:s}))this.retry(h);else xt.error(`${s} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:s,text:t.statusText},e,t,i)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Ls(e,this.stats.retry,!0))this.retry(e);else{var t;xt.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Ss(e,i.retry),i.retry++,xt.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Ah.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Th=Rt(Rt({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,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,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:Eh,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends It{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:i,partCurrent:s,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!i||!a)return;const o=performance.now(),l=s?s.stats:i.stats,h=s?s.duration:i.duration,u=o-l.loading.start,c=r.minAutoLevel,d=i.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||d<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==d,p=!!e||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const m=r.mainForwardBufferInfo;if(!p&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(u<=Math.max(v,h/(2*y)*1e3))return;const A=m?m.len/y:0,E=l.loading.first?l.loading.first-l.loading.start:-1,T=l.loaded&&E>-1,S=this.getBwEstimate(),b=r.levels,L=b[d],_=Math.max(l.loaded,Math.round(h*(i.bitrate||L.averageBitrate)/8));let k=T?u-E:u;k<1&&T&&(k=Math.min(u,8*l.loaded/S));const R=T?1e3*l.loaded/k:0,I=v/1e3,D=R?(_-l.loaded)/R:8*_/S+I;if(D<=A)return;const P=R?8*R:S,C=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),w=this.hls.config.abrBandWidthUpFactor;let O,x=Number.POSITIVE_INFINITY;for(O=d-1;O>c;O--){const e=b[O].maxBitrate,t=!b[O].details||C;if(x=this.getTimeToLoadFrag(I,P,h*e,t),x<Math.min(A,h+I))break}if(x>=D)return;if(x>10*h)return;T?this.bwEstimator.sample(u-Math.min(v,E),l.loaded):this.bwEstimator.sampleTTFB(u);const M=b[O].maxBitrate;this.getBwEstimate()*w>M&&this.resetEstimator(M);const F=this.findBestLevel(M,c,O,0,A,1,1);F>-1&&(O=F),this.warn(`Fragment ${i.sn}${s?" part "+s.index:""} of level ${d} is loading too slowly;\n Fragment duration: ${i.duration.toFixed(3)}\n Time to underbuffer: ${A.toFixed(3)} s\n Estimated load time for current fragment: ${D.toFixed(3)} s\n Estimated load time for down switch fragment: ${x.toFixed(3)} s\n TTFB estimate: ${0|E} ms\n Current BW estimate: ${ht(S)?0|S:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|M} bps`),r.nextLoadLevel=r.nextAutoLevel=O,this.clearTimer();const N=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${i.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,O>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,O,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||D>2*x?N():this.timer=self.setInterval(N,1e3*x),r.trigger(gt.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:s,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new bt(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.FRAG_LOADING,this.onFragLoading,this),e.on(gt.FRAG_LOADED,this.onFragLoaded,this),e.on(gt.FRAG_BUFFERED,this.onFragBuffered,this),e.on(gt.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.on(gt.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(gt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(gt.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.FRAG_LOADING,this.onFragLoading,this),e.off(gt.FRAG_LOADED,this.onFragLoaded,this),e.off(gt.FRAG_BUFFERED,this.onFragBuffered,this),e.off(gt.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.off(gt.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(gt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(gt.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=t.part)?s:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ft.BUFFER_ADD_CODEC_ERROR:case ft.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ft.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:i,partCurrent:s}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){const t=performance.now(),i=s?s.stats:e.stats,r=t-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,i,s){return e+i/t+(s?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,r=s.end-s.first;ht(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===At&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=i?i.duration:t.duration,r=this.hls.levels[t.level],n=(r.loaded?r.loaded.bytes:0)+s.loaded,a=(r.loaded?r.loaded.duration:0)+e;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(gt.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,r=null!=s&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==At||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const s=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,s)&&t[e].loadError<=t[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,s,l,0,h,u);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=u=1}}const d=this.findBestLevel(o,n,s,l,c,h,u);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,r,n,a){var o;const l=s+r,h=this.lastLoadedFragLevel,u=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:d}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(1===f.length)return 0;const v=f[u],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),A=-1===p||-1===h;let E,T="SDR",S=(null==v?void 0:v.frameRate)||0;const{audioPreference:b,videoPreference:L}=m,_=this.audioTracksByGroup||(this.audioTracksByGroup=ls(g));let k=-1;if(A){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(e,t,i,s){return e.slice(i,s+1).reduce(((e,i,s)=>{if(!i.codecSet)return e;const r=i.audioGroups;let n=e[i.codecSet];n||(e[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,s),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,r&&r.forEach((e=>{if(!e)return;const i=t.groups[e];i&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((e=>{n.channels[e]=(n.channels[e]||0)+i.channels[e]})))})),e}),{})}(f,_,t,i)),r=function(e,t,i,s,r){const n=Object.keys(e),a=null==s?void 0:s.channels,o=null==s?void 0:s.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let u=!1,c=!1,d=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:A}=ns(t,r);for(let t=n.length;t--;){const i=e[n[t]];u||(u=i.channels[2]>0),d=Math.min(d,i.minHeight),f=Math.min(f,i.minFramerate),g=Math.min(g,i.minBitrate),A.filter((e=>i.videoRanges[e]>0)).length>0&&(c=!0)}d=ht(d)?d:0,f=ht(f)?f:0;const E=Math.max(1080,d),T=Math.max(30,f);g=ht(g)?g:i,i=Math.max(g,i),c||(t=void 0);const S=n.length>1;return{codecSet:n.reduce(((t,s)=>{const r=e[s];if(s===t)return t;if(v=c?A.filter((e=>r.videoRanges[e]>0)):[],S){if(r.minBitrate>i)return os(s,`min bitrate of ${r.minBitrate} > current estimate of ${i}`),t;if(!r.hasDefaultAudio)return os(s,"no renditions with default or auto-select sound found"),t;if(o&&s.indexOf(o.substring(0,4))%5!=0)return os(s,`audio codec preference "${o}" not found`),t;if(a&&!h){if(!r.channels[a])return os(s,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||h)&&u&&0===r.channels[2])return os(s,"no renditions with stereo sound found"),t;if(r.minHeight>E)return os(s,`min resolution of ${r.minHeight} > maximum of ${E}`),t;if(r.minFramerate>T)return os(s,`min framerate of ${r.minFramerate} > maximum of ${T}`),t;if(!v.some((e=>r.videoRanges[e]>0)))return os(s,`no variants with VIDEO-RANGE of ${as(v)} found`),t;if(l&&s.indexOf(l.substring(0,4))%5!=0)return os(s,`video codec preference "${l}" not found`),t;if(r.maxScore<m)return os(s,`max score of ${r.maxScore} < selected max of ${m}`),t}return t&&(Ni(s)>=Ni(t)||r.fragmentError>e[t].fragmentError)?t:(p=r.minIndex,m=r.maxScore,s)}),void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}(s,T,e,b,L),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:u}=r;k=h,E=n,T=u?a[a.length-1]:a[0],S=o,e=Math.max(e,l),this.log(`picked start tier ${as(r)}`)}else E=null==v?void 0:v.codecSet,T=null==v?void 0:v.videoRange;const R=d?d.duration:c?c.duration:0,I=this.bwEstimator.getEstimateTTFB()/1e3,D=[];for(let o=i;o>=t;o--){var P;const t=f[o],c=o>u;if(!t)continue;if(m.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&(qi(t,_,T,S,e,b)||Li(t.videoCodec))?(t.supportedPromise=zi(t,_,i),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;const i=this.hls.levels,s=i.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${s} ${as(e)}`):e.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${as(e)}`),s>-1&&i.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}))):t.supportedResult=Yi}if((E&&t.codecSet!==E||T&&t.videoRange!==T||c&&S>t.frameRate||!c&&S>0&&S<t.frameRate||t.supportedResult&&(null==(P=t.supportedResult.decodingInfoResults)||!P[0].smooth))&&(!A||o!==k)){D.push(o);continue}const g=t.details,v=(d?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||R;let L;L=c?a*e:n*e;const C=R&&s>=2*R&&0===r?t.averageBitrate:t.maxBitrate,w=this.getTimeToLoadFrag(I,L,C*v,void 0===g);if(L>=C&&(o===h||0===t.loadError&&0===t.fragmentError)&&(w<=I||!ht(w)||y&&!this.bitrateTestDelay||w<l)){const e=this.forcedAutoLevel;return o===p||-1!==e&&e===p||(D.length&&this.trace(`Skipped level(s) ${D.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[D[0]].codecs}" ${f[D[0]].videoRange}; not compatible with "${E}" ${T}`),this.info(`switch candidate:${u}->${o} adjustedbw(${Math.round(L)})-bitrate=${Math.round(L-C)} ttfb:${I.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${w.toFixed(1)} firstSelection:${A} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${p}`)),A&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},bufferController:class extends It{constructor(e,t){var i;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(gt.MEDIA_ATTACHED,{media:t,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(i=Mt(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.on(gt.BUFFER_RESET,this.onBufferReset,this),e.on(gt.BUFFER_APPENDING,this.onBufferAppending,this),e.on(gt.BUFFER_CODECS,this.onBufferCodecs,this),e.on(gt.BUFFER_EOS,this.onBufferEos,this),e.on(gt.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(gt.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(gt.FRAG_PARSED,this.onFragParsed,this),e.on(gt.FRAG_CHANGED,this.onFragChanged,this),e.on(gt.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.off(gt.BUFFER_RESET,this.onBufferReset,this),e.off(gt.BUFFER_APPENDING,this.onBufferAppending,this),e.off(gt.BUFFER_CODECS,this.onBufferCodecs,this),e.off(gt.BUFFER_EOS,this.onBufferEos,this),e.off(gt.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(gt.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(gt.FRAG_PARSED,this.onFragParsed,this),e.off(gt.FRAG_CHANGED,this.onFragChanged,this),e.off(gt.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?_t(i,s.tracks):this.sourceBuffers.forEach((e=>{const[t]=e;t&&(i[t]=_t({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null})),{media:e,mediaSource:t,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media,s=Mt(this.appendSource);if(this.transferData=this.overrides=void 0,i&&s){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const r=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(r),e)this._objectUrl=i.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const t=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||t&&r instanceof t,mo(i),function(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(i=e.constructor)?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,s=t.tracks,r=s?Object.keys(s):null,n=r?r.length:0,a=()=>{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: ${as(i,((e,t)=>"initSegment"===e?void 0:t))};\ntransfer tracks: ${as(s,((e,t)=>"initSegment"===e?void 0:t))}}`),!Ft(s,i)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(gt.MEDIA_DETACHING,{}),this.onMediaAttaching(gt.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach((e=>{const t=e,i=s[t];if(i){const e=i.buffer;if(e){const s=this.fragmentTracker,r=i.id;if(s.hasFragments(r)||s.hasParts(r)){const i=tr.getBuffered(e);s.detectEvictedFragments(t,i,r,null,!0)}const n=vo(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,i)}}})),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((([e])=>{e&&this.removeBuffer(e)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),r.removeSourceBuffer(t[i]);e&&r.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(s.removeAttribute("src"),this.appendSource&&mo(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(gt.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach((([e])=>{e&&this.resetBuffer(e)})),this.initTracks()}resetBuffer(e){var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[vo(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new co(this.tracks)}onBufferCodecs(e,t){const i=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const r="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),n=!r&&this.sourceBufferCount&&this.media&&s.some((e=>!i[e]));r||n?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`):(s.forEach((e=>{var s,r,n;const a=t[e],{id:o,codec:l,levelCodec:h,container:u,metadata:c,supplemental:d}=a;let f=i[e];const g=null==(s=this.transferData)||null==(r=s.tracks)?void 0:r[e],p=null!=g&&g.buffer?g:f,m=(null==p?void 0:p.pendingCodec)||(null==p?void 0:p.codec),v=null==p?void 0:p.levelCodec;f||(f=i[e]={buffer:void 0,listeners:[],codec:l,supplemental:d,container:u,levelCodec:h,metadata:c,id:o});const y=Gi(m,v),A=null==y?void 0:y.replace(fo,"$1");let E=Gi(l,h);const T=null==(n=E)?void 0:n.replace(fo,"$1");E&&y&&A!==T&&("audio"===e.slice(0,5)&&(E=$i(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(f.pendingCodec||f.codec)&&(f.pendingCodec=E),f.container=u,this.appendChangeType(e,u,E))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e}),{})}appendChangeType(e,t,i){const s=`${t};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),n.changeType(s),r.codec=i,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,At))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>s||null!=t&&t.buffer&&tr.isBuffered(t.buffer,s)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,At))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:r,parent:n,frag:a,part:o,chunkMeta:l}=t,h=l.buffering[r],u=a.sn,c=self.performance.now();h.start=c;const d=a.stats.buffering,f=o?o.stats.buffering:null;0===d.start&&(d.start=c),f&&0===f.start&&(f.start=c);const g=i.audio;let p=!1;"audio"===r&&"audio/mpeg"===(null==g?void 0:g.container)&&(p=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const m=this.tracks.video,v=null==m?void 0:m.buffer;if(v&&"initSegment"!==u){const e=o||a,t=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend){if("video"===r){const i=e.end;if(t){const e=t.frag.start;(i>e||i<this.lastVideoAppendEnd||tr.isBuffered(v,e))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const t=e.start+.05*e.duration,i=v.buffered,s=this.currentOp("video");i.length||s?!s&&!tr.isBuffered(v,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const y=(o||a).start,A={label:`append-${r}`,execute:()=>{if(h.executeStart=self.performance.now(),p){const e=this.tracks[r];if(e){const t=e.buffer;if(t){const e=y-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${y} (delta: ${e}) sn: ${u})`),t.timestampOffset=y)}}}this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();h.executeEnd=h.end=e,0===d.first&&(d.first=e),f&&0===f.first&&(f.first=e);const t={};this.sourceBuffers.forEach((([e,i])=>{e&&(t[e]=tr.getBuffered(i))})),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(gt.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const i={type:dt.MEDIA_ERROR,parent:a.type,details:ft.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},s=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR)i.details=ft.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!s)i.errorAction=ws(!0);else if(e.name===go&&0===this.sourceBufferCount)i.errorAction=ws(!0);else{const e=++this.appendErrors[r];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${s||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}this.hls.trigger(gt.ERROR,i)}};this.append(A,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(gt.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:r}=t;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach((([e])=>{e&&this.append(this.getFlushOp(e,s,r),e)}))}onFragParsed(e,t){const{frag:i,part:s}=t,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[Qt]?r.push("audiovideo"):(n[zt]&&r.push("audio"),n[Xt]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const e=self.performance.now();i.stats.buffering.end=e,s&&(s.stats.buffering.end=e);const t=s?s.stats:i.stats;this.hls.trigger(gt.FRAG_BUFFERED,{frag:i,part:s,stats:t,id:i.type})}),r).catch((e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t,i;return e&&(!(null!=(t=this.tracks[e])&&t.ended)||(null==(i=this.tracks[e])?void 0:i.ending))}))}onBufferEos(e,t){var i;this.sourceBuffers.forEach((([e])=>{if(e){const i=this.tracks[e];t.type&&t.type!==e||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}}));const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)}))&&(s?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(gt.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(gt.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach((([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen((()=>this.updateMediaSource(e)))}onError(e,t){if(t.details===ft.BUFFER_APPEND_ERROR&&t.frag){var i;const e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;ht(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||null===t)return;if(!this.sourceBufferCount)return;const s=e.config,r=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(ht(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(r/n)*n-e;this.flushBackBuffer(r,n,t)}if(ht(s.frontBufferFlushThreshold)&&s.frontBufferFlushThreshold>0){const e=Math.max(s.maxBufferLength,s.frontBufferFlushThreshold),t=Math.max(e,n),i=Math.floor(r/n)*n+t;this.flushFrontBuffer(r,n,i)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach((([e,t])=>{if(t){const r=tr.getBuffered(t);if(r.length>0&&i>r.start(0)){var s;this.hls.trigger(gt.BACK_BUFFER_REACHED,{bufferEnd:i});const t=this.tracks[e];if(null!=(s=this.details)&&s.live)this.hls.trigger(gt.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(gt.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}}))}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach((([t,s])=>{if(s){const r=tr.getBuffered(s),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(i>a||e>=a&&e<=o)return;this.hls.trigger(gt.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}}))}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,s)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return ht(r)?{duration:r}:null;const n=this.media.duration;return s>(ht(i.duration)?i.duration:0)&&s>n||!ht(n)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==e&&(ht(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),void 0!==t&&void 0!==i&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${as(i)}`),this.tracksReady){var s;const e=null==(s=this.transferData)?void 0:s.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach((([t,i])=>{if(t){const s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}})),this.hls.trigger(gt.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([e])=>{this.executeNext(e)}))}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),r=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${as(a)}`);try{const e=i.addSourceBuffer(r),s=vo(n),o=[n,e];t[s]=o,a.buffer=e}catch(e){var s;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[n],void this.hls.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&("video"===t||"audiovideo"===t)&&Oi(i,"video")&&(s=function(e,t){const i=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)wi(t[e],"video")||i.push(t[e])}return t&&i.push(t),i.join(",")}(s,i));const r=Gi(s,e.levelCodec);return r?"audio"===t.slice(0,5)?$i(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",((e,t)=>{const i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(gt.BUFFER_FLUSHED,{type:e})}))}get mediaSrc(){var e,t;const i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const r=this.currentOp(e);r&&r.onError(s)}removeExecutor(e,t,i){const{media:s,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!s||!r||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=ht(s.duration)?s.duration:1/0,l=ht(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(i,o,l);u>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),a.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],s=null==i?void 0:i.buffer;if(!s)throw new po(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some((([e,t])=>e&&t.updating))}isQueued(){return this.sourceBuffers.some((([e])=>e&&!!this.currentOp(e)))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,s=t.map((e=>this.appendBlocker(e)));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then((t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(e){e.forEach((e=>{var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;i&&!i.updating&&this.shiftAndExecuteNext(e)}))}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((e,t)=>e+(this.isPending(this.tracks[t])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((e,[t])=>e+(t?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([e])=>e)).filter((e=>!!e))}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,e);s.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach((e=>{i.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},capLevelController:yo,errorController:class extends It{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(gt.ERROR,this.onError,this),e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(gt.ERROR,this.onError,this),e.off(gt.ERROR,this.onErrorOut,this),e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===At?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,r=t.context;switch(t.details){case ft.FRAG_LOAD_ERROR:case ft.FRAG_LOAD_TIMEOUT:case ft.KEY_LOAD_ERROR:case ft.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ft.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=ws());case ft.FRAG_GAP:case ft.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=ks);case ft.LEVEL_EMPTY_ERROR:case ft.LEVEL_PARSING_ERROR:{var n,a;const e=t.parent===At?t.level:s.loadLevel;t.details===ft.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(a=n.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ft.LEVEL_LOAD_ERROR:case ft.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case ft.AUDIO_TRACK_LOAD_ERROR:case ft.AUDIO_TRACK_LOAD_TIMEOUT:case ft.SUBTITLE_LOAD_ERROR:case ft.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=s.loadLevelObj;if(e&&(r.type===vt&&e.hasAudioGroup(r.groupId)||r.type===yt&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=ks,void(t.errorAction.flags=Ps)}return;case ft.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.loadLevelObj,i=null==e?void 0:e.attrs["HDCP-LEVEL"];i?t.errorAction={action:ks,flags:Cs,hdcpLevel:i}:this.keySystemError(t)}return;case ft.BUFFER_ADD_CODEC_ERROR:case ft.REMUX_ALLOC_ERROR:case ft.BUFFER_APPEND_ERROR:var o;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(o=t.level)?o:s.loadLevel);return;case ft.INTERNAL_EXCEPTION:case ft.BUFFER_APPENDING_ERROR:case ft.BUFFER_FULL_ERROR:case ft.LEVEL_SWITCH_ERROR:case ft.BUFFER_STALLED_ERROR:case ft.BUFFER_SEEK_OVER_HOLE:case ft.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=ws())}t.type===dt.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=Ts(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++;if(Ls(i,s,Es(e),e.response))return{action:Is,flags:Ds,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(e,t);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=Ts(e.details.startsWith("key")?n:r,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(s){e.details!==ft.FRAG_GAP&&s.fragmentError++;if(Ls(a,o,Es(e),e.response))return{action:Is,flags:Ds,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;null==t&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var r,n;const t=e.details;s.loadError++,t===ft.BUFFER_APPEND_ERROR&&s.fragmentError++;let l=-1;const{levels:h,loadLevel:u,minAutoLevel:c,maxAutoLevel:d}=i;i.autoLevelEnabled||(i.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===Et&&t===ft.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===ft.BUFFER_ADD_CODEC_ERROR||t===ft.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:e})=>s.audioCodec!==e)),p="video"===e.sourceBufferName&&(t===ft.BUFFER_ADD_CODEC_ERROR||t===ft.BUFFER_APPEND_ERROR)&&h.some((({codecSet:e,audioCodec:t})=>s.codecSet!==e&&s.audioCodec===t)),{type:m,groupId:v}=null!=(n=e.context)?n:{};for(let i=h.length;i--;){const r=(i+u)%h.length;if(r!==u&&r>=c&&r<=d&&0===h[r].loadError){var a,o;const i=h[r];if(t===ft.FRAG_GAP&&f===At&&e.frag){const t=h[r].details;if(t){const i=ms(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(m===vt&&i.hasAudioGroup(v)||m===yt&&i.hasSubtitleGroup(v))continue;if(f===Et&&null!=(a=s.audioGroups)&&a.some((e=>i.hasAudioGroup(e)))||f===Tt&&null!=(o=s.subtitleGroups)&&o.some((e=>i.hasSubtitleGroup(e)))||g&&s.audioCodec===i.audioCodec||!g&&s.audioCodec!==i.audioCodec||p&&s.codecSet===i.codecSet)continue}l=r;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:ks,flags:Ds,nextAutoLevel:l}}return{action:ks,flags:Ps}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case _s:break;case ks:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ft.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s,hdcpLevel:r,nextAutoLevel:n}=i;switch(s){case Ds:this.switchLevel(e,n);break;case Cs:r&&(t.maxHdcpLevel=Xi[Xi.indexOf(r)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===ft.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=Hi(e.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${e.sourceBufferName}Codec`]===t&&this.hls.removeLevel(s)}}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const e=s-this.lastTime,r=i-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger(gt.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(gt.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:wr,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,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:gh,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 Pn{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",Tt),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.on(gt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(gt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(gt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(gt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(gt.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.off(gt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(gt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(gt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(gt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(gt.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=An,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if(Jt(i)&&(this.fragPrevious=i),this.state=An,!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let e=0;e<r.length;e++)if(a>=r[e].start&&a<=r[e].end){n=r[e];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(0===i&&s!==Number.POSITIVE_INFINITY){const e=s-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let i=0;i<t.length;)if(t[i].end<=e)t.shift();else{if(!(t[i].start<e))break;t[i].start=e,i++}})),this.fragmentTracker.removeFragmentsInRange(i,e,Tt)}}onError(e,t){const i=t.frag;(null==i?void 0:i.type)===Tt&&(t.details===ft.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==yn&&(this.state=An))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&lo(this.levels,t)?this.levels=t.map((e=>new ss(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new ss(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Tt),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==yn&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:a}=t;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&t&&(l=t.start,an(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(mn(n,e),l=n.fragmentStart):t&&(l=t.start,an(n,l))}if(o.details=n,this.levelLastLoaded=o,a===s&&(this.hls.trigger(gt.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===An)){ms(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&fr(s.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,gr(s.method)).catch((e=>{throw r.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{const s=performance.now();r.trigger(gt.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:s}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=An}))}}doTick(){if(this.media){if(this.state===An){const{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;const{config:s}=this,r=this.getLoadPosition(),n=tr.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 h=l.fragments,u=h.length,c=l.edge;let d=null;const f=this.fragPrevious;if(a<c){const e=s.maxFragLookUpTolerance,t=a>c-e?0:e;d=ms(f,h,Math.max(h[0].start,a),t),!d&&f&&f.start<h[0].start&&(d=h[0])}else d=h[u-1];if(d=this.filterReplacedPrimary(d,i.details),!d)return;const g=h[d.sn-l.startSN-1];if(g&&g.cc===d.cc&&this.fragmentTracker.getState(g)===Os&&(d=g),this.fragmentTracker.getState(d)===Os){const e=this.mapToInitFragWhenRequired(d);e&&this.loadFragment(e,i,a)}}}else this.state=An}loadFragment(e,t,i){Jt(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Al(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends oo{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=sl(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}const i=this.findTrackForTextTrack(e);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.on(gt.LEVEL_LOADING,this.onLevelLoading,this),e.on(gt.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(gt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(gt.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.off(gt.LEVEL_LOADING,this.onLevelLoading,this),e.off(gt.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(gt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(gt.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,s)return;sl(i.textTracks).forEach((e=>{tl(e)}))}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==s?void 0:s.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!r&&t){this.selectDefaultTrack=!1;const i=us(t,e);if(i>-1)r=e[i];else{const e=us(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(gt.SUBTITLE_TRACKS_UPDATED,n),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const r=t[s];if((!i||r.default)&&(i||e)&&(!e||cs(r,e)))return s}if(e){for(let i=0;i<t.length;i++){const s=t[i];if(ho(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const s=t[i];if(ho(e.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){if(uo(t[i],e))return i}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==yt||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&cs(e,i))return i;const s=us(e,this.tracksInGroup);if(s>-1){const e=this.tracksInGroup[s];return this.setSubtitleTrack(s),e}if(i)return null;{const i=us(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(gt.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=sl(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter((e=>uo(i,e)))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach((e=>{"disabled"!==e.mode&&e!==s&&(e.mode="disabled")})),s){const e=this.subtitleDisplay?"showing":"hidden";s.mode!==e&&(s.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!ht(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(gt.SUBTITLE_TRACK_SWITCH,{id:e});const r=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=s;this.hls.trigger(gt.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const u=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(u)}},timelineController:class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(gt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(gt.FRAG_LOADING,this.onFragLoading,this),e.on(gt.FRAG_LOADED,this.onFragLoaded,this),e.on(gt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(gt.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(gt.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(gt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(gt.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(gt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(gt.FRAG_LOADING,this.onFragLoading,this),e.off(gt.FRAG_LOADED,this.onFragLoaded,this),e.off(gt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(gt.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(gt.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(gt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(gt.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new uh(this,"textTrack1"),t=new uh(this,"textTrack2"),i=new uh(this,"textTrack3"),s=new uh(this,"textTrack4");this.cea608Parser1=new Fl(1,e,t),this.cea608Parser2=new Fl(3,i,s)}addCues(e,t,i,s,r){let n=!1;for(let e=r.length;e--;){const s=r[e],u=(a=s[0],o=s[1],l=t,h=i,Math.min(o,h)-Math.max(a,l));if(u>=0&&(s[0]=Math.min(s[0],t),s[1]=Math.max(s[1],i),n=!0,u/(i-t)>.5))return}var a,o,l,h;if(n||r.push([t,i]),this.config.renderTextTracksNatively){const r=this.captionsTracks[e];this.Cues.newCue(r,t,i,s)}else{const r=this.Cues.newCue(null,t,i,s);this.hls.trigger(gt.CUES_PARSED,{type:"captions",cues:r,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r}){const{unparsedVttFrags:n}=this;i===At&&(this.initPTS[t.cc]={baseTime:s,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach((e=>{this.onFragLoaded(gt.FRAG_LOADED,e)})))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(dh(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:r,languageCode:n}=t[e],a=this.getExistingTrack(r,n);if(a)i[e]=a,tl(i[e]),Jo(i[e],s);else{const t=this.createTextTrack("captions",r,n);t&&(t[e]=!0,i[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(gt.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach((e=>{tl(s[e]),delete s[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)tl(t[e])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some((e=>e.textCodec===Jl));if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(lo(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const e=this.media,t=e?sl(e.textTracks):null;if(this.tracks.forEach(((e,i)=>{let s;if(t){let i=null;for(let s=0;s<t.length;s++)if(t[s]&&dh(t[s],e)){i=t[s],t[s]=null;break}i&&(s=i)}if(s)tl(s);else{const t=ch(e);s=this.createTextTrack(t,e.name,e.lang),s&&(s.mode="disabled")}s&&this.textTracks.push(s)})),null!=t&&t.length){const e=t.filter((e=>null!==e)).map((e=>e.label));e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(gt.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const i=`textTrack${t[1]}`,s=this.captionsProperties[i];s&&(s.label=e.name,e.lang&&(s.languageCode=e.lang),s.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===At){var i,s;const{cea608Parser1:e,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(i=null==(s=t.part)?void 0:s.index)?i:-1;e&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===Tt)if(s.byteLength){const e=i.decryptdata,r="stats"in t;if(null==e||!e.encrypted||r){const e=this.tracks[i.level],r=this.vttCCs;r[i.cc]||(r[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===Jl?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(gt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;sh(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),i.trigger(gt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{i.logger.log(`Failed to parse IMSC1: ${t}`),i.trigger(gt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[i.cc]&&-1===a)return void n.push(e);const o=this.hls;Zl(null!=(t=i.initSegment)&&t.data?Si(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(e=>{this._appendCues(e,i.level),o.trigger(gt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(t=>{const r="Missing initPTS for VTT MPEGTS"===t.message;r?n.push(e):this._fallbackToIMSC1(i,s),o.logger.log(`Failed to parse VTT cue: ${t}`),r&&a>i.cc||o.trigger(gt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})}))}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||sh(t,this.initPTS[e.cc],(()=>{i.textCodec=Jl,this._parseIMSC1(e,t)}),(()=>{i.textCodec="wvtt"}))}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach((e=>el(i,e)))}else{const s=this.tracks[t];if(!s)return;const r=s.default?"default":"subtitles"+t;i.trigger(gt.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===Tt&&this.onFragLoaded(gt.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(i.type!==At||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;e<s.length;e++){const t=s[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(t);this.cea608Parser1.addData(s[e].pts,i[0]),this.cea608Parser2.addData(s[e].pts,i[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!r||"video"===r){const{captionsTracks:e}=this;Object.keys(e).forEach((s=>il(e[s],t,i)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==s){const{textTracks:e}=this;Object.keys(e).forEach((i=>il(e[i],t,s)))}}}extractCea608Data(e){const t=[[],[]],i=31&e[0];let s=2;for(let r=0;r<i;r++){const i=e[s++],r=127&e[s++],n=127&e[s++];if(0===r&&0===n)continue;if(!!(4&i)){const e=3&i;0!==e&&1!==e||(t[e].push(r),t[e].push(n))}}return t}},audioStreamController:class extends Pn{constructor(e,t,i){super(e,t,i,"audio-stream-controller",Et),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.on(gt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(gt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(gt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(gt.BUFFER_RESET,this.onBufferReset,this),e.on(gt.BUFFER_CREATED,this.onBufferCreated,this),e.on(gt.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(gt.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(gt.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(gt.FRAG_LOADING,this.onFragLoading,this),e.on(gt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.off(gt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(gt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(gt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(gt.BUFFER_RESET,this.onBufferReset,this),e.off(gt.BUFFER_CREATED,this.onBufferCreated,this),e.off(gt.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(gt.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(gt.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(gt.FRAG_LOADING,this.onFragLoading,this),e.off(gt.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r}){if(i===At){const e=t.cc,i=this.fragCurrent;if(this.initPTS[e]={baseTime:s,timescale:r},this.log(`InitPTS for cc: ${e} found from main: ${s}/${r}`),this.mainAnchor=t,this.state===In){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==e)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&i&&i.cc!==e?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,i.abortRequests(),this.resetLoadingState()):this.state===An&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),i=e.cc;return function(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){const s=i.start,r=i.end;let n=e.fragments;if(!i.relurl){const{fragmentHint:t}=e;t&&(n=n.concat(t))}return ps(n,(e=>e.cc<t||e.end<=s?1:e.cc>t||e.start>=r?-1:0))}return null}(t,i,e)||t&&As(t.fragments,i)||e}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=yn);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=An):this.state=bn,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case An:this.doTickIdle();break;case bn:{const{levels:e,trackId:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=In}break}case Sn:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:e,trackId:t}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==e?void 0:e[t])||null),this.state=An}break}case In:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:r}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=Tn;const e={frag:t,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),r&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&(this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${n.cc}`),this.nextLoadPosition=this.findSyncFrag(n).start,this.clearWaitingFragment())}else this.state=An}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==yn&&(this.state=An))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:r}=this,n=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[r])return;const a=i[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=bn,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,zt,Et));const h=this.getFwdBufferInfo(l,Et);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(gt.BUFFER_EOS,{type:"audio"}),void(this.state=kn);const u=h.len,c=t.maxBufferLength,d=o.fragments,f=d[0].start,g=this.getLoadPosition(),p=this.flushing?g:h.end;if(this.switchingTrack&&s){const e=g;o.PTSKnown&&e<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(u>=c&&!this.switchingTrack&&p<d[d.length-1].start)return;let m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,h,At,c)),!m)return void(this.bufferFlushed=!0);let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Jt(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Fs&&(this.mainFragLoading=v=null),v&&Jt(v))){if(m.start>v.end){const e=this.fragmentTracker.getFragAtPos(p,At);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(m.start>v.end)return}this.loadFragment(m,a,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new ss(e)))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==yn&&(this.setInterval(100),this.state=An,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(gt.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:r,id:n,groupId:a,track:o}=t;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==yn&&(this.state=bn));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=s[n];let u=0;if(r.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;if(h.details)u=this.alignPlaylists(r,h.details,null==(c=this.levelLastLoaded)?void 0:c.details);r.alignedSliding||(pn(r,l),r.alignedSliding||mn(r,l),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(gt.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state!==bn||this.waitForCdnTuneIn(r)||(this.state=An),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const u=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new ao(this.hls,Et,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==d){const e=!1,t=s?s.index:-1,n=-1!==t,a=new Js(i.level,i.sn,i.stats.chunkCount,r.byteLength,t,n);c.push(r,f,u,"",i,s,h.totalduration,e,a,d)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new wn,complete:!1};e.push(new Uint8Array(r)),this.state!==yn&&(this.state=In)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===At&&Jt(t.frag)&&(this.mainFragLoading=t,this.state===An&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type===Et)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(Jt(i)){this.fragPrevious=i;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(gt.AUDIO_TRACK_SWITCHED,Rt({},e)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==At||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var i;if(t.fatal)this.state=Rn;else switch(t.details){case ft.FRAG_GAP:case ft.FRAG_PARSING_ERROR:case ft.FRAG_DECRYPT_ERROR:case ft.FRAG_LOAD_ERROR:case ft.FRAG_LOAD_TIMEOUT:case ft.KEY_LOAD_ERROR:case ft.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Et,t);break;case ft.AUDIO_TRACK_LOAD_ERROR:case ft.AUDIO_TRACK_LOAD_TIMEOUT:case ft.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==bn||(null==(i=t.context)?void 0:i.type)!==vt||(this.state=An);break;case ft.BUFFER_ADD_CODEC_ERROR:case ft.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.resetLoadingState();break;case ft.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ft.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==Xt&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Xt){this.flushing=!1,this.bufferFlushed=!0,this.state===kn&&(this.state=An);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,Et),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:u}=h,{audio:c,text:d,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&u){if(this.state=Ln,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;this._bufferInitSegment(h,g.tracks,e,n),s.trigger(gt.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(c){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=c;l&&(l.elementaryStreams[zt]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),o.setElementaryStreamInfo(zt,e,t,i,s),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=_t({id:i,frag:o,details:u},f);s.trigger(gt.FRAG_PARSING_METADATA,e)}if(d){const e=_t({id:i,frag:o,details:u},d);s.trigger(gt.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,i,s){if(this.state!==Ln)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const r=t.audio;r.id=Et;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(gt.BUFFER_CODECS,t);const a=r.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:a};this.hls.trigger(gt.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);var r;if(this.switchingTrack||s===Os||s===Ms)if(Jt(e))if(null!=(r=t.details)&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=In;const i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&mn(t.details,i)}else super.loadFragment(e,t,i);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;cs({name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},e,ds)||(gs(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(gt.AUDIO_TRACK_SWITCHED,Rt({},e))}},audioTrackController:class extends oo{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.on(gt.LEVEL_LOADING,this.onLevelLoading,this),e.on(gt.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(gt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(gt.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.off(gt.LEVEL_LOADING,this.onLevelLoading,this),e.off(gt.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(gt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(gt.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==s?void 0:s.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!r&&t){const i=us(t,e,ds);if(i>-1)r=e[i];else{const e=us(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(gt.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==s&&-1===o)this.setAudioTrack(s);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==vt||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&cs(e,s,ds))return s;const r=us(e,this.tracksInGroup,ds);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r),e}if(s){let s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);const r=function(e,t,i,s,r){const n=t[s],a=t.reduce(((e,t,i)=>{const s=t.uri;return(e[s]||(e[s]=[])).push(i),e}),{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),u=fs(t,s,(t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;const s=t.audioGroups,n=i.filter((e=>!s||-1!==s.indexOf(e.groupId)));return us(e,n,r)>-1}));return u>-1?u:fs(t,s,(t=>{const s=t.audioGroups,n=i.filter((e=>!s||-1!==s.indexOf(e.groupId)));return us(e,n,r)>-1}))}(e,t.levels,i,s,ds);if(-1===r)return null;t.nextLoadLevel=r}if(e.channels||e.audioCodec){const t=us(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],r=s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;if(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(gt.AUDIO_TRACK_SWITCHING,Rt({},s)),r)return;const n=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if((!this.selectDefaultTrack||s.default)&&(!e||cs(e,s,ds)))return i}if(e){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(cs({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},t[e],ds))return e}for(let i=0;i<t.length;i++){const s=t[i];if(ho(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const s=t[i];if(ho(e.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&gs(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(gt.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},emeController:Qo,cmcdController:class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:Ao.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:i}=e,s=this.hls.levels[t.level],r=this.getObjectType(t),n={d:1e3*(i||t).duration,ot:r};r!==Ao.VIDEO&&r!==Ao.AUDIO&&r!=Ao.MUXED||(n.br=s.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=i?this.getNextPart(i):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(n.nor=a.url),this.apply(e,n)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(gt.MEDIA_DETACHED,this.onMediaDetached,this),e.on(gt.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(gt.MEDIA_DETACHED,this.onMediaDetached,this),e.off(gt.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,s;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=t.tracks.video)?void 0:s.buffer}createData(){var e;return{v:1,sf:Eo.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){_t(t,this.createData());const i=t.ot===Ao.INIT||t.ot===Ao.VIDEO||t.ot===Ao.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce(((e,i)=>(s.includes(i)&&(e[i]=t[i]),e)),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),jo(e.headers,t,r)):e.url=qo(e.url,t,r)}getNextFrag(e){var t;const i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){const t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t,i;const{index:s,fragment:r}=e,n=null==(t=this.hls.levels[r.level])||null==(i=t.details)?void 0:i.partList;if(n){const{sn:e}=r;for(let t=n.length-1;t>=0;t--){const i=n[t];if(i.index===s&&i.fragment.sn===e)return n[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?Ao.TIMED_TEXT:"initSegment"===e.sn?Ao.INIT:"audio"===t?Ao.AUDIO:"main"===t?this.hls.audioTracks.length?Ao.VIDEO:Ao.MUXED:void 0}getTopBandwidth(e){let t,i=0;const s=this.hls;if(e===Ao.AUDIO)t=s.audioTracks;else{const e=s.maxAutoLevel,i=e>-1?e+1:s.levels.length;t=s.levels.slice(0,i)}for(const e of t)e.bitrate>i&&(i=e.bitrate);return i>0?i:NaN}getBufferLength(e){const t=this.media,i=e===Ao.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!t)return NaN;return 1e3*tr.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}},contentSteeringController:class extends It{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.on(gt.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.off(gt.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((null==i?void 0:i.action)===ks&&i.flags===Ps){const e=this.levels;let s=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:i,pathwayId:s,type:n}=t.context;i&&e?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&e&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r),i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${as(s)} penalized: ${as(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this._pathwayPriority=e;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach((e=>{s-i[e]>3e5&&delete i[e]}));for(let s=0;s<e.length;s++){const r=e[s];if(r in i)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,cn(t),this.hls.trigger(gt.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(t===vt&&s[i].hasAudioGroup(e)||t===yt&&s[i].hasSubtitleGroup(e))return s[i].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach((e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===r)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new hr(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(i[t.AUDIO]=n,t.AUDIO=n),o&&(s[t.SUBTITLES]=o,t.SUBTITLES=o);const l=Xo(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new ss({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)h.addGroupId("audio",`${e.audioGroups[t]}_clone_${r}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)h.addGroupId("text",`${e.subtitleGroups[t]}_clone_${r}`);return h}));t.push(...o),zo(this.audioTracks,i,a,r),zo(this.subtitleTracks,s,a,r)}))}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;let s;this.loader&&this.loader.destroy(),this.loader=new i(t);try{s=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==s.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+e)}const r={responseType:"json",url:s.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,i,r)=>{this.log(`Loaded steering manifest: "${s}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,s).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:s.toString()};this.hls.trigger(gt.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,i,s)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,r);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}},interstitialsController:class extends It{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const i=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule()}if(this.checkBuffer(),i&&e<s.start||e>=s.end){var r;const e=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(s)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i){const t=this.findItemIndex(s);if(e>t){const i=this.schedule.findJumpRestrictedIndex(t+1,e);if(i>t)return void this.setSchedulePosition(i)}}return void this.setSchedulePosition(e)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(s)){const t=s.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;(i&&e<a||e>=a+o)&&this.setScheduleToAssetAtTime(e,n)},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const i=this.playingAsset;if(!i)return;e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{const i=this.schedule,s=this.playingItem,r=i.events||[],n=i.items||[],a=i.durations,o=e.map((e=>e.identifier)),l=!(!r.length&&!o.length);if(l&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map((e=>gl(e)))}`),o.length&&this.log(`Removed events ${o}`),this.playerQueue.forEach((e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(s){Math.abs(i)>nl&&this.warn(`${s} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}})),s){const e=this.updateItem(s,this.timelinePos);this.itemsMatch(s,e)&&(this.playingItem=e,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const h=this.bufferingItem;if(h){const e=this.updateItem(h,this.bufferedPos);this.itemsMatch(h,e)?this.bufferingItem=e:h.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(h.event,null))}if(e.forEach((e=>{e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,null)}))})),l||t){if(this.hls.trigger(gt.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(s)&&o.includes(s.event.identifier))return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new pl(e),this.schedule=new fl(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e.on(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(gt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(gt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(gt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(gt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(gt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(gt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(gt.BUFFER_APPENDED,this.onBufferAppended,this),e.on(gt.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(gt.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(gt.MEDIA_ENDED,this.onMediaEnded,this),e.on(gt.ERROR,this.onError,this),e.on(gt.DESTROYING,this.onDestroying,this)}unregisterListeners(){const e=this.hls;e&&(e.off(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(gt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(gt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(gt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(gt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(gt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(gt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(gt.BUFFER_CODECS,this.onBufferCodecs,this),e.off(gt.BUFFER_APPENDED,this.onBufferAppended,this),e.off(gt.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(gt.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(gt.MEDIA_ENDED,this.onMediaEnded,this),e.off(gt.ERROR,this.onError,this),e.off(gt.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){vl(e,"play",this.onPlay),vl(e,"pause",this.onPause),vl(e,"seeking",this.onSeeking),vl(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;ml(i,"seeking",this.onSeeking),ml(i,"timeupdate",this.onTimeupdate),ml(i,"play",this.onPlay),ml(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const e=this.findItemIndex(i);this.setSchedulePosition(e)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=t=>t?e.getAssetPlayer(t.identifier):t,s=(t,s,r,a,o)=>{if(t){let l=t[s].start;const h=t.event;if(h){if("playout"===s||h.timelineOccupancy!==al.Point){const e=i(r);(null==e?void 0:e.interstitial)===h&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?n():e[a])-t.start}return l}return 0},r=(t,i)=>{if(0!==t&&"primary"!==i&&e.schedule.length){var s;const r=e.schedule.findItemIndexAtTime(t),n=null==(s=e.schedule.items)?void 0:s[r];if(n){return t+(n[i].start-n.start)}}return t},n=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=t=>{var i;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:e.schedule.durations[t]},o=(t,r)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip)return;e.log(`seek to ${t} "${r}"`);const l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,r),u=null==(a=e.schedule.items)?void 0:a[h],c=e.getBufferingPlayer(),d=null==c?void 0:c.interstitial,f=null==d?void 0:d.appendInPlace,g=l&&e.itemsMatch(l,u);if(l&&(f||g)){const n=i(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const i="primary"===r?a.currentTime:s(l,r,e.playingAsset,"timelinePos","currentTime"),o=t-i,h=(f?i:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(u){let i=t;if("primary"!==r){const e=t-u[r].start;i=u.start+e}const s=!e.isInterstitial(u);if(e.isInterstitial(l)&&!l.event.appendInPlace||!s&&!u.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(h>n){const t=e.schedule.findJumpRestrictedIndex(n+1,h);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(s)e.timelinePos=i,e.checkBuffer();else{var p;const e=null==u||null==(p=u.event)?void 0:p.assetList;if(e){const i=t-(u[r]||u).start;for(let t=e.length;t--;){const s=e[t];if(s.duration&&i>=s.startOffset&&i<s.startOffset+s.duration){a=t;break}}}}e.setSchedulePosition(h,a)}}else{const t=e.media||(f?null==c?void 0:c.media:null);t&&(t.currentTime=i)}}},l=()=>{const i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;const s=t();return e.isInterstitial(s)?s:null},h={get currentTime(){const t=l(),i=e.effectivePlayingItem;return i&&i===t?s(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){const i=l(),s=e.effectivePlayingItem;s&&s===i&&o(t+s.playout.start,"playout")},get duration(){const e=l();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const i=null==(t=l())?void 0:t.event.assetList;return i?i.map((t=>e.getAssetPlayer(t.identifier))):[]},get playingIndex(){var t;const i=null==(t=l())?void 0:t.event;return i&&e.effectivePlayingAsset?i.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var t,i;return(null==(t=e.schedule)||null==(i=t.events)?void 0:i.slice(0))||[]},get schedule(){var t,i;return(null==(t=e.schedule)||null==(i=t.items)?void 0:i.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){o(e,"primary")},get duration(){return a("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){o(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){var t;return r((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){const s=e.findItemIndex(t);if(i.appendInPlace){const e=t.playout.start+t.event.duration;o(e+.001,"playout")}else e.advanceAfterAssetEnded(i,s,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t,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!=(e=this.bufferingItem)&&null!=(t=e.event)&&t.appendInPlace&&(r=this.primaryMedia);const n=null==(i=r)?void 0:i.currentTime;return void 0!==n&&ht(n)?n:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s)return void(this.detachedData={media:s});const i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${as(i)}`),this.detachedData=i}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const e=this.getBufferingPlayer();e?(r=e.transferMedia(),h=`${e}`):h="detached MediaSource"}else h="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${as(r)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach((e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}})),this.hls.detachMedia(),this.detachedData={media:t}}const u=r&&"mediaSource"in r&&"closed"!==(null==(s=r.mediaSource)?void 0:s.readyState),c=u&&r?r:t;if(this.log(`${u?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${h}`),c===r){const t=a&&e.assetId===this.schedule.assetIdAtEnd;c.overrides={duration:this.schedule.duration,endOfStream:!a||t,cueRemoval:!a}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.timelinePos=i,t.length&&t[0].cue.pre){const i=e.findEventIndex(t[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){const t=this.timelinePos=i>0?i:0,s=e.findItemIndexAtTime(t);this.setSchedulePosition(s)}}else if(s&&!this.playingItem){const t=e.findItemIndex(s);this.setSchedulePosition(t)}}advanceAfterAssetEnded(e,t,i){const s=i+1;if(e.isAssetPastPlayoutLimit(s)||e.assetList[s].error){const i=this.schedule.items;if(i){const s=t+1;if(s>=i.length)return void this.setSchedulePosition(-1);const r=e.resumeTime;this.timelinePos<r&&(this.timelinePos=r,this.checkBuffer()),this.setSchedulePosition(s)}}else this.setSchedulePosition(t,s)}setScheduleToAssetAtTime(e,t){const i=this.schedule,s=t.parentIdentifier,r=i.getEvent(s);if(r){const t=i.findEventIndex(s),n=i.findAssetIndex(r,e);this.setSchedulePosition(t,n)}}setSchedulePosition(e,t){const i=this.schedule.items;if(!i||this.playbackDisabled)return;this.log(`setSchedulePosition ${e}, ${t}`);const s=e>=0?i[e]:null,r=this.playingItem,n=this.playingLastItem;if(this.isInterstitial(r)){var a;const l=r.event,h=this.playingAsset,u=null==h?void 0:h.identifier,c=u?this.getAssetPlayer(u):null;if(c&&u&&(!this.eventItemsMatch(r,s)||void 0!==t&&u!==(null==(a=l.assetList)?void 0:a[t].identifier))){var o;const t=l.findAssetIndex(h);this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${l.assetList.length} ${cl(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(gt.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:t,event:l,schedule:i.slice(0),scheduleIndex:e,player:c}),this.retreiveMediaSource(u,s),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(r,s)&&(this.endedItem=r,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${gl(r)}`),l.hasPlayed=!0,this.hls.trigger(gt.INTERSTITIAL_ENDED,{event:l,schedule:i.slice(0),scheduleIndex:e}),l.cue.once)){this.updateSchedule();const e=this.schedule.items;if(s&&e){const i=this.schedule.findItemIndex(s);this.advanceSchedule(i,e,t,r,n)}return}}this.advanceSchedule(e,i,t,r,n)}advanceSchedule(e,t,i,s,r){const n=e>=0?t[e]:null,a=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach((t=>{const i=t.interstitial,s=this.schedule.findEventIndex(i.identifier);(s<e||s>e+1)&&this.clearInterstitial(i,n)})),this.isInterstitial(n)){this.timelinePos=Math.min(Math.max(this.timelinePos,n.start),n.end);const r=n.event;void 0===i&&(i=this.schedule.findAssetIndex(r,this.timelinePos));const o=this.waitingItem;this.assetsBuffered(n,a)||this.setBufferingItem(n);let l=this.preloadAssets(r,i);if(this.eventItemsMatch(n,o||s)||(this.waitingItem=n,this.log(`INTERSTITIAL_STARTED ${gl(n)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(gt.INTERSTITIAL_STARTED,{event:r,schedule:t.slice(0),scheduleIndex:e})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!a)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=n;const h=r.assetList[i];if(!h){const s=t[e+1],n=this.media;return s&&n&&!this.isInterstitial(s)&&n.currentTime<s.start&&(n.currentTime=this.timelinePos=s.start),void this.advanceAfterAssetEnded(r,e,i||0)}if(l||(l=this.getAssetPlayer(h.identifier)),null===l||l.destroyed){const e=r.assetList.length;this.warn(`asset ${i+1}/${e} player destroyed ${r}`),l=this.createAssetPlayer(r,h,i)}if(!this.eventItemsMatch(n,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(l,i,t,e,a),this.shouldPlay&&yl(l.media)}else null!==n?(this.resumePrimary(n,e,s),this.shouldPlay&&yl(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e,t;return null==(e=this.mediaSelection)||null==(t=e.main)?void 0:t.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,i){var s;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${gl(e)}`),null==(s=this.detachedData)||!s.mediaSource){let i=this.timelinePos;(i<e.start||i>=e.end)&&(i=this.getPrimaryResumption(e,t),this.timelinePos=i),this.attachPrimary(i,e)}if(!i)return;const r=this.schedule.items;r&&(this.log(`resumed ${gl(e)}`),this.hls.trigger(gt.INTERSTITIALS_PRIMARY_RESUMED,{schedule:r.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(i<e.fragmentStart||i>e.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return tr.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs(((null==(i=s.mainForwardBufferInfo)?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.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(gt.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(gt.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level)return;const i=this.hls.levels[t.level],s=Rt(Rt({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=Rt(Rt({},this.altSelection),{},{audio:i}));const r=Rt(Rt({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=Rt(Rt({},this.altSelection),{},{subtitles:i}));const r=Rt(Rt({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=hs(t);this.playerQueue.forEach((e=>e.hls.setAudioOption(t)||e.hls.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=hs(t);this.playerQueue.forEach((e=>e.hls.setSubtitleOption(t)||-1!==t.id&&e.hls.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const s=t[e];if(s.cue.post){var i;const e=this.schedule.findEventIndex(s.identifier),t=null==(i=this.schedule.items)?void 0:i[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){const i=this.schedule.items;if(e&&i){return i[this.findItemIndex(e,t)]||null}return null}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))}findItemIndex(e,t){return e?this.schedule.findItemIndex(e,t):-1}updateSchedule(){const e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])}checkBuffer(e){const t=this.schedule.items;if(!t)return;const i=tr.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,t,e)}updateBufferedPos(e,t,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e)return;if(1===t.length&&this.itemsMatch(t[0],r))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,h;const i=this.findItemIndex(r),s=Math.min(i+1,t.length-1),n=t[s];if((-1===o&&r&&e>=r.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=s),s-a>1&&!1===(null==r||null==(h=r.event)?void 0:h.appendInPlace))return;if(this.bufferedPos=e,o>i&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else i&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some((e=>{const i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))}))}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:s,events:r}=i;if(!s||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){const i=a?a.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${gl(e)}`+(t?` (${i.toFixed(2)} remaining)`:"")),n?e.event.assetList.forEach((e=>{const t=this.getAssetPlayer(e.identifier);t&&t.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((e=>e.pauseBuffering())))}this.hls.trigger(gt.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){const e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){const s=i.assetList[t],r=this.primaryMedia;s&&r&&this.bufferAssetPlayer(e,r)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,r=0===s&&!e.assetListLoader,n=e.cue.once;if(r){const r=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-r;e>0&&(n=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(e,0,0,r,e.duration,i);const l=this.assetListLoader.loadAssetList(e,n);l&&(e.assetListLoader=l)}else if(!n&&s){for(let i=t;i<s;i++){const t=e.assetList[i],s=this.getAssetPlayerQueueIndex(t.identifier);-1!==s&&!this.playerQueue[s].destroyed||t.error||this.createAssetPlayer(e,t,i)}return this.getAssetPlayer(e.assetList[t].identifier)}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach((t=>{this.hls.trigger(gt.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null}createAsset(e,t,i,s,r,n){const a={parentIdentifier:e.identifier,identifier:ol(e,n,t),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){this.log(`create HLSAssetPlayer for ${cl(t)}`);const s=this.hls,r=s.userConfig;let n=r.videoPreference;const a=s.loadLevelObj||s.levels[s.currentLevel];(n||a)&&(n=_t({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const i=t.duration;i&&e<i&&(h=e)}}const u=t.identifier,c=Rt(Rt({},r),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(c.timelineOffset=t.timelineStart));const d=c.cmcd;null!=d&&d.sessionId&&d.contentId&&(c.cmcd=_t({},d,{contentId:rl(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const f=new dl(this.HlsPlayerClass,c,e,t);this.playerQueue.push(f),e.assetList[i]=t;const g=s=>{if(s.live){const t=new Error(`Interstitials MUST be VOD assets ${e}`),s={fatal:!0,type:dt.OTHER_ERROR,details:ft.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};return void this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,t.message)}const r=s.edge-s.fragmentStart,n=t.duration;(null===n||r>n)&&(this.log(`Interstitial asset "${u}" duration change ${n} > ${r}`),t.duration=r,this.updateSchedule())};f.on(gt.LEVEL_UPDATED,((e,{details:t})=>g(t))),f.on(gt.LEVEL_PTS_UPDATED,((e,{details:t})=>g(t)));const p=(e,t)=>{const i=this.getAssetPlayer(u);if(i&&t.tracks){i.off(gt.BUFFER_CODECS,p),i.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};f.on(gt.BUFFER_CODECS,p);const m=()=>{var i;const s=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${s}`),!s)return;const r=this.schedule.findEventIndex(e.identifier),n=e.findAssetIndex(t),a=n+1,o=null==(i=this.schedule.items)?void 0:i[r];if(this.isInterstitial(o))if(-1===n||e.isAssetPastPlayoutLimit(a)||e.assetList[a].error){var l;const e=null==(l=this.schedule.items)?void 0:l[r+1];e&&this.bufferedToItem(e)}else this.bufferedToItem(o,a)};f.on(gt.BUFFERED_TO_END,m);const v=t=>()=>{if(!this.getAssetPlayer(u))return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return f.once(gt.MEDIA_ENDED,v(i)),f.once(gt.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(gt.ERROR,((t,s)=>{const r=this.getAssetPlayer(u);if(s.details!==ft.BUFFER_STALLED_ERROR)this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${s.error} ${e}`);else if(null!=r&&r.media){const t=r.currentTime,i=r.duration-t;t&&e.appendInPlace&&i/r.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${u} ${e} at ${r.media.currentTime}`),m()):(this.warn(`Stalled at ${t} of ${t+i} in asset ${u} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}})),f.on(gt.DESTROYING,(()=>{if(!this.getAssetPlayer(u))return;const t=new Error(`Asset player destroyed unexpectedly ${u}`),s={fatal:!0,type:dt.OTHER_ERROR,details:ft.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,t.message)})),this.hls.trigger(gt.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,t)})),e.reset()}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(-1!==i){this.log(`clearAssetPlayer "${e}" toSegment: ${t?gl(t):t}`);const s=this.playerQueue[i];this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[s]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${e}`),this.hls.trigger(gt.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,s;const{interstitial:r,assetItem:n,assetId:a}=e,o=this.schedule.findEventIndex(r.identifier),l=null==(i=this.schedule.items)?void 0:i[o];if(!l)return;this.setBufferingItem(l),this.bufferingAsset=n;const h=this.getBufferingPlayer();if(h===e)return;const u=r.appendInPlace;if(u&&!1===(null==h?void 0:h.interstitial.appendInPlace))return;const c=(null==h?void 0:h.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(u&&n!==this.playingAsset){if(!e.tracks)return;if(c&&!Ft(c,e.tracks)){const t=new Error(`Asset "${a}" SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),i={fatal:!0,type:dt.OTHER_ERROR,details:ft.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},s=r.findAssetIndex(n);return void this.handleAssetItemError(i,r,o,s,t.message)}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,i,s,r){if(e.details===ft.BUFFER_STALLED_ERROR)return;const n=t.assetList[s]||null;let a=null;if(n){const e=this.getAssetPlayerQueueIndex(n.identifier);a=this.playerQueue[e]||null}const o=this.schedule.items,l=_t({},e,{fatal:!1,errorAction:ws(!0),asset:n,assetListIndex:s,event:t,schedule:o,scheduleIndex:i,player:a});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(gt.INTERSTITIAL_ASSET_ERROR,l),!e.fatal)return;const h=new Error(r);n&&(this.playingAsset!==n&&this.clearAssetPlayer(n.identifier,null),n.error=h),t.assetList.some((e=>!e.error))?t.appendInPlace&&(t.error=h):t.error=h,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${i?gl(i):"<none>"} error: ${e.error}`),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));let s=this.timelinePos;-1===s&&(s=this.hls.startPosition);const r=this.updateItem(i,s);if(this.itemsMatch(i,r))this.clearInterstitial(e,null);else{const e=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(e)}}else this.checkStart()}onAssetListLoaded(e,t){var i;const s=t.event,r=s.identifier,n=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(r))return;const a=s.timelineStart,o=s.duration;let l=0;n.forEach(((e,t)=>{const i=parseFloat(e.DURATION);this.createAsset(s,t,l,a+l,i,e.URI),l+=i})),s.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${o}) ${s}`);const h=this.waitingItem,u=(null==h?void 0:h.event.identifier)===r;this.updateSchedule();const c=null==(i=this.bufferingItem)?void 0:i.event;if(u){var d;const e=this.schedule.findEventIndex(r),t=null==(d=this.schedule.items)?void 0:d[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return s.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${s}`),void this.primaryFallback(s)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==c?void 0:c.identifier)===r&&c.appendInPlace){const e=s.assetList[0],t=this.getAssetPlayer(e.identifier),i=this.primaryMedia;e&&t&&i&&this.bufferAssetPlayer(t,i)}}onError(e,t){switch(t.details){case ft.ASSET_LIST_PARSING_ERROR:case ft.ASSET_LIST_LOAD_ERROR:case ft.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&this.primaryFallback(e);break}case ft.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}}}});function Sh(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Sh):Object.keys(e).reduce(((t,i)=>(t[i]=Sh(e[i]),t)),{}):e}function bh(e,t){const i=e.loader;if(i!==mh&&i!==Eh)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=mh,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Lh extends Zs{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(gt.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(gt.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(gt.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const i=this.media=t.media;ml(i,"playing",this.onMediaPlaying),ml(i,"waiting",this.onMediaWaiting),ml(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(vl(i,"playing",this.onMediaPlaying),vl(i,"waiting",this.onMediaWaiting),vl(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const{media:n,stalled:a}=this;if(!n)return;const{seeking:o}=n,l=this.seeking&&!o,h=!this.seeking&&o,u=n.paused&&!o||n.ended||0===n.playbackRate;if(this.seeking=o,e!==t)return t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(h||l)return void(l&&this.stallResolved(e));if(u)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(gt.MEDIA_ENDED,{stalled:!1})));if(!tr.getBuffered(n).length)return void(this.nudgeRetry=0);const c=tr.bufferInfo(n,e,0),d=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const t=_h(this.hls.inFlightFragments,e),i=c.len>2,s=!d||t||d-e>2&&!f.getPartialFragment(e);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)&&!d)return;const t=Math.max(d,c.start||0)-e,i=!(null==g||!g.live)?2*g.targetduration:2,s=f.getPartialFragment(e);if(t>0&&(t<=i||s))return void(n.paused||this._trySkipBufferHole(s))}const p=r.detectStallWithCurrentTimeMs,m=self.performance.now(),v=this.waiting;if(null===a)return void(this.stalled=v>0&&m-v<p?v:m);const y=m-a;if(!o&&(y>=p||v)&&this.hls){var A;if("ended"===(null==(A=this.mediaSource)?void 0:A.readyState)&&(null==g||!g.live)&&Math.abs(e-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(gt.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}const E=tr.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(E,y)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(gt.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&s&&s.length>1&&e>s.end(0)){const i=tr.bufferedInfo(tr.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){const i=tr.timeRangesToArray(s),r=tr.bufferedInfo(i,t,0).bufferedIndex;if(r>-1&&r<i.length-1){const t=tr.bufferedInfo(i,e,0).bufferedIndex,s=i[r].end,n=i[r+1].start;if((-1===t||t>r)&&n-s<1&&e-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${s} -> ${n} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;const r=this.fragmentTracker.getPartialFragment(e)||void 0,a=tr.bufferInfo(this.media,e,0);this.hls.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t){var i,s;const{fragmentTracker:r,media:n}=this,a=null==(i=this.hls)?void 0:i.config;if(!n||!r||!a)return;const o=n.currentTime,l=null==(s=this.hls)?void 0:s.latestLevelDetails,h=r.getPartialFragment(o);if(h||null!=l&&l.live&&o<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const u=e.buffered;(u&&u.length>1&&e.len>a.maxBufferHole||e.nextStart&&e.nextStart-o<a.maxBufferHole)&&(t>1e3*a.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:r}=this;if(!s&&null!==r&&i&&t){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${as(e)})`);this.warn(s.message),t.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,r=null==(t=this.hls)?void 0:t.config;if(!s||!i||!r)return 0;const n=s.currentTime,a=tr.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=r.maxBufferHole,h=a.len>0&&a.len<1&&s.readyState<3,u=o-n;if(u>0&&(t||h)){if(u>r.maxBufferHole){let t=!1;if(0===n){const e=i.getAppendedFrag(0,At);e&&o<e.end&&(t=!0)}if(!t){const t=e||i.getAppendedFrag(n,At);if(t){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(_h(this.hls.inFlightFragments,o))return 0;let e=!1,s=t.end;for(;s<o;){const t=i.getPartialFragment(s);if(!t){e=!0;break}s+=t.duration}if(e)return 0}}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,s.currentTime=t,null==e||!e.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`);this.hls.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:e||void 0,buffer:a.len,bufferInfo:a})}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,r=null==t?void 0:t.config;if(!i||!r)return 0;const n=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){const a=n+(s+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),i.currentTime=a,t.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const i=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(i.message),t.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:e.len,bufferInfo:e})}}}function _h(e,t){const i=kh(e.main);if(i&&i.start<=t)return i;const s=kh(e.audio);return s&&s.start<=t?s:null}function kh(e){if(!e)return null;switch(e.state){case An:case yn:case kn:case Rn:return null}return e.frag}function Rh(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Ih(e,t,i,s,r){let n=new e(t,i,"");try{n.value=s,r&&(n.type=r)}catch(a){n=new e(t,i,as(r?Rt({type:r},s):s))}return n}const Dh=(()=>{const e=Rh();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Ph{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(gt.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e.on(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(gt.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(gt.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(gt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(gt.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(gt.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(gt.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(gt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&tl(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if("metadata"===i.kind&&"id3"===i.label)return Jo(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:s}}}=this;if(!i&&!s)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Rh();if(n)for(let e=0;e<r.length;e++){const t=r[e].type;if(t===oa.emsg&&!i||!s)continue;const a=sa(r[e].data);if(a){const i=r[e].pts;let s=i+r[e].duration;s>Dh&&(s=Dh);s-i<=0&&(s=i+.25);for(let e=0;e<a.length;e++){const r=a[e];if(!ra(r)){this.updateId3CueEnds(i,t);const e=Ih(n,i,s,r,t);e&&this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){var i;const s=null==(i=this.id3Track)?void 0:i.cues;if(s)for(let i=s.length;i--;){const r=s[i];r.type===t&&r.startTime<e&&r.endTime===Dh&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===s?e=>e.type===oa.audioId3&&o:"video"===s?e=>e.type===oa.emsg&&a:e=>e.type===oa.audioId3&&o||e.type===oa.emsg&&a,il(r,t,i,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:i}=this,{dateRanges:s}=e,r=Object.keys(s);let n=this.dateRangeCuesAppended;var a;if(i&&t)if(null!=(a=i.cues)&&a.length){const e=Object.keys(n).filter((e=>!r.includes(e)));for(let t=e.length;t--;){const s=e[t],r=n[s].cues;delete n[s],Object.keys(r).forEach((e=>{try{const t=r[e];t.removeEventListener("enter",this.onEventCueEnter),i.removeCue(t)}catch(e){}}))}}else n=this.dateRangeCuesAppended={};const o=e.fragments[e.fragments.length-1];if(0===r.length||!ht(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=Rh();for(let e=0;e<r.length;e++){const t=r[e],i=s[t],a=i.startTime,o=n[t],c=(null==o?void 0:o.cues)||{};let d=(null==o?void 0:o.durationKnown)||!1,f=Dh;const{duration:g,endDate:p}=i;if(p&&null!==g)f=a+g,d=!0;else if(i.endOnNext&&!d){const e=r.reduce(((e,t)=>{if(t!==i.id){const r=s[t];if(r.class===i.class&&r.startDate>i.startDate&&(!e||i.startDate<e.startDate))return r}return e}),null);e&&(f=e.startTime,d=!0)}const m=Object.keys(i.attr);for(let e=0;e<m.length;e++){const s=m[e];if("ID"===(u=s)||"CLASS"===u||"CUE"===u||"START-DATE"===u||"DURATION"===u||"END-DATE"===u||"END-ON-NEXT"===u)continue;const r=c[s];if(r)d&&!o.durationKnown?r.endTime=f:Math.abs(r.startTime-a)>.01&&(r.startTime=a,r.endTime=f);else if(l){let e=i.attr[s];ur(s)&&(h=e,e=Uint8Array.from(h.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const r=Ih(l,a,f,{key:s,data:e},oa.dateRange);r&&(r.id=t,this.id3Track.addCue(r),c[s]=r,this.hls.config.interstitialsController&&("X-ASSET-LIST"!==s&&"X-ASSET-URL"!==s||r.addEventListener("enter",this.onEventCueEnter)))}}n[t]={cues:c,dateRange:i,durationKnown:d}}var h,u}}class Ch{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,s=Math.min(t,Math.max(1,i));this.changeMediaPlaybackRate(e,s)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*s);const h=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,r=e-t-this.edgeStalled,n=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(gt.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(gt.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(gt.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(gt.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===ft.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(s=this.targetLatency)?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class wh extends oo{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.on(gt.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(gt.FRAG_BUFFERED,this.onFragBuffered,this),e.on(gt.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.off(gt.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(gt.FRAG_BUFFERED,this.onFragBuffered,this),e.off(gt.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{var t;const h=e.attrs;let{audioCodec:u,videoCodec:c}=e;u&&(e.audioCodec=u=$i(u,i)||void 0),0===(null==(t=c)?void 0:t.indexOf("avc1"))&&(c=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const i=t[e].split(".");if(i.length>2){let s=i.shift()+".";s+=parseInt(i.shift()).toString(16),s+=("000"+parseInt(i.shift()).toString(16)).slice(-4),t[e]=s}}return t.join(",")}(c));const{width:d,height:f,unknownCodecs:g}=e;let p=g?g.length:0;if(g)for(let t=p;t--;){const i=g[t];this.isAudioSupported(i)?(e.audioCodec=u=u?`${u},${i}`:i,p--,Ci.audio[u.substring(0,4)]=2):this.isVideoSupported(i)&&(e.videoCodec=c=c?`${c},${i}`:i,p--,Ci.video[c.substring(0,4)]=2)}if(a||(a=!(!d||!f)),o||(o=!!c),l||(l=!!u),p||u&&!this.isAudioSupported(u)||c&&!this.isVideoSupported(c))return void this.log(`Some or all CODECS not supported "${h.CODECS}"`);const{CODECS:m,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":A,RESOLUTION:E,"VIDEO-RANGE":T}=h,S=`${`${A||"."}-`}${e.bitrate}-${E}-${v}-${m}-${T}-${y}`;if(r[S])if(r[S].uri===e.url||e.attrs["PATHWAY-ID"])r[S].addGroupId("audio",h.AUDIO),r[S].addGroupId("text",h.SUBTITLES);else{const t=n[S]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const i=this.createLevel(e);r[S]=i,s.push(i)}else{const t=this.createLevel(e);r[S]=t,n[S]=1,s.push(t)}})),this.filterAndSortMediaOptions(s,t,a,o,l)}createLevel(e){const t=new ss(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=ji(e,[])}return t}isAudioSupported(e){return Oi(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Oi(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,r){let n=[],a=[],o=e;if((i||s)&&r&&(o=o.filter((({videoCodec:e,videoRange:t,width:i,height:s})=>{return(!!e||!(!i||!s))&&(!!(r=t)&&Qi.indexOf(r)>-1);var r}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${as(t.levels.map((e=>e.attrs.CODECS)).filter(((e,t,i)=>i.indexOf(e)===t)))}`,this.warn(i),e+=` (${i})`);const s=new Error(e);this.hls.trigger(gt.ERROR,{type:dt.MEDIA_ERROR,details:ft.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:s,reason:i})}}));t.audioTracks&&(n=t.audioTracks.filter((e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),Oh(n)),t.subtitles&&(a=t.subtitles,Oh(a));const l=o.slice(0);o.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Qi.indexOf(e.videoRange)-Qi.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const i=Fi(e.videoCodec),s=Fi(t.videoCodec);if(i!==s)return s-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const i=Ni(e.codecSet),s=Ni(t.codecSet);if(i!==s)return s-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===o[0].pathwayId){h=l[e];break}this._levels=o;for(let e=0;e<o.length;e++)if(o[e]===h){var u;this._firstLevel=e;const t=h.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${t}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const c=r&&!s,d=this.hls.config,f=!(!d.audioStreamController||!d.audioTrackController),g={levels:o,audioTracks:n,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:f&&!c&&n.some((e=>!!e.url))};this.hls.trigger(gt.MANIFEST_PARSED,g)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const i=new Error("invalid level idx"),s=e<0;if(this.hls.trigger(gt.ERROR,{type:dt.OTHER_ERROR,details:ft.LEVEL_SWITCH_ERROR,level:e,fatal:s,error:i,reason:i.message}),s)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&s&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(gt.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==s?void 0:s.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter((e=>-1!==t.indexOf(e)));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=i}}onError(e,t){!t.fatal&&t.context&&t.context.type===mt&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===At){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(s,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(gt.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const i=this._levels.filter(((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));cn(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(gt.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(gt.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Oh(e){const t={};e.forEach((e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}function xh(){return self.SourceBuffer||self.WebKitSourceBuffer}function Mh(){if(!Mt())return!1;const e=xh();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Fh extends Pn{constructor(e,t,i){super(e,t,i,"stream-controller",At),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!ht(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const i=this.getFwdBufferInfoAtPos(e,t,At,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.on(gt.LEVEL_LOADING,this.onLevelLoading,this),e.on(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.on(gt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(gt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(gt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(gt.BUFFER_CREATED,this.onBufferCreated,this),e.on(gt.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(gt.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(gt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(gt.MANIFEST_PARSED,this.onManifestParsed,this),e.off(gt.LEVEL_LOADED,this.onLevelLoaded,this),e.off(gt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(gt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(gt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(gt.BUFFER_CREATED,this.onBufferCreated,this),e.off(gt.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(gt.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(gt.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=s.startLevel;-1===e&&(s.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=s.firstAutoLevel),s.nextLoadLevel=e,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=An,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=yn}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Dn:{const{levels:e,level:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=An;break}if(this.hls.nextLoadLevel!==this.level){this.state=An;break}break}case Sn:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:e,level:t}=this,i=null==e?void 0:e[t];this.resetStartWhenNotLoaded(i||null),this.state=An}}}this.state===An&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(null===t||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==i||!i[r])return;const n=i[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(gt.BUFFER_EOS,e),void(this.state=kn)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===Dn||this.waitForLive(n))return this.level=r,this.state=Dn,void(this.startFragRequested=!1);const h=a.len,u=this.getMaxBufferLength(n.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let d=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&d&&Jt(d)&&this.fragmentTracker.getState(d)!==Fs){var f;const e=(null!=(f=this.backtrackFragment)?f:d).sn-l.startSN,t=l.fragments[e-1];t&&d.cc===t.cc&&(d=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(d&&this.isLoopLoading(d,c)){if(!d.gap){const e=this.audioOnly&&!this.altAudio?zt:Xt,t=(e===Xt?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,At)}d=this.getNextFragmentLoopLoading(d,l,a,At,u)}d&&(!d.initSegment||d.initSegment.data||this.bitrateTest||(d=d.initSegment),this.loadFragment(d,n,c))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===Os||s===Ms?Jt(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,At)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*r.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*s)+1:0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,s=Math.max(n.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case En:case Tn:case Sn:case Ln:case _n:this.state=An}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;ml(i,"playing",this.onMediaPlaying),ml(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(vl(i,"playing",this.onMediaPlaying),vl(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(gt.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;t.levels.forEach((e=>{const t=e.audioCodec;t&&(i=i||-1!==t.indexOf("mp4a.40.2"),s=s||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&s&&!function(){var e;const t=xh();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==An)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=Dn)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,h=this.fragCurrent;!h||this.state!==Tn&&this.state!==Sn||h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(a.live||null!=(i=l.details)&&i.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,u),this.hls.trigger(gt.LEVEL_UPDATED,{details:a,level:n}),this.state===Dn){if(this.waitForCdnTuneIn(a))return;this.state=An}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r<s||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&i.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,u=null==(t=i.initSegment)?void 0:t.data,c=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new ao(this.hls,At,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=-1!==f,p=new Js(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,g),m=this.initPTS[i.cc];d.push(r,u,c,l,i,s,o.totalduration,h,p,m)}onAudioTrackSwitching(e,t){const i=this.hls,s=2===this.altAudio;if(gs(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.fragmentTracker.removeAllFragments(),i.once(gt.BUFFER_FLUSHED,(()=>{var e;null==(e=this.hls)||e.trigger(gt.AUDIO_TRACK_SWITCHED,t)})),void i.trigger(gt.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(gt.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=gs(t.url,this.hls);if(i){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,r,n=!1;for(const e in i){const t=i[e];if("main"===t.id){if(r=e,s=t,"video"===e){const t=i[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,r=i.type===At;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===_n&&(this.state=An));const e=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),Jt(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const n=this.media;n&&(!this._hasEnoughToStart&&tr.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal)this.state=Rn;else switch(t.details){case ft.FRAG_GAP:case ft.FRAG_PARSING_ERROR:case ft.FRAG_DECRYPT_ERROR:case ft.FRAG_LOAD_ERROR:case ft.FRAG_LOAD_TIMEOUT:case ft.KEY_LOAD_ERROR:case ft.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(At,t);break;case ft.LEVEL_LOAD_ERROR:case ft.LEVEL_LOAD_TIMEOUT:case ft.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Dn||(null==(i=t.context)?void 0:i.type)!==mt||(this.state=An);break;case ft.BUFFER_ADD_CODEC_ERROR:case ft.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.resetLoadingState();break;case ft.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case ft.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=An,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==zt||!this.altAudio){const e=(t===Xt?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,At),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log(`could not seek to ${i}, already seeking at ${t}`);const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=tr.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${a}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((e=>{const{hls:i}=this,s=null==e?void 0:e.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=An,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(gt.FRAG_LOADED,e),s.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const i=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:u,text:c,id3:d,initSegment:f}=r,{details:g}=h,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Ln,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(h,f.tracks,e,n),s.trigger(gt.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;ht(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},s.trigger(gt.INIT_PTS_FOUND,{frag:o,id:i,initPTS:e,timescale:t}))}if(u&&g){p&&"audiovideo"===u.type&&this.logMuxedErr(o);const e=g.fragments[o.sn-1-g.startSN],t=o.sn===g.startSN,i=!e||o.cc>e.cc;if(!1!==r.independent){const{startPTS:e,endPTS:s,startDTS:r,endDTS:a}=u;if(l)l.elementaryStreams[u.type]={startPTS:e,endPTS:s,startDTS:r,endDTS:a};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),u.dropped&&u.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,l=u.firstKeyFramePTS?u.firstKeyFramePTS:e;if(!t&&n<l-this.config.maxBufferHole&&!i)return void this.backtrack(o);i&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,s,o.start,a,!0)}else t&&e-(g.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,e,s,r,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,t||i)}else{if(!t&&!i)return void this.backtrack(o);o.gap=!0}}if(p){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=p;l&&(l.elementaryStreams[zt]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),o.setElementaryStreamInfo(zt,e,t,i,s),this.bufferFragmentData(p,o,l,n)}if(g&&null!=d&&null!=(t=d.samples)&&t.length){const e={id:i,frag:o,details:g,samples:d.samples};s.trigger(gt.FRAG_PARSING_METADATA,e)}if(g&&c){const e={id:i,frag:o,details:g,samples:c.samples};s.trigger(gt.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${Jt(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==Ln)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:a}=t;if(r){let i=Gi(r.codec,e.audioCodec);"mp4a"===i&&(i="mp4a.40.5");const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===s.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),e.audioCodec&&e.audioCodec!==i&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${i}"`),r.levelCodec=i,r.id=At,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${e.audioCodec||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=At;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(gt.BUFFER_CODECS,t),!this.hls)return;o.forEach((e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(gt.BUFFER_APPENDING,{type:e,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,At)}get maxBufferLength(){const{levels:e,level:t}=this,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=An}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const i=e.currentTime;if(tr.isBuffered(e,i)?t=this.getAppendedFrag(i):tr.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,i=t.level;e&&t.sn===e.sn&&e.level===i||(this.fragPlaying=t,this.hls.trigger(gt.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(gt.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return ht(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(ht(t)){const e=this.getLevelDetails(),i=this.currentFrag||(e?ms(null,e.fragments,t):null);if(i){const e=i.programDateTime;if(null!==e){const s=e+1e3*(t-i.start);return new Date(s)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Nh{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[i].loader;if(s){var t;if(e&&e!==(null==(t=s.context)?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=ft.KEY_LOAD_ERROR,i,s,r){return new Qs({type:dt.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=e;for(let e=0;e<t.length;e++){const r=t[e];if(s<=r.cc&&("initSegment"===i||"initSegment"===r.sn||i<r.sn)){this.emeController.selectKeySystemFormat(r).then((e=>{r.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const i=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,ft.KEY_LOAD_ERROR,i))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,ft.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(i=a)&&i.decryptdata.key)return r.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(s=a)&&s.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(r.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,ft.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(i);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,i)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=new(0,i.loader)(i);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise(((r,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,s)=>{const{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,ft.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(e,i,s,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,ft.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),s,Rt({url:a.url,data:void 0},e)))},onTimeout:(e,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,ft.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(e,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,ft.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(a,l,h)}))}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],r&&r.destroy()}}function Uh(e){const{type:t}=e;switch(t){case vt:return Et;case yt:return Tt;default:return At}}function Bh(e,t){let i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}class $h{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.on(gt.LEVEL_LOADING,this.onLevelLoading,this),e.on(gt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(gt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(gt.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(gt.MANIFEST_LOADING,this.onManifestLoading,this),e.off(gt.LEVEL_LOADING,this.onLevelLoading,this),e.off(gt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(gt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(gt.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,r=new(i||s)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:pt,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:mt,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:vt,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:yt,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const i=this.loaders[mt];if(i){const e=i.context;e&&!t.levels.some((t=>t===e.levelOrTrack))&&(i.abort(),delete this.loaders[mt])}}load(e){var t;const i=this.hls.config;let s,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,i=r.context;if(i&&i.levelOrTrack===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives))return void(i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(s=e.type===pt?i.manifestLoadPolicy.default:_t({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),ht(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===mt&&null!==e.level?t=this.hls.levels[e.level].details:e.type===vt&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===yt&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,i=t.targetduration;if(e&&i){const t=1e3*Math.max(3*e,.8*i);s=_t({},s,{maxTimeToFirstByteMs:Math.min(t,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,s.maxTimeToFirstByteMs)})}}}const n=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Kr.isMediaPlaylist(n)||i.type!==pt?this.handleTrackOrLevelPlaylist(e,t,i,s||null,r):this.handleMasterPlaylist(e,t,i,s)):this.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),s||null,t)},onError:(e,t,i,s)=>{this.handleNetworkError(t,i,!1,e,s)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};r.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const r=this.hls,n=e.data,a=Bh(e,i),o=Kr.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,i,o.playlistParsingError,s,t);const{contentSteering:l,levels:h,sessionData:u,sessionKeys:c,startTimeOffset:d,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=Kr.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((e=>!e.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"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new hr({}),bitrate:0,url:""}))}r.trigger(gt.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:m,contentSteering:l,url:a,stats:t,networkDetails:s,sessionData:u,sessionKeys:c,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,s,r){const n=this.hls,{id:a,level:o,type:l}=i,h=Bh(e,i),u=ht(o)?o:ht(a)?a:0,c=Uh(i),d=Kr.parseLevelPlaylist(e.data,h,u,c,0,this.variableList);if(l===pt){const e={attrs:new hr({}),bitrate:0,details:d,name:"",url:h};d.requestScheduled=t.loading.start+on(d,0),n.trigger(gt.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=d,this.handlePlaylistLoaded(d,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(gt.ERROR,{type:dt.NETWORK_ERROR,details:ft.MANIFEST_PARSING_ERROR,fatal:t.type===pt,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===mt?n+=`: ${e.level} id: ${e.id}`:e.type!==vt&&e.type!==yt||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=ft.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case pt:o=i?ft.MANIFEST_LOAD_TIMEOUT:ft.MANIFEST_LOAD_ERROR,l=!0;break;case mt:o=i?ft.LEVEL_LOAD_TIMEOUT:ft.LEVEL_LOAD_ERROR,l=!1;break;case vt:o=i?ft.AUDIO_TRACK_LOAD_TIMEOUT:ft.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case yt:o=i?ft.SUBTITLE_TRACK_LOAD_TIMEOUT:ft.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const u={type:dt.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:r};if(s){const i=(null==t?void 0:t.url)||e.url;u.response=Rt({url:i,data:void 0},s)}this.hls.trigger(gt.ERROR,u)}handlePlaylistLoaded(e,t,i,s,r,n){const a=this.hls,{type:o,level:l,id:h,groupId:u,deliveryDirectives:c}=s,d=Bh(t,s),f=Uh(s),g="number"==typeof s.level&&f===At?l:void 0;if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(gt.ERROR,{type:dt.NETWORK_ERROR,details:ft.LEVEL_EMPTY_ERROR,fatal:!1,url:d,error:n,reason:n.message,response:t,context:s,level:g,parent:f,networkDetails:r,stats:i})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(p),!a.config.ignorePlaylistParsingErrors)return void a.trigger(gt.ERROR,{type:dt.NETWORK_ERROR,details:ft.LEVEL_PARSING_ERROR,fatal:!1,url:d,error:p,reason:p.message,response:t,context:s,level:g,parent:f,networkDetails:r,stats:i});e.playlistParsingError=null}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case pt:case mt:a.trigger(gt.LEVEL_LOADED,{details:e,levelInfo:s.levelOrTrack||a.levels[0],level:g||0,id:h||0,stats:i,networkDetails:r,deliveryDirectives:c,withoutMultiVariant:o===pt});break;case vt:a.trigger(gt.AUDIO_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:h||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:c});break;case yt:a.trigger(gt.SUBTITLE_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:h||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:c})}}}class Gh{static get version(){return Nn}static isMSESupported(){return Mh()}static isSupported(){return function(){if(!Mh())return!1;const e=Mt();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(Mi(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(Mi(t,"audio")))))}()}static getMediaSource(){return Mt()}static get Events(){return gt}static get MetadataSchema(){return oa}static get ErrorTypes(){return dt}static get ErrorDetails(){return ft}static get DefaultConfig(){return Gh.defaultConfig?Gh.defaultConfig:Th}static set DefaultConfig(e){Gh.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Fn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,i){const s=Ct();if("object"==typeof console&&!0===e||"object"==typeof e){const r=["debug","log","info","warn","error"];r.forEach((t=>{s[t]=wt(t,e,i)}));try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.6.2`)}catch(e){return Ct()}r.forEach((t=>{Ot[t]=wt(t,e)}))}else _t(Ot,s);return s}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Sh(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach((i=>{const r=`${e}Loading${i}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=s[n].default;switch(t[n]={default:e},i){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${as(t[n])}`)})),Rt(Rt({},s),t)}(Gh.DefaultConfig,e,t);this.userConfig=e,i.progressive&&bh(i,t);const{abrController:s,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=i,l=new a(this),h=this.abrController=new s(this),u=new Ns(this),c=i.interstitialsController,d=c?this.interstitialsController=new c(this,Gh):null,f=this.bufferController=new r(this,u),g=this.capLevelController=new n(this),p=new o(this),m=new $h(this),v=i.contentSteeringController,y=v?new v(this):null,A=this.levelController=new wh(this,y),E=new Ph(this),T=new Nh(this.config),S=this.streamController=new Fh(this,u,T),b=this.gapController=new Lh(this,u);g.setStreamController(S),p.setStreamController(S);const L=[m,A,S];d&&L.splice(1,0,d),y&&L.splice(1,0,y),this.networkControllers=L;const _=[h,f,b,g,p,E,u];this.audioTrackController=this.createController(i.audioTrackController,L);const k=i.audioStreamController;k&&L.push(this.audioStreamController=new k(this,u,T)),this.subtitleTrackController=this.createController(i.subtitleTrackController,L);const R=i.subtitleStreamController;R&&L.push(this.subtititleStreamController=new R(this,u,T)),this.createController(i.timelineController,_),T.emeController=this.emeController=this.createController(i.emeController,_),this.cmcdController=this.createController(i.cmcdController,_),this.latencyController=this.createController(Ch,_),this.coreComponents=_,L.push(l);const I=l.onErrorOut;"function"==typeof I&&this.on(gt.ERROR,I,l),this.on(gt.MANIFEST_LOADED,m.onManifestLoaded,m)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const i=e===gt.ERROR;this.trigger(gt.ERROR,{type:dt.OTHER_ERROR,details:ft.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(gt.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(gt.ERROR,{type:dt.OTHER_ERROR,details:ft.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(gt.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(gt.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(gt.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,s=this._url=Wt.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(gt.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((e=>{e.resumeBuffering&&e.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((e=>{e.pauseBuffering&&e.pauseBuffering()})))}get inFlightFragments(){const e={[At]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Et]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Tt]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)}))}}}()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return Xi.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(s=-1===t&&null!=e&&e.length?e.length-1:t,i)for(let t=s;t--;){const s=e[t].attrs["HDCP-LEVEL"];if(s&&s<=i)return t}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return zi(e,ls(t),navigator.mediaCapabilities)}}Gh.defaultConfig=void 0;var Kh=le,Vh=he;Ee.register("PLAYBACK_FRAGMENT_CHANGED"),Ee.register("PLAYBACK_FRAGMENT_PARSING_METADATA");var Hh=function(e){function s(){var e;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,s);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return(e=t(this,s,[].concat(r))).options.hlsPlayback=l(l({},e.defaultOptions),e.options.hlsPlayback),e._timeUpdateThrottleDelay=200,e._timeUpdateFiringRate=.2,e._durationChangeMinOffset=.5,e._setInitialState(),e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&h(e,t)}(s,e),r=s,a=[{key:"HLSJS",get:function(){return Gh}}],(n=[{key:"name",get:function(){return"hls"}},{key:"supportedVersion",get:function(){return{min:"0.12.0"}}},{key:"levels",get:function(){return this._levels||[]}},{key:"currentLevel",get:function(){return null===this._currentLevel||void 0===this._currentLevel?-1:this._currentLevel},set:function(e){this._currentLevel=e,this.trigger(Ee.PLAYBACK_LEVEL_SWITCH_START),this.options.playback.hlsUseNextLevel?this._hls.nextLevel=this._currentLevel:this._hls.currentLevel=this._currentLevel}},{key:"isReady",get:function(){return this._isReadyState}},{key:"latency",get:function(){return this._hls.latency}},{key:"liveSyncPosition",get:function(){return this._hls.liveSyncPosition}},{key:"currentProgramDateTime",get:function(){return this._hls.playingDate}},{key:"_startTime",get:function(){return this._playbackType===Ue.LIVE&&"EVENT"!==this._playlistType?this._extrapolatedStartTime:this._playableRegionStartTime}},{key:"_now",get:function(){return Kh()}},{key:"_extrapolatedStartTime",get:function(){if(!this._localStartTimeCorrelation)return this._playableRegionStartTime;var e=this._localStartTimeCorrelation,t=this._now-e.local,i=(e.remote+t)/1e3;return Math.min(i,this._playableRegionStartTime+this._extrapolatedWindowDuration)}},{key:"_extrapolatedEndTime",get:function(){var e=this._playableRegionStartTime+this._playableRegionDuration;if(!this._localEndTimeCorrelation)return e;var t=this._localEndTimeCorrelation,i=this._now-t.local,s=(t.remote+i)/1e3;return Math.max(e-this._extrapolatedWindowDuration,Math.min(s,e))}},{key:"_duration",get:function(){return this._extrapolatedEndTime-this._startTime}},{key:"_extrapolatedWindowDuration",get:function(){return null===this._segmentTargetDuration?0:this._extrapolatedWindowNumSegments*this._segmentTargetDuration}},{key:"bandwidthEstimate",get:function(){return this._hls&&this._hls.bandwidthEstimate}},{key:"defaultOptions",get:function(){return{preload:!0}}},{key:"customListeners",get:function(){return this.options.hlsPlayback&&this.options.hlsPlayback.customListeners||[]}},{key:"sourceMedia",get:function(){return this.options.src}},{key:"currentTimestamp",get:function(){return this._currentFragment?(this._currentFragment.programDateTime+1e3*(this.el.currentTime-this._currentFragment.start))/1e3:null}},{key:"_setInitialState",value:function(){this._minDvrSize=void 0===this.options.hlsMinimumDvrSize?60:this.options.hlsMinimumDvrSize,this._extrapolatedWindowNumSegments=this.options.playback&&void 0!==this.options.playback.extrapolatedWindowNumSegments?this.options.playback.extrapolatedWindowNumSegments:2,this._playbackType=Ue.VOD,this._lastTimeUpdate={current:0,total:0,firstFragDateTime:0},this._lastTimeUpdateFiredTime=0,this._lastDuration=null,this._playableRegionStartTime=0,this._localStartTimeCorrelation=null,this._localEndTimeCorrelation=null,this._playableRegionDuration=0,this._programDateTime=0,this._durationExcludesAfterLiveSyncPoint=!1,this._segmentTargetDuration=null,this._playlistType=null,this._recoverAttemptsRemaining=this.options.hlsRecoverAttempts||16}},{key:"_setup",value:function(){this._destroyHLSInstance(),this._createHLSInstance(),this._listenHLSEvents(),this._attachHLSMedia()}},{key:"_destroyHLSInstance",value:function(){this._hls&&(this._manifestLoading=!1,this._ccIsSetup=!1,this._ccTracksUpdated=!1,this._setInitialState(),this._hls.destroy(),this._hls=null)}},{key:"_createHLSInstance",value:function(){var e=l({},this.options.playback.hlsjsConfig);this._hls=new Gh(e)}},{key:"_attachHLSMedia",value:function(){this._hls&&this._hls.attachMedia(this.el)}},{key:"_listenHLSEvents",value:function(){var e=this;this._hls&&(this._hls.once(Gh.Events.MEDIA_ATTACHED,(function(){e.options.hlsPlayback.preload&&e._hls.loadSource(e.options.src)})),this._hls.on(Gh.Events.MANIFEST_LOADING,(function(){return e._manifestLoading=!0})),this._hls.on(Gh.Events.LEVEL_LOADED,(function(t,i){return e._updatePlaybackType(t,i)})),this._hls.on(Gh.Events.LEVEL_UPDATED,(function(t,i){return e._onLevelUpdated(t,i)})),this._hls.on(Gh.Events.LEVEL_SWITCHED,(function(t,i){return e._onLevelSwitch(t,i)})),this._hls.on(Gh.Events.FRAG_CHANGED,(function(t,i){return e._onFragmentChanged(t,i)})),this._hls.on(Gh.Events.FRAG_LOADED,(function(t,i){return e._onFragmentLoaded(t,i)})),this._hls.on(Gh.Events.FRAG_BUFFERED,(function(t,i){return e._onFragmentBuffered(t,i)})),this._hls.on(Gh.Events.FRAG_PARSING_METADATA,(function(t,i){return e._onFragmentParsingMetadata(t,i)})),this._hls.on(Gh.Events.ERROR,(function(t,i){return e._onHLSJSError(t,i)})),this._hls.on(Gh.Events.SUBTITLE_TRACK_LOADED,(function(t,i){return e._onSubtitleLoaded(t,i)})),this._hls.on(Gh.Events.SUBTITLE_TRACKS_UPDATED,(function(){return e._ccTracksUpdated=!0})),this.bindCustomListeners())}},{key:"bindCustomListeners",value:function(){var e=this;this.customListeners.forEach((function(t){var i=t.eventName,s=t.once?"once":"on";i&&e._hls["".concat(s)](i,t.callback)}))}},{key:"unbindCustomListeners",value:function(){var e=this;this.customListeners.forEach((function(t){var i=t.eventName;i&&e._hls.off(i,t.callback)}))}},{key:"_onFragmentParsingMetadata",value:function(e,t){this.trigger(Ee.Custom.PLAYBACK_FRAGMENT_PARSING_METADATA,{evt:e,data:t})}},{key:"render",value:function(){return this._ready(),u(s,"render",this,3)([])}},{key:"_ready",value:function(){this._isReadyState||(!this._hls&&this._setup(),this._isReadyState=!0,this.trigger(Ee.PLAYBACK_READY,this.name))}},{key:"_recover",value:function(e,t,i){if(this._recoveredDecodingError)if(this._recoveredAudioCodecError){pe.error("hlsjs: failed to recover",{evt:e,data:t}),i.level=xe.Levels.FATAL;var s=this.createError(i);this.trigger(Ee.PLAYBACK_ERROR,s),this.stop()}else this._recoveredAudioCodecError=!0,this._hls.swapAudioCodec(),this._hls.recoverMediaError(),this.play();else this._recoveredDecodingError=!0,this._hls.recoverMediaError(),this.play()}},{key:"_setupSrc",value:function(e){}},{key:"_startTimeUpdateTimer",value:function(){var e=this;this._timeUpdateTimer||(this._timeUpdateTimer=setInterval((function(){e._onDurationChange(),e._onTimeUpdate()}),100))}},{key:"_stopTimeUpdateTimer",value:function(){this._timeUpdateTimer&&(clearInterval(this._timeUpdateTimer),this._timeUpdateTimer=null)}},{key:"getProgramDateTime",value:function(){return this._programDateTime}},{key:"getDuration",value:function(){return this._duration}},{key:"getCurrentTime",value:function(){return Math.max(0,this.el.currentTime-this._startTime)}},{key:"getStartTimeOffset",value:function(){return this._startTime}},{key:"seekPercentage",value:function(e){var t=e>0?this._duration*(e/100):this._duration;this.seek(t)}},{key:"seek",value:function(e){e<0&&(pe.warn("Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point."),e=this.getDuration()),e+=this._startTime,this.el.currentTime=e}},{key:"seekToLivePoint",value:function(){this.seek(this.getDuration())}},{key:"_updateSettings",value:function(){this._playbackType===Ue.VOD?this.settings.left=["playpause","position","duration"]:this.dvrEnabled?this.settings.left=["playpause"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(Ee.PLAYBACK_SETTINGSUPDATE)}},{key:"_onHLSJSError",value:function(e,t){var i,s={code:"".concat(t.type,"_").concat(t.details),description:"".concat(this.name," error: type: ").concat(t.type,", details: ").concat(t.details),raw:t};if(t.response&&(s.description+=", response: ".concat(JSON.stringify(t.response))),t.fatal)if(this._recoverAttemptsRemaining>0)switch(this._recoverAttemptsRemaining-=1,t.type){case Gh.ErrorTypes.NETWORK_ERROR:switch(t.details){case Gh.ErrorDetails.MANIFEST_LOAD_ERROR:case Gh.ErrorDetails.MANIFEST_LOAD_TIMEOUT:case Gh.ErrorDetails.MANIFEST_PARSING_ERROR:case Gh.ErrorDetails.LEVEL_LOAD_ERROR:case Gh.ErrorDetails.LEVEL_LOAD_TIMEOUT:pe.error("hlsjs: unrecoverable network fatal error.",{evt:e,data:t}),i=this.createError(s),this.trigger(Ee.PLAYBACK_ERROR,i),this.stop();break;default:pe.warn("hlsjs: trying to recover from network error.",{evt:e,data:t}),s.level=xe.Levels.WARN,this._hls.startLoad()}break;case Gh.ErrorTypes.MEDIA_ERROR:pe.warn("hlsjs: trying to recover from media error.",{evt:e,data:t}),s.level=xe.Levels.WARN,this._recover(e,t,s);break;default:pe.error("hlsjs: could not recover from error.",{evt:e,data:t}),i=this.createError(s),this.trigger(Ee.PLAYBACK_ERROR,i),this.stop()}else pe.error("hlsjs: could not recover from error after maximum number of attempts.",{evt:e,data:t}),i=this.createError(s),this.trigger(Ee.PLAYBACK_ERROR,i),this.stop();else{if(this.options.playback.triggerFatalErrorOnResourceDenied&&this._keyIsDenied(t))return pe.error("hlsjs: could not load decrypt key.",{evt:e,data:t}),i=this.createError(s),this.trigger(Ee.PLAYBACK_ERROR,i),void this.stop();s.level=xe.Levels.WARN,pe.warn("hlsjs: non-fatal error occurred",{evt:e,data:t})}}},{key:"_keyIsDenied",value:function(e){return e.type===Gh.ErrorTypes.NETWORK_ERROR&&e.details===Gh.ErrorDetails.KEY_LOAD_ERROR&&e.response&&e.response.code>=400}},{key:"_onTimeUpdate",value:function(){var e={current:this.getCurrentTime(),total:this.getDuration(),firstFragDateTime:this.getProgramDateTime()};this._shouldThrottleTimeUpdate(e)||(this._lastTimeUpdate=e,this._lastTimeUpdateFiredTime=this._now,this.trigger(Ee.PLAYBACK_TIMEUPDATE,e,this.name))}},{key:"_shouldThrottleTimeUpdate",value:function(e){var t=Math.abs(e.current-this._lastTimeUpdate.current)<this._timeUpdateFiringRate,i=Math.abs(e.total-this._lastTimeUpdate.total)<this._durationChangeMinOffset,s=e.firstFragDateTime===this._lastTimeUpdate.firstFragDateTime,r=t&&i&&s,n=this._now-this._lastTimeUpdateFiredTime<this._timeUpdateThrottleDelay;return r&&n}},{key:"_onDurationChange",value:function(){var e=this.getDuration();Math.abs(this._lastDuration-e)<this._durationChangeMinOffset||(this._lastDuration=e,u(s,"_onDurationChange",this,3)([]))}},{key:"_onProgress",value:function(){if(this.el.buffered.length){for(var e=[],t=0,i=0;i<this.el.buffered.length;i++)e=[].concat(c(e),[{start:Math.max(0,this.el.buffered.start(i)-this._playableRegionStartTime),end:Math.max(0,this.el.buffered.end(i)-this._playableRegionStartTime)}]),this.el.currentTime>=e[i].start&&this.el.currentTime<=e[i].end&&(t=i);var s={start:e[t].start,current:e[t].end,total:this.getDuration()};this.trigger(Ee.PLAYBACK_PROGRESS,s,e)}}},{key:"load",value:function(e){this._stopTimeUpdateTimer(),this.options.src=e,this._setup()}},{key:"play",value:function(){!this._hls&&this._setup(),!this._manifestLoading&&!this.options.hlsPlayback.preload&&this._hls.loadSource(this.options.src),u(s,"play",this,3)([]),this._startTimeUpdateTimer()}},{key:"pause",value:function(){this._hls&&this.el.pause()}},{key:"stop",value:function(){this._stopTimeUpdateTimer(),this._hls&&u(s,"stop",this,3)([]),this._destroyHLSInstance()}},{key:"destroy",value:function(){this._stopTimeUpdateTimer(),this._destroyHLSInstance(),u(s,"destroy",this,3)([])}},{key:"_updatePlaybackType",value:function(e,t){this._playbackType=t.details.live?Ue.LIVE:Ue.VOD,this._onLevelUpdated(e,t),this._ccTracksUpdated&&this._playbackType===Ue.LIVE&&this.hasClosedCaptionsTracks&&this._onSubtitleLoaded()}},{key:"_fillLevels",value:function(){this._levels=this._hls.levels.map((function(e,t){return{id:t,level:e,label:"".concat(e.bitrate/1e3,"Kbps")}})),this.trigger(Ee.PLAYBACK_LEVELS_AVAILABLE,this._levels)}},{key:"_onLevelUpdated",value:function(e,t){this._segmentTargetDuration=t.details.targetduration,this._playlistType=t.details.type||null;var i=!1,s=!1,r=t.details.fragments,n=this._playableRegionStartTime,a=this._playableRegionDuration;if(0!==r.length){if(r[0].rawProgramDateTime&&(this._programDateTime=r[0].rawProgramDateTime),this._playableRegionStartTime!==r[0].start&&(i=!0,this._playableRegionStartTime=r[0].start),i)if(this._localStartTimeCorrelation){var o=this._localStartTimeCorrelation,l=this._now-o.local,h=(o.remote+l)/1e3;h<r[0].start?this._localStartTimeCorrelation={local:this._now,remote:1e3*r[0].start}:h>n+this._extrapolatedWindowDuration&&(this._localStartTimeCorrelation={local:this._now,remote:1e3*Math.max(r[0].start,n+this._extrapolatedWindowDuration)})}else this._localStartTimeCorrelation={local:this._now,remote:1e3*(r[0].start+this._extrapolatedWindowDuration/2)};var u=t.details.totalduration;if(this._playbackType===Ue.LIVE){var c=t.details.targetduration*((this.options.playback.hlsjsConfig||{}).liveSyncDurationCount||Gh.DefaultConfig.liveSyncDurationCount);c<=u?(u-=c,this._durationExcludesAfterLiveSyncPoint=!0):this._durationExcludesAfterLiveSyncPoint=!1}u!==this._playableRegionDuration&&(s=!0,this._playableRegionDuration=u);var d=r[0].start+u,f=n+a;if(d!==f)if(this._localEndTimeCorrelation){var g=this._localEndTimeCorrelation,p=this._now-g.local,m=(g.remote+p)/1e3;m>d?this._localEndTimeCorrelation={local:this._now,remote:1e3*d}:m<d-this._extrapolatedWindowDuration?this._localEndTimeCorrelation={local:this._now,remote:1e3*(d-this._extrapolatedWindowDuration)}:m>f&&(this._localEndTimeCorrelation={local:this._now,remote:1e3*f})}else this._localEndTimeCorrelation={local:this._now,remote:1e3*d};s&&this._onDurationChange(),i&&this._onProgress()}}},{key:"_onFragmentChanged",value:function(e,t){this._currentFragment=t.frag,this.trigger(Ee.Custom.PLAYBACK_FRAGMENT_CHANGED,t)}},{key:"_onFragmentLoaded",value:function(e,t){this.trigger(Ee.PLAYBACK_FRAGMENT_LOADED,t)}},{key:"_onFragmentBuffered",value:function(e,t){this.trigger(Ee.PLAYBACK_FRAGMENT_BUFFERED,t)}},{key:"_onSubtitleLoaded",value:function(){if(!this._ccIsSetup){this.trigger(Ee.PLAYBACK_SUBTITLE_AVAILABLE);var e=this._playbackType===Ue.LIVE?-1:this.closedCaptionsTrackId;this.closedCaptionsTrackId=e,this._ccIsSetup=!0}}},{key:"_onLevelSwitch",value:function(e,t){this.levels.length||this._fillLevels(),this.trigger(Ee.PLAYBACK_LEVEL_SWITCH_END),this.trigger(Ee.PLAYBACK_LEVEL_SWITCH,t);var i=this._hls.levels[t.level];i&&(this.highDefinition=i.height>=720||i.bitrate/1e3>=2e3,this.trigger(Ee.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinition),this.trigger(Ee.PLAYBACK_BITRATE,{height:i.height,width:i.width,bandwidth:i.bitrate,bitrate:i.bitrate,level:t.level}))}},{key:"dvrEnabled",get:function(){return this._durationExcludesAfterLiveSyncPoint&&this._duration>=this._minDvrSize&&this.getPlaybackType()===Ue.LIVE}},{key:"getPlaybackType",value:function(){return this._playbackType}},{key:"isSeekEnabled",value:function(){return this._playbackType===Ue.VOD||this.dvrEnabled}}])&&i(r.prototype,n),a&&i(r,a),Object.defineProperty(r,"prototype",{writable:!1}),r;var r,n,a}(st);return Hh.canPlay=function(e,t){var i=e.split("?")[0].match(/.*\.(.*)$/)||[],s=i.length>1&&"m3u8"===i[1].toLowerCase()||Vh(t,["application/vnd.apple.mpegurl","application/x-mpegURL"]);return!(!Gh.isSupported()||!s)},Hh}();
2
2
  //# sourceMappingURL=hlsjs-playback.min.js.map